Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e6d856b93e | ||
|
|
ef843d400e | ||
|
|
654ca0da91 | ||
|
|
aa66e08034 | ||
|
|
268d4f7cf8 | ||
|
|
0de5742b04 | ||
|
|
321251907a | ||
|
|
d5c86c9af6 | ||
|
|
b500a36a94 | ||
|
|
a75a9b427f | ||
|
|
1310045629 | ||
|
|
579a69eb77 | ||
|
|
9ee8c4f543 | ||
|
|
55560f5116 | ||
|
|
f98679d217 | ||
|
|
5c9cfcd4c3 | ||
|
|
e6254a8451 | ||
|
|
3710ddb611 | ||
|
|
3fce14bbcf | ||
|
|
d430a0624b | ||
|
|
b04132d8c8 | ||
|
|
b577cb5326 | ||
|
|
fc9660f238 | ||
|
|
b403ca3183 | ||
|
|
f34dd0a91f | ||
|
|
33791cdfe5 | ||
|
|
fdcb05d3f6 | ||
|
|
2121682546 | ||
|
|
d2b00e6550 | ||
|
|
e0facb03bd | ||
|
|
73152abe81 | ||
|
|
c5bfff1583 | ||
|
|
040011dbc7 | ||
|
|
858116d836 | ||
|
|
ff34d2c708 | ||
|
|
99cd1c560e | ||
|
|
01f01c5e6b | ||
|
|
de7cfba261 | ||
|
|
1da30f776e | ||
|
|
11aca1fcc6 | ||
|
|
95c50053bc | ||
|
|
da9cbcc98c | ||
|
|
b9ea1487b3 | ||
|
|
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
@@ -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,202 @@
|
||||
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 changed lines (additions + deletions).",
|
||||
},
|
||||
{
|
||||
name: "size:S",
|
||||
color: "5ebd3e",
|
||||
description: "10-29 changed lines (additions + deletions).",
|
||||
},
|
||||
{
|
||||
name: "size:M",
|
||||
color: "fbca04",
|
||||
description: "30-99 changed lines (additions + deletions).",
|
||||
},
|
||||
{
|
||||
name: "size:L",
|
||||
color: "fe7d37",
|
||||
description: "100-499 changed lines (additions + deletions).",
|
||||
},
|
||||
{
|
||||
name: "size:XL",
|
||||
color: "d93f0b",
|
||||
description: "500-999 changed lines (additions + deletions).",
|
||||
},
|
||||
{
|
||||
name: "size:XXL",
|
||||
color: "b60205",
|
||||
description: "1,000+ changed lines (additions + deletions).",
|
||||
},
|
||||
];
|
||||
|
||||
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 additions = context.payload.pull_request.additions ?? 0;
|
||||
const deletions = context.payload.pull_request.deletions ?? 0;
|
||||
const changedLines = additions + deletions;
|
||||
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
|
||||
|
||||
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
|
||||
|
||||
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 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],
|
||||
});
|
||||
}
|
||||
|
||||
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
|
||||
@@ -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: ${{ vars.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,8 @@ build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.9",
|
||||
"version": "0.0.10",
|
||||
"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.
|
||||
}
|
||||
}
|
||||
@@ -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";
|
||||
@@ -535,7 +535,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 +640,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),
|
||||
];
|
||||
|
||||
@@ -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:"
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { execFileSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
ProviderKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -205,7 +206,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex";
|
||||
readonly provider?: ProviderKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -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,9 +5,11 @@ import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
@@ -36,7 +38,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();
|
||||
@@ -105,6 +107,8 @@ function withRealCodexHarness<A, E>(
|
||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = nowIso();
|
||||
const provider = harness.adapterHarness?.provider ?? "codex";
|
||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
@@ -112,7 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModel,
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -122,7 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5-codex",
|
||||
model: defaultModel,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -882,3 +886,420 @@ it.live(
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Claude first turn.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-initial",
|
||||
messageId: "msg-user-claude-initial",
|
||||
text: "Use Claude",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeAgent" &&
|
||||
entry.session.status === "ready" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
|
||||
),
|
||||
);
|
||||
assert.equal(thread.session?.providerName, "claudeAgent");
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn before restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-1",
|
||||
messageId: "msg-user-claude-recover-1",
|
||||
text: "Before restart",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness!.adapter.stopAll();
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness!.listActiveSessionIds(),
|
||||
(sessionIds) => sessionIds.length === 0,
|
||||
"provider stopAll",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn after restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-recover-2",
|
||||
messageId: "msg-user-claude-recover-2",
|
||||
text: "After restart",
|
||||
});
|
||||
yield* waitForSync(
|
||||
() => harness.adapterHarness!.getStartCount(),
|
||||
(count) => count === 2,
|
||||
"claude provider recovery start",
|
||||
);
|
||||
|
||||
const recoveredThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.providerName === "claudeAgent" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "user" && message.text === "After restart",
|
||||
) &&
|
||||
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
);
|
||||
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Approve Claude tool call",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-approval",
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
entry.activities.some((activity) => activity.kind === "approval.requested"),
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
yield* harness.waitForPendingApproval(
|
||||
"req-approval-1",
|
||||
(row) => row.status === "resolved" && row.decision === "accept",
|
||||
);
|
||||
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
|
||||
(responses) => responses.length === 1,
|
||||
"claude provider approval response",
|
||||
);
|
||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Long running output.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-interrupt",
|
||||
messageId: "msg-user-claude-interrupt",
|
||||
text: "Start long turn",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.session?.threadId === "thread-1",
|
||||
);
|
||||
assert.equal(thread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
yield* harness.waitForDomainEvent(
|
||||
(event) => event.type === "thread.turn-interrupt-requested",
|
||||
);
|
||||
|
||||
const interruptCalls = yield* waitForSync(
|
||||
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
|
||||
(calls) => calls.length === 1,
|
||||
"claude provider interrupt call",
|
||||
);
|
||||
assert.equal(interruptCalls.length, 1);
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
|
||||
withHarness(
|
||||
(harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v2\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-1",
|
||||
messageId: "msg-user-claude-revert-1",
|
||||
text: "First Claude edit",
|
||||
provider: "claudeAgent",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
|
||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v3\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
mutateWorkspace: ({ cwd }) =>
|
||||
Effect.sync(() => {
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
}),
|
||||
});
|
||||
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-claude-revert-2",
|
||||
messageId: "msg-user-claude-revert-2",
|
||||
text: "Second Claude edit",
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.latestTurn?.turnId === "turn-2" &&
|
||||
entry.checkpoints.length === 2 &&
|
||||
entry.session?.providerName === "claudeAgent",
|
||||
);
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const revertedThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
|
||||
);
|
||||
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||
}),
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.9",
|
||||
"version": "0.0.10",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
@@ -22,6 +22,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 +45,6 @@
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13 || ^23.4 || >=24.10"
|
||||
"node": "^22.16 || ^23.11 || >=24.10"
|
||||
}
|
||||
}
|
||||
@@ -62,6 +62,7 @@ function makeSnapshot(input: {
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
|
||||
@@ -37,6 +37,8 @@ function createSendTurnHarness() {
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -75,6 +77,8 @@ function createThreadControlHarness() {
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -117,6 +121,8 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
],
|
||||
]),
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -135,6 +141,44 @@ 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>(),
|
||||
collabReceiverItems: 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 +765,8 @@ describe("respondToUserInput", () => {
|
||||
},
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
};
|
||||
type ApprovalRequestContext = {
|
||||
session: typeof context.session;
|
||||
@@ -748,6 +794,197 @@ 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",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("rewrites child task notifications onto the parent collab item when no child item id exists", () => {
|
||||
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 {
|
||||
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
|
||||
}
|
||||
).handleServerNotification(context, {
|
||||
method: "codex/event/task_started",
|
||||
params: {
|
||||
threadId: "child_provider_1",
|
||||
msg: {
|
||||
type: "task_started",
|
||||
turn_id: "turn_child_1",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "codex/event/task_started",
|
||||
turnId: "turn_parent",
|
||||
itemId: "call_collab_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,8 @@ interface CodexSessionContext {
|
||||
pending: Map<PendingRequestKey, PendingRequest>;
|
||||
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
|
||||
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
|
||||
collabReceiverTurns: Map<string, TurnId>;
|
||||
collabReceiverItems: Map<string, ProviderItemId>;
|
||||
nextRequestId: number;
|
||||
stopping: boolean;
|
||||
}
|
||||
@@ -571,6 +573,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
pending: new Map(),
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
collabReceiverTurns: new Map(),
|
||||
collabReceiverItems: new Map(),
|
||||
nextRequestId: 1,
|
||||
stopping: false,
|
||||
};
|
||||
@@ -732,6 +736,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
|
||||
const context = this.requireSession(input.threadId);
|
||||
context.collabReceiverTurns.clear();
|
||||
context.collabReceiverItems.clear();
|
||||
|
||||
const turnInput: Array<
|
||||
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
|
||||
@@ -1121,7 +1127,18 @@ 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 childParentItemId = this.readChildParentItemId(context, notification.params);
|
||||
const isChildConversation = childParentTurnId !== undefined;
|
||||
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
|
||||
if (
|
||||
isChildConversation &&
|
||||
this.shouldSuppressChildConversationNotification(notification.method)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const textDelta =
|
||||
notification.method === "item/agentMessage/delta"
|
||||
? this.readString(notification.params, "delta")
|
||||
@@ -1134,8 +1151,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 }
|
||||
: {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
textDelta,
|
||||
payload: notification.params,
|
||||
});
|
||||
@@ -1151,6 +1170,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 +1182,11 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (notification.method === "turn/completed") {
|
||||
if (isChildConversation) {
|
||||
return;
|
||||
}
|
||||
context.collabReceiverTurns.clear();
|
||||
context.collabReceiverItems.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 +1199,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 +1213,11 @@ 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 childParentItemId = this.readChildParentItemId(context, request.params);
|
||||
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
|
||||
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
@@ -1199,8 +1233,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 } : {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
};
|
||||
context.pendingApprovals.set(requestId, pendingRequest);
|
||||
}
|
||||
@@ -1211,8 +1245,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 } : {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1223,8 +1257,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 } : {}),
|
||||
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
|
||||
requestId,
|
||||
requestKind,
|
||||
payload: request.params,
|
||||
@@ -1451,6 +1485,79 @@ 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 readChildParentItemId(
|
||||
context: CodexSessionContext,
|
||||
params: unknown,
|
||||
): ProviderItemId | undefined {
|
||||
const providerConversationId = this.readProviderConversationId(params);
|
||||
if (!providerConversationId) {
|
||||
return undefined;
|
||||
}
|
||||
return context.collabReceiverItems.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 parentItemId = toProviderItemId(this.readString(item, "id"));
|
||||
|
||||
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);
|
||||
if (parentItemId) {
|
||||
context.collabReceiverItems.set(receiverThreadId, parentItemId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -97,7 +97,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
|
||||
return {
|
||||
status: (input) => core.status(input),
|
||||
statusDetails: (cwd) => core.statusDetails(cwd),
|
||||
prepareCommitContext: (cwd) => core.prepareCommitContext(cwd),
|
||||
prepareCommitContext: (cwd, filePaths?) => core.prepareCommitContext(cwd, filePaths),
|
||||
commit: (cwd, subject, body) => core.commit(cwd, subject, body),
|
||||
pushCurrentBranch: (cwd, fallbackBranch) => core.pushCurrentBranch(cwd, fallbackBranch),
|
||||
pullCurrentBranch: (cwd) => core.pullCurrentBranch(cwd),
|
||||
@@ -1711,6 +1711,45 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepareCommitContext stages only selected files when filePaths provided", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n");
|
||||
yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n");
|
||||
|
||||
const context = yield* core.prepareCommitContext(tmp, ["a.txt"]);
|
||||
expect(context).not.toBeNull();
|
||||
expect(context!.stagedSummary).toContain("a.txt");
|
||||
expect(context!.stagedSummary).not.toContain("b.txt");
|
||||
|
||||
yield* core.commit(tmp, "Add only a.txt", "");
|
||||
|
||||
// b.txt should still be untracked after commit
|
||||
const statusAfter = yield* git(tmp, ["status", "--porcelain"]);
|
||||
expect(statusAfter).toContain("b.txt");
|
||||
expect(statusAfter).not.toContain("a.txt");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("prepareCommitContext stages everything when filePaths is undefined", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const core = yield* GitCore;
|
||||
|
||||
yield* writeTextFile(path.join(tmp, "a.txt"), "file a\n");
|
||||
yield* writeTextFile(path.join(tmp, "b.txt"), "file b\n");
|
||||
|
||||
const context = yield* core.prepareCommitContext(tmp);
|
||||
expect(context).not.toBeNull();
|
||||
expect(context!.stagedSummary).toContain("a.txt");
|
||||
expect(context!.stagedSummary).toContain("b.txt");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("pushes with upstream setup and then skips when up to date", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -766,9 +766,21 @@ const makeGitCore = Effect.gen(function* () {
|
||||
})),
|
||||
);
|
||||
|
||||
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd) =>
|
||||
const prepareCommitContext: GitCoreShape["prepareCommitContext"] = (cwd, filePaths) =>
|
||||
Effect.gen(function* () {
|
||||
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
|
||||
if (filePaths && filePaths.length > 0) {
|
||||
yield* runGit("GitCore.prepareCommitContext.reset", cwd, ["reset"]).pipe(
|
||||
Effect.catch(() => Effect.void),
|
||||
);
|
||||
yield* runGit("GitCore.prepareCommitContext.addSelected", cwd, [
|
||||
"add",
|
||||
"-A",
|
||||
"--",
|
||||
...filePaths,
|
||||
]);
|
||||
} else {
|
||||
yield* runGit("GitCore.prepareCommitContext.addAll", cwd, ["add", "-A"]);
|
||||
}
|
||||
|
||||
const stagedSummary = yield* runGitStdout("GitCore.prepareCommitContext.stagedSummary", cwd, [
|
||||
"diff",
|
||||
|
||||
@@ -451,6 +451,7 @@ function runStackedAction(
|
||||
action: "commit" | "commit_push" | "commit_push_pr";
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
},
|
||||
) {
|
||||
return manager.runStackedAction(input);
|
||||
@@ -767,6 +768,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-");
|
||||
|
||||
@@ -638,9 +638,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 +666,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)));
|
||||
|
||||
@@ -680,6 +683,8 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
filePaths?: readonly string[],
|
||||
model?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
@@ -688,6 +693,8 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
@@ -701,7 +708,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 +752,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 +972,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(
|
||||
@@ -1018,6 +1034,8 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
@@ -1033,6 +1051,8 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
@@ -1040,7 +1060,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
|
||||
@@ -101,6 +101,7 @@ export interface GitCoreShape {
|
||||
*/
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
@@ -44,7 +44,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 +235,7 @@ describe("CheckpointReactor", () => {
|
||||
readonly projectWorkspaceRoot?: string;
|
||||
readonly threadWorktreePath?: string | null;
|
||||
readonly providerSessionCwd?: string;
|
||||
readonly providerName?: ProviderKind;
|
||||
}) {
|
||||
const cwd = createGitRepository();
|
||||
tempDirs.push(cwd);
|
||||
@@ -242,7 +243,7 @@ describe("CheckpointReactor", () => {
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
"codex",
|
||||
options?.providerName ?? "codex",
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -477,6 +478,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 +854,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();
|
||||
|
||||
@@ -89,6 +89,7 @@ const make = Effect.gen(function* () {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: null,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
@@ -113,6 +114,7 @@ const make = Effect.gen(function* () {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
@@ -313,6 +315,7 @@ const make = Effect.gen(function* () {
|
||||
status: input.status,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
@@ -175,6 +176,138 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("projects work units and activity work-unit links", () =>
|
||||
Effect.gen(function* () {
|
||||
const projectionPipeline = yield* OrchestrationProjectionPipeline;
|
||||
const eventStore = yield* OrchestrationEventStore;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const now = new Date().toISOString();
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.created",
|
||||
eventId: EventId.makeUnsafe("evt-work-unit-thread"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-work-unit-thread"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-work-unit-thread"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread work unit",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.work-unit-upserted",
|
||||
eventId: EventId.makeUnsafe("evt-work-unit-upsert"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-work-unit-upsert"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-work-unit-upsert"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
workUnit: {
|
||||
id: WorkUnitId.makeUnsafe("wu:thread-work-unit:turn:turn-1:root"),
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* eventStore.append({
|
||||
type: "thread.activity-appended",
|
||||
eventId: EventId.makeUnsafe("evt-work-unit-activity"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-work-unit-activity"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-work-unit-activity"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-work-unit"),
|
||||
activity: {
|
||||
id: EventId.makeUnsafe("activity-work-unit"),
|
||||
tone: "info",
|
||||
kind: "task.progress",
|
||||
summary: "Reasoning update",
|
||||
payload: {
|
||||
detail: "Looking around",
|
||||
},
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
workUnitId: WorkUnitId.makeUnsafe("wu:thread-work-unit:turn:turn-1:root"),
|
||||
createdAt: now,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* projectionPipeline.bootstrap;
|
||||
|
||||
const workUnitRows = yield* sql<{
|
||||
readonly workUnitId: string;
|
||||
readonly turnId: string;
|
||||
readonly state: string;
|
||||
readonly providerRefsJson: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
work_unit_id AS "workUnitId",
|
||||
turn_id AS "turnId",
|
||||
state,
|
||||
provider_refs_json AS "providerRefsJson"
|
||||
FROM projection_thread_work_units
|
||||
WHERE thread_id = 'thread-work-unit'
|
||||
`;
|
||||
assert.deepEqual(workUnitRows, [
|
||||
{
|
||||
workUnitId: "wu:thread-work-unit:turn:turn-1:root",
|
||||
turnId: "turn-1",
|
||||
state: "running",
|
||||
providerRefsJson: '{"providerTurnId":"provider-turn-1"}',
|
||||
},
|
||||
]);
|
||||
|
||||
const activityRows = yield* sql<{
|
||||
readonly activityId: string;
|
||||
readonly workUnitId: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
activity_id AS "activityId",
|
||||
work_unit_id AS "workUnitId"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = 'thread-work-unit'
|
||||
`;
|
||||
assert.deepEqual(activityRows, [
|
||||
{
|
||||
activityId: "activity-work-unit",
|
||||
workUnitId: "wu:thread-work-unit:turn:turn-1:root",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores message attachment references without mutating payloads", () =>
|
||||
Effect.sync(() => fs.mkdtempSync(path.join(os.tmpdir(), "t3-projection-attachments-"))).pipe(
|
||||
Effect.flatMap((stateDir) =>
|
||||
@@ -1729,6 +1862,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
const threadId = ThreadId.makeUnsafe("thread-restart");
|
||||
const turnId = TurnId.makeUnsafe("turn-restart");
|
||||
const messageId = MessageId.makeUnsafe("message-restart");
|
||||
const sourcePlanThreadId = ThreadId.makeUnsafe("thread-plan-source");
|
||||
const sourcePlanId = "plan-source";
|
||||
const turnStartedAt = "2026-02-26T14:00:00.000Z";
|
||||
const sessionSetAt = "2026-02-26T14:00:05.000Z";
|
||||
|
||||
@@ -1749,6 +1884,10 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
payload: {
|
||||
threadId,
|
||||
messageId,
|
||||
sourceProposedPlan: {
|
||||
threadId: sourcePlanThreadId,
|
||||
planId: sourcePlanId,
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: turnStartedAt,
|
||||
},
|
||||
@@ -1800,11 +1939,15 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
return yield* sql<{
|
||||
readonly turnId: string;
|
||||
readonly userMessageId: string | null;
|
||||
readonly sourceProposedPlanThreadId: string | null;
|
||||
readonly sourceProposedPlanId: string | null;
|
||||
readonly startedAt: string;
|
||||
}>`
|
||||
SELECT
|
||||
turn_id AS "turnId",
|
||||
pending_message_id AS "userMessageId",
|
||||
source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
|
||||
source_proposed_plan_id AS "sourceProposedPlanId",
|
||||
started_at AS "startedAt"
|
||||
FROM projection_turns
|
||||
WHERE turn_id = ${turnId}
|
||||
@@ -1815,6 +1958,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
{
|
||||
turnId: "turn-restart",
|
||||
userMessageId: "message-restart",
|
||||
sourceProposedPlanThreadId: "thread-plan-source",
|
||||
sourceProposedPlanId: "plan-source",
|
||||
startedAt: turnStartedAt,
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -22,6 +22,10 @@ import {
|
||||
type ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import {
|
||||
type ProjectionThreadWorkUnit,
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
|
||||
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import {
|
||||
type ProjectionTurn,
|
||||
@@ -34,6 +38,7 @@ import { ProjectionStateRepositoryLive } from "../../persistence/Layers/Projecti
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadWorkUnitRepositoryLive } from "../../persistence/Layers/ProjectionThreadWorkUnits.ts";
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
@@ -55,6 +60,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
threadMessages: "projection.thread-messages",
|
||||
threadProposedPlans: "projection.thread-proposed-plans",
|
||||
threadActivities: "projection.thread-activities",
|
||||
threadWorkUnits: "projection.thread-work-units",
|
||||
threadSessions: "projection.thread-sessions",
|
||||
threadTurns: "projection.thread-turns",
|
||||
checkpoints: "projection.checkpoints",
|
||||
@@ -214,6 +220,28 @@ function retainProjectionProposedPlansAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainProjectionWorkUnitsAfterRevert(
|
||||
workUnits: ReadonlyArray<ProjectionThreadWorkUnit>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
turnCount: number,
|
||||
): ReadonlyArray<ProjectionThreadWorkUnit> {
|
||||
const retainedTurnIds = new Set<string>(
|
||||
turns
|
||||
.filter(
|
||||
(turn) =>
|
||||
turn.turnId !== null &&
|
||||
turn.checkpointTurnCount !== null &&
|
||||
turn.checkpointTurnCount <= turnCount,
|
||||
)
|
||||
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
|
||||
);
|
||||
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
|
||||
const retainedIds = new Set(retained.map((workUnit) => workUnit.workUnitId));
|
||||
return retained.filter(
|
||||
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
|
||||
);
|
||||
}
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
@@ -346,6 +374,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadWorkUnitRepository = yield* ProjectionThreadWorkUnitRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
|
||||
@@ -653,6 +682,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,
|
||||
});
|
||||
@@ -703,6 +734,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
activityId: event.payload.activity.id,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.activity.turnId,
|
||||
workUnitId: event.payload.activity.workUnitId,
|
||||
tone: event.payload.activity.tone,
|
||||
kind: event.payload.activity.kind,
|
||||
summary: event.payload.activity.summary,
|
||||
@@ -746,6 +778,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadWorkUnitsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.work-unit-upserted":
|
||||
yield* projectionThreadWorkUnitRepository.upsert({
|
||||
workUnitId: event.payload.workUnit.id,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.workUnit.turnId,
|
||||
parentWorkUnitId: event.payload.workUnit.parentWorkUnitId,
|
||||
kind: event.payload.workUnit.kind,
|
||||
state: event.payload.workUnit.state,
|
||||
title: event.payload.workUnit.title,
|
||||
detail: event.payload.workUnit.detail,
|
||||
spawnedByActivityId: event.payload.workUnit.spawnedByActivityId,
|
||||
...(event.payload.workUnit.providerRefs !== undefined
|
||||
? { providerRefs: event.payload.workUnit.providerRefs }
|
||||
: {}),
|
||||
startedAt: event.payload.workUnit.startedAt,
|
||||
updatedAt: event.payload.workUnit.updatedAt,
|
||||
completedAt: event.payload.workUnit.completedAt,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingRows = yield* projectionThreadWorkUnitRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (existingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const keptRows = retainProjectionWorkUnitsAfterRevert(
|
||||
existingRows,
|
||||
existingTurns,
|
||||
event.payload.turnCount,
|
||||
);
|
||||
if (keptRows.length === existingRows.length) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadWorkUnitRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(keptRows, projectionThreadWorkUnitRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
@@ -775,6 +865,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 +896,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 +924,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 +983,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 +1020,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 +1066,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,
|
||||
@@ -1108,6 +1222,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
apply: applyThreadActivitiesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
|
||||
apply: applyThreadWorkUnitsProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
apply: applyThreadSessionsProjection,
|
||||
@@ -1225,6 +1343,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadWorkUnitRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
|
||||
Layer.provideMerge(ProjectionTurnRepositoryLive),
|
||||
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
|
||||
|
||||
@@ -1,4 +1,12 @@
|
||||
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
CheckpointRef,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -13,6 +21,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
const asWorkUnitId = (value: string): WorkUnitId => WorkUnitId.makeUnsafe(value);
|
||||
|
||||
const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
@@ -26,6 +35,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`
|
||||
@@ -101,11 +111,35 @@ 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,
|
||||
thread_id,
|
||||
turn_id,
|
||||
work_unit_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -116,6 +150,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'activity-1',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'wu:thread-1:turn:turn-1:root',
|
||||
'info',
|
||||
'runtime.note',
|
||||
'provider started',
|
||||
@@ -124,6 +159,39 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_work_units (
|
||||
work_unit_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
parent_work_unit_id,
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id,
|
||||
provider_refs_json,
|
||||
started_at,
|
||||
updated_at,
|
||||
completed_at
|
||||
)
|
||||
VALUES (
|
||||
'wu:thread-1:turn:turn-1:root',
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'primary_agent',
|
||||
'completed',
|
||||
'Primary agent',
|
||||
NULL,
|
||||
NULL,
|
||||
'{"providerTurnId":"provider-turn-1"}',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
'2026-02-24T00:00:08.000Z'
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_sessions (
|
||||
thread_id,
|
||||
@@ -154,6 +222,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 +238,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'thread-1',
|
||||
'plan-1',
|
||||
'message-1',
|
||||
'completed',
|
||||
'2026-02-24T00:00:08.000Z',
|
||||
@@ -238,6 +310,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 +329,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"),
|
||||
@@ -262,9 +348,28 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
summary: "provider started",
|
||||
payload: { stage: "start" },
|
||||
turnId: asTurnId("turn-1"),
|
||||
workUnitId: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
|
||||
createdAt: "2026-02-24T00:00:06.000Z",
|
||||
},
|
||||
],
|
||||
workUnits: [
|
||||
{
|
||||
id: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "completed",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: "2026-02-24T00:00:08.000Z",
|
||||
updatedAt: "2026-02-24T00:00:08.000Z",
|
||||
completedAt: "2026-02-24T00:00:08.000Z",
|
||||
},
|
||||
],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: asTurnId("turn-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,
|
||||
type OrchestrationWorkUnit,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -32,6 +35,7 @@ import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadWorkUnit } from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
|
||||
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
@@ -60,6 +64,13 @@ const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
sequence: Schema.NullOr(NonNegativeInt),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
|
||||
Struct.assign({
|
||||
providerRefs: Schema.NullOr(
|
||||
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
|
||||
),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
|
||||
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
|
||||
Struct.assign({
|
||||
@@ -74,6 +85,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;
|
||||
|
||||
@@ -83,6 +96,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
] as const;
|
||||
@@ -200,6 +214,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
|
||||
@@ -216,6 +232,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
work_unit_id AS "workUnitId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -232,6 +249,30 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadWorkUnitRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadWorkUnitDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
work_unit_id AS "workUnitId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
parent_work_unit_id AS "parentWorkUnitId",
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id AS "spawnedByActivityId",
|
||||
provider_refs_json AS "providerRefs",
|
||||
started_at AS "startedAt",
|
||||
updated_at AS "updatedAt",
|
||||
completed_at AS "completedAt"
|
||||
FROM projection_thread_work_units
|
||||
ORDER BY thread_id ASC, started_at ASC, work_unit_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadSessionRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadSessionDbRowSchema,
|
||||
@@ -284,7 +325,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
|
||||
@@ -314,6 +357,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
workUnitRows,
|
||||
sessionRows,
|
||||
checkpointRows,
|
||||
latestTurnRows,
|
||||
@@ -359,6 +403,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadWorkUnitRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadSessionRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -396,6 +448,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const workUnitsByThread = new Map<string, Array<OrchestrationWorkUnit>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
|
||||
@@ -435,6 +488,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,
|
||||
});
|
||||
@@ -451,12 +506,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
workUnitId: row.workUnitId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
}
|
||||
|
||||
for (const row of workUnitRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
const threadWorkUnits = workUnitsByThread.get(row.threadId) ?? [];
|
||||
threadWorkUnits.push({
|
||||
id: row.workUnitId,
|
||||
turnId: row.turnId,
|
||||
parentWorkUnitId: row.parentWorkUnitId,
|
||||
kind: row.kind,
|
||||
state: row.state,
|
||||
title: row.title,
|
||||
detail: row.detail,
|
||||
spawnedByActivityId: row.spawnedByActivityId,
|
||||
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
|
||||
startedAt: row.startedAt,
|
||||
updatedAt: row.updatedAt,
|
||||
completedAt: row.completedAt,
|
||||
});
|
||||
workUnitsByThread.set(row.threadId, threadWorkUnits);
|
||||
}
|
||||
|
||||
for (const row of checkpointRows) {
|
||||
updatedAt = maxIso(updatedAt, row.completedAt);
|
||||
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
|
||||
@@ -497,6 +573,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,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -540,6 +624,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
workUnits: workUnitsByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
}));
|
||||
|
||||
@@ -83,9 +83,13 @@ describe("ProviderCommandReactor", () => {
|
||||
createdStateDirs.clear();
|
||||
});
|
||||
|
||||
async function createHarness(input?: { readonly stateDir?: string }) {
|
||||
async function createHarness(input?: {
|
||||
readonly stateDir?: string;
|
||||
readonly threadModel?: string;
|
||||
}) {
|
||||
const now = new Date().toISOString();
|
||||
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
|
||||
const threadModel = input?.threadModel ?? "gpt-5-codex";
|
||||
createdStateDirs.add(stateDir);
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
@@ -96,7 +100,7 @@ describe("ProviderCommandReactor", () => {
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
input.provider === "codex"
|
||||
(input.provider === "codex" || input.provider === "claudeAgent")
|
||||
? input.provider
|
||||
: "codex";
|
||||
const resumeCursor =
|
||||
@@ -129,7 +133,7 @@ describe("ProviderCommandReactor", () => {
|
||||
: "full-access",
|
||||
...(model !== undefined ? { model } : {}),
|
||||
threadId,
|
||||
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
|
||||
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
@@ -228,7 +232,7 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModel: threadModel,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -239,7 +243,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
model: threadModel,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -351,6 +355,106 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards claude effort options through session start and turn send", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-effort"),
|
||||
role: "user",
|
||||
text: "hello with effort",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards claude fast mode options through session start and turn send", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-fast-mode"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-fast-mode"),
|
||||
role: "user",
|
||||
text: "hello with fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("forwards plan interaction mode to the provider turn request", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -389,6 +493,102 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-first"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-first"),
|
||||
role: "user",
|
||||
text: "hello claude",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
expect(harness.startSession).not.toHaveBeenCalled();
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session).toBeNull();
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
summary: "Provider turn start failed",
|
||||
payload: {
|
||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a turn when the requested model belongs to a different provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-model-provider-mismatch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-model-provider-mismatch"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
model: "claude-sonnet-4-6",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
expect(harness.startSession).not.toHaveBeenCalled();
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("does not belong to provider 'codex'"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -435,6 +635,73 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("restarts claude sessions when claude effort changes", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-effort-1"),
|
||||
role: "user",
|
||||
text: "first claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-claude-effort-2"),
|
||||
role: "user",
|
||||
text: "second claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("restarts the provider session when runtime mode is updated on the thread", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -509,7 +776,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 +789,77 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("rejects provider changes after a thread is already bound to a session provider", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-1"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-provider-switch-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-provider-switch-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
expect(harness.startSession.mock.calls.length).toBe(1);
|
||||
expect(harness.sendTurn.mock.calls.length).toBe(1);
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.providerName).toBe("codex");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
expect(
|
||||
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
|
||||
).toMatchObject({
|
||||
payload: {
|
||||
detail: expect.stringContaining("cannot switch to 'claudeAgent'"),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -759,6 +1097,7 @@ describe("ProviderCommandReactor", () => {
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
workUnitId: null,
|
||||
createdAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
type ProviderKind,
|
||||
ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -74,6 +76,11 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
|
||||
const sameModelOptions = (
|
||||
left: ProviderModelOptions | undefined,
|
||||
right: ProviderModelOptions | undefined,
|
||||
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
|
||||
|
||||
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
|
||||
const error = Cause.squash(cause);
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
@@ -136,6 +143,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
const threadModelOptions = new Map<string, ProviderModelOptions>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -165,6 +173,7 @@ const make = Effect.gen(function* () {
|
||||
...(input.requestId ? { requestId: input.requestId } : {}),
|
||||
},
|
||||
turnId: input.turnId,
|
||||
workUnitId: null,
|
||||
createdAt: input.createdAt,
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
@@ -205,9 +214,30 @@ 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 currentProvider: ProviderKind | undefined = Schema.is(ProviderKind)(
|
||||
thread.session?.providerName,
|
||||
)
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const threadProvider: ProviderKind = currentProvider ?? inferProviderForModel(thread.model);
|
||||
if (options?.provider !== undefined && options.provider !== threadProvider) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${options.provider}'.`,
|
||||
});
|
||||
}
|
||||
if (
|
||||
options?.model !== undefined &&
|
||||
inferProviderForModel(options.model, threadProvider) !== threadProvider
|
||||
) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
@@ -267,13 +297,23 @@ const make = Effect.gen(function* () {
|
||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||
const previousModelOptions = threadModelOptions.get(threadId);
|
||||
const shouldRestartForModelOptionsChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
options?.modelOptions !== undefined &&
|
||||
!sameModelOptions(previousModelOptions, options.modelOptions);
|
||||
|
||||
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
!providerChanged &&
|
||||
!shouldRestartForModelChange &&
|
||||
!shouldRestartForModelOptionsChange
|
||||
) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
|
||||
const resumeCursor =
|
||||
providerChanged || shouldRestartForModelChange
|
||||
providerChanged || shouldRestartForModelChange || shouldRestartForModelOptionsChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
@@ -287,6 +327,7 @@ const make = Effect.gen(function* () {
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelOptionsChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
@@ -326,15 +367,18 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
if (input.providerOptions !== undefined) {
|
||||
threadProviderOptions.set(input.threadId, input.providerOptions);
|
||||
}
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
if (input.providerOptions !== undefined) {
|
||||
threadProviderOptions.set(input.threadId, input.providerOptions);
|
||||
}
|
||||
if (input.modelOptions !== undefined) {
|
||||
threadModelOptions.set(input.threadId, input.modelOptions);
|
||||
}
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
const activeSession = yield* providerService
|
||||
@@ -391,6 +435,7 @@ const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -475,7 +520,18 @@ const make = Effect.gen(function* () {
|
||||
: {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.start.failed",
|
||||
summary: "Provider turn start failed",
|
||||
detail: Cause.pretty(cause),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const processTurnInterruptRequested = Effect.fnUntraced(function* (
|
||||
@@ -624,13 +680,13 @@ const make = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedProviderOptions !== undefined
|
||||
const cachedModelOptions = threadModelOptions.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
|
||||
...(cachedProviderOptions !== undefined
|
||||
? { providerOptions: cachedProviderOptions }
|
||||
: undefined,
|
||||
);
|
||||
: {}),
|
||||
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
|
||||
});
|
||||
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;
|
||||
}
|
||||
@@ -108,6 +125,7 @@ type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number]
|
||||
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
|
||||
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
|
||||
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
|
||||
type ProviderRuntimeTestWorkUnit = ProviderRuntimeTestThread["workUnits"][number];
|
||||
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
|
||||
|
||||
describe("ProviderRuntimeIngestion", () => {
|
||||
@@ -150,6 +168,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),
|
||||
@@ -205,10 +224,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 +430,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 +710,496 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("marks the source proposed plan implemented only after the target turn starts", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
const targetThreadId = asThreadId("thread-implement");
|
||||
const sourceTurnId = asTurnId("turn-plan-source");
|
||||
const targetTurnId = asTurnId("turn-plan-implement");
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
session: {
|
||||
threadId: targetThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
harness.setProviderSession({
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: targetThreadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: targetTurnId,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("evt-plan-source-completed"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: sourceThreadId,
|
||||
turnId: sourceTurnId,
|
||||
payload: {
|
||||
planMarkdown: "# Source plan",
|
||||
},
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
|
||||
proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) =>
|
||||
entry.id === "plan:thread-plan:turn:turn-plan-source",
|
||||
);
|
||||
expect(sourcePlan).toBeDefined();
|
||||
if (!sourcePlan) {
|
||||
throw new Error("Expected source plan to exist.");
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target"),
|
||||
role: "user",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
|
||||
attachments: [],
|
||||
},
|
||||
sourceProposedPlan: {
|
||||
threadId: sourceThreadId,
|
||||
planId: sourcePlan.id,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
const sourceThreadBeforeStart = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === sourcePlan.id && proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadBeforeStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-plan-target-started"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: targetThreadId,
|
||||
turnId: targetTurnId,
|
||||
});
|
||||
|
||||
const sourceThreadAfterStart = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === sourcePlan.id &&
|
||||
proposedPlan.implementedAt !== null &&
|
||||
proposedPlan.implementationThreadId === targetThreadId,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadAfterStart.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementationThreadId: "thread-implement",
|
||||
});
|
||||
});
|
||||
|
||||
it("does not mark the source proposed plan implemented for a rejected turn.started event", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
const targetThreadId = asThreadId("thread-1");
|
||||
const sourceTurnId = asTurnId("turn-plan-source");
|
||||
const activeTurnId = asTurnId("turn-already-running");
|
||||
const staleTurnId = asTurnId("turn-stale-start");
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-guarded"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
harness.setProviderSession({
|
||||
provider: "codex",
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: targetThreadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-already-running"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: targetThreadId,
|
||||
turnId: activeTurnId,
|
||||
});
|
||||
|
||||
await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.session?.status === "running" && thread.session?.activeTurnId === activeTurnId,
|
||||
2_000,
|
||||
targetThreadId,
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("evt-plan-source-completed-guarded"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: sourceThreadId,
|
||||
turnId: sourceTurnId,
|
||||
payload: {
|
||||
planMarkdown: "# Source plan",
|
||||
},
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
|
||||
proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) =>
|
||||
entry.id === "plan:thread-plan:turn:turn-plan-source",
|
||||
);
|
||||
expect(sourcePlan).toBeDefined();
|
||||
if (!sourcePlan) {
|
||||
throw new Error("Expected source plan to exist.");
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-guarded"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target-guarded"),
|
||||
role: "user",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
|
||||
attachments: [],
|
||||
},
|
||||
sourceProposedPlan: {
|
||||
threadId: sourceThreadId,
|
||||
planId: sourcePlan.id,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-stale-plan-implementation"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: targetThreadId,
|
||||
turnId: staleTurnId,
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterRejectedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadAfterRejectedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
});
|
||||
|
||||
const targetThreadAfterRejectedStart = readModel.threads.find(
|
||||
(entry) => entry.id === targetThreadId,
|
||||
);
|
||||
expect(targetThreadAfterRejectedStart?.session?.status).toBe("running");
|
||||
expect(targetThreadAfterRejectedStart?.session?.activeTurnId).toBe(activeTurnId);
|
||||
});
|
||||
|
||||
it("does not mark the source proposed plan implemented for an unrelated turn.started when no thread active turn is tracked", async () => {
|
||||
const harness = await createHarness();
|
||||
const sourceThreadId = asThreadId("thread-plan");
|
||||
const targetThreadId = asThreadId("thread-implement");
|
||||
const sourceTurnId = asTurnId("turn-plan-source");
|
||||
const expectedTurnId = asTurnId("turn-plan-implement");
|
||||
const replayedTurnId = asTurnId("turn-replayed");
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-source-unrelated"),
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-source-unrelated"),
|
||||
threadId: sourceThreadId,
|
||||
session: {
|
||||
threadId: sourceThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
session: {
|
||||
threadId: targetThreadId,
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
updatedAt: createdAt,
|
||||
lastError: null,
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
harness.emit({
|
||||
type: "turn.proposed.completed",
|
||||
eventId: asEventId("evt-plan-source-completed-unrelated"),
|
||||
provider: "codex",
|
||||
createdAt,
|
||||
threadId: sourceThreadId,
|
||||
turnId: sourceTurnId,
|
||||
payload: {
|
||||
planMarkdown: "# Source plan",
|
||||
},
|
||||
});
|
||||
|
||||
const sourceThreadWithPlan = await waitForThread(
|
||||
harness.engine,
|
||||
(thread) =>
|
||||
thread.proposedPlans.some(
|
||||
(proposedPlan: ProviderRuntimeTestProposedPlan) =>
|
||||
proposedPlan.id === "plan:thread-plan:turn:turn-plan-source" &&
|
||||
proposedPlan.implementedAt === null,
|
||||
),
|
||||
2_000,
|
||||
sourceThreadId,
|
||||
);
|
||||
const sourcePlan = sourceThreadWithPlan.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) =>
|
||||
entry.id === "plan:thread-plan:turn:turn-plan-source",
|
||||
);
|
||||
expect(sourcePlan).toBeDefined();
|
||||
if (!sourcePlan) {
|
||||
throw new Error("Expected source plan to exist.");
|
||||
}
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan-target-unrelated"),
|
||||
threadId: targetThreadId,
|
||||
message: {
|
||||
messageId: asMessageId("msg-plan-target-unrelated"),
|
||||
role: "user",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n# Source plan",
|
||||
attachments: [],
|
||||
},
|
||||
sourceProposedPlan: {
|
||||
threadId: sourceThreadId,
|
||||
planId: sourcePlan.id,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
|
||||
harness.setProviderSession({
|
||||
provider: "codex",
|
||||
status: "running",
|
||||
runtimeMode: "approval-required",
|
||||
threadId: targetThreadId,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
activeTurnId: expectedTurnId,
|
||||
});
|
||||
|
||||
harness.emit({
|
||||
type: "turn.started",
|
||||
eventId: asEventId("evt-turn-started-unrelated-plan-implementation"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: targetThreadId,
|
||||
turnId: replayedTurnId,
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const sourceThreadAfterUnrelatedStart = readModel.threads.find(
|
||||
(entry) => entry.id === sourceThreadId,
|
||||
);
|
||||
expect(
|
||||
sourceThreadAfterUnrelatedStart?.proposedPlans.find((entry) => entry.id === sourcePlan.id),
|
||||
).toMatchObject({
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("finalizes buffered proposed-plan deltas into a first-class proposed plan on turn completion", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -1338,6 +1910,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-task-1"),
|
||||
itemId: "call-collab-1",
|
||||
payload: {
|
||||
taskId: "turn-task-1",
|
||||
taskType: "plan",
|
||||
@@ -1351,9 +1924,11 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-task-1"),
|
||||
itemId: "call-collab-1",
|
||||
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.",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1364,6 +1939,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-task-1"),
|
||||
itemId: "call-collab-1",
|
||||
payload: {
|
||||
taskId: "turn-task-1",
|
||||
status: "completed",
|
||||
@@ -1416,11 +1992,44 @@ 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>");
|
||||
expect(started?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
|
||||
expect(progress?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
|
||||
expect(completed?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
|
||||
expect(
|
||||
thread.workUnits.find(
|
||||
(entry: ProviderRuntimeTestWorkUnit) => entry.id === "wu:thread-1:turn:turn-task-1:root",
|
||||
),
|
||||
).toMatchObject({
|
||||
id: "wu:thread-1:turn:turn-task-1:root",
|
||||
turnId: "turn-task-1",
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
});
|
||||
expect(
|
||||
thread.workUnits.find(
|
||||
(entry: ProviderRuntimeTestWorkUnit) =>
|
||||
entry.id === "wu:thread-1:turn:turn-task-1:task:turn-task-1",
|
||||
),
|
||||
).toMatchObject({
|
||||
id: "wu:thread-1:turn:turn-task-1:task:turn-task-1",
|
||||
turnId: "turn-task-1",
|
||||
parentWorkUnitId: "wu:thread-1:turn:turn-task-1:root",
|
||||
kind: "delegated_agent",
|
||||
state: "completed",
|
||||
title: "<proposed_plan>\n# Plan title\n</proposed_plan>",
|
||||
providerRefs: {
|
||||
runtimeTaskId: "turn-task-1",
|
||||
runtimeItemId: "call-collab-1",
|
||||
},
|
||||
});
|
||||
expect(
|
||||
thread.proposedPlans.find(
|
||||
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-task-1",
|
||||
|
||||
@@ -4,9 +4,14 @@ import {
|
||||
CommandId,
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationProposedPlanId,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
RuntimeTaskId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -14,6 +19,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";
|
||||
@@ -25,6 +32,10 @@ import {
|
||||
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
|
||||
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
|
||||
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
|
||||
const rootWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId): WorkUnitId =>
|
||||
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:root`);
|
||||
const taskWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId, taskId: string): WorkUnitId =>
|
||||
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:task:${taskId}`);
|
||||
|
||||
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
|
||||
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
|
||||
@@ -173,16 +184,55 @@ 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 workUnitIdForRuntimeEvent(event: ProviderRuntimeEvent): WorkUnitId | null {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
event.type === "task.started" ||
|
||||
event.type === "task.progress" ||
|
||||
event.type === "task.completed"
|
||||
) {
|
||||
return taskWorkUnitIdForTurn(event.threadId, turnId, String(event.payload.taskId));
|
||||
}
|
||||
return rootWorkUnitIdForTurn(event.threadId, turnId);
|
||||
}
|
||||
|
||||
function runtimeTurnStateToWorkUnitState(
|
||||
state: "completed" | "failed" | "interrupted" | "cancelled",
|
||||
): "completed" | "failed" | "stopped" | "cancelled" {
|
||||
switch (state) {
|
||||
case "failed":
|
||||
return "failed";
|
||||
case "interrupted":
|
||||
return "stopped";
|
||||
case "cancelled":
|
||||
return "cancelled";
|
||||
case "completed":
|
||||
return "completed";
|
||||
}
|
||||
}
|
||||
|
||||
function runtimeTaskStateToWorkUnitState(
|
||||
state: "completed" | "failed" | "stopped",
|
||||
): "completed" | "failed" | "stopped" {
|
||||
switch (state) {
|
||||
case "failed":
|
||||
return "failed";
|
||||
case "stopped":
|
||||
return "stopped";
|
||||
case "completed":
|
||||
return "completed";
|
||||
}
|
||||
}
|
||||
|
||||
function providerTurnWorkUnitRefs(
|
||||
event: ProviderRuntimeEvent,
|
||||
): NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]> | undefined {
|
||||
return event.providerRefs?.providerTurnId !== undefined
|
||||
? { providerTurnId: event.providerRefs.providerTurnId }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function runtimeEventToActivities(
|
||||
@@ -194,6 +244,7 @@ function runtimeEventToActivities(
|
||||
? { sequence: eventWithSequence.sessionSequence }
|
||||
: {};
|
||||
})();
|
||||
const maybeWorkUnit = { workUnitId: workUnitIdForRuntimeEvent(event) };
|
||||
switch (event.type) {
|
||||
case "request.opened": {
|
||||
if (event.payload.requestType === "tool_user_input") {
|
||||
@@ -221,6 +272,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -245,6 +297,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.decision ? { decision: event.payload.decision } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -266,6 +319,7 @@ function runtimeEventToActivities(
|
||||
message: truncateDetail(message),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -284,6 +338,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -304,6 +359,7 @@ function runtimeEventToActivities(
|
||||
: {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -322,6 +378,7 @@ function runtimeEventToActivities(
|
||||
questions: event.payload.questions,
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -340,6 +397,7 @@ function runtimeEventToActivities(
|
||||
answers: event.payload.answers,
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -366,6 +424,7 @@ function runtimeEventToActivities(
|
||||
: {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -381,11 +440,13 @@ 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 } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -411,6 +472,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -434,6 +496,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -449,12 +512,13 @@ 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) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -476,6 +540,7 @@ function runtimeEventToActivities(
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeWorkUnit,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
@@ -491,6 +556,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 +748,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -704,6 +772,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 +787,8 @@ const make = Effect.gen(function* () {
|
||||
threadProposedPlans: ReadonlyArray<{
|
||||
id: string;
|
||||
createdAt: string;
|
||||
implementedAt: string | null;
|
||||
implementationThreadId: ThreadId | null;
|
||||
}>;
|
||||
planId: string;
|
||||
turnId?: TurnId;
|
||||
@@ -783,6 +855,147 @@ 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 upsertWorkUnit = Effect.fnUntraced(function* (input: {
|
||||
thread: OrchestrationThread;
|
||||
event: ProviderRuntimeEvent;
|
||||
workUnitId: WorkUnitId;
|
||||
turnId: TurnId;
|
||||
kind: "primary_agent" | "delegated_agent";
|
||||
state: "queued" | "running" | "completed" | "failed" | "stopped" | "cancelled";
|
||||
title: string;
|
||||
updatedAt: string;
|
||||
parentWorkUnitId?: WorkUnitId | null;
|
||||
detail?: string | null;
|
||||
startedAt?: string;
|
||||
completedAt?: string | null;
|
||||
providerRefs?: NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]>;
|
||||
}) {
|
||||
const existing = input.thread.workUnits.find((entry) => sameId(entry.id, input.workUnitId));
|
||||
const providerRefs =
|
||||
input.providerRefs !== undefined || existing?.providerRefs !== undefined
|
||||
? {
|
||||
...existing?.providerRefs,
|
||||
...input.providerRefs,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.work-unit.upsert",
|
||||
commandId: providerCommandId(input.event, "thread-work-unit-upsert"),
|
||||
threadId: input.thread.id,
|
||||
workUnit: {
|
||||
id: input.workUnitId,
|
||||
turnId: input.turnId,
|
||||
parentWorkUnitId: input.parentWorkUnitId ?? existing?.parentWorkUnitId ?? null,
|
||||
kind: input.kind,
|
||||
state: input.state,
|
||||
title: input.title.trim().length > 0 ? input.title : (existing?.title ?? "Work unit"),
|
||||
detail: input.detail !== undefined ? input.detail : (existing?.detail ?? null),
|
||||
spawnedByActivityId: existing?.spawnedByActivityId ?? null,
|
||||
...(providerRefs !== undefined ? { providerRefs } : {}),
|
||||
startedAt: existing?.startedAt ?? input.startedAt ?? input.updatedAt,
|
||||
updatedAt: input.updatedAt,
|
||||
completedAt:
|
||||
input.completedAt !== undefined ? input.completedAt : (existing?.completedAt ?? null),
|
||||
},
|
||||
createdAt: input.updatedAt,
|
||||
});
|
||||
});
|
||||
|
||||
const ensureRootWorkUnit = Effect.fnUntraced(function* (
|
||||
thread: OrchestrationThread,
|
||||
event: ProviderRuntimeEvent,
|
||||
turnId: TurnId,
|
||||
updatedAt: string,
|
||||
) {
|
||||
const providerRefs = providerTurnWorkUnitRefs(event);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId: rootWorkUnitIdForTurn(thread.id, turnId),
|
||||
turnId,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
updatedAt,
|
||||
startedAt: updatedAt,
|
||||
...(providerRefs ? { providerRefs } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -823,6 +1036,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 +1082,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"),
|
||||
@@ -883,6 +1120,89 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
}
|
||||
|
||||
if (eventTurnId !== undefined) {
|
||||
yield* ensureRootWorkUnit(thread, event, eventTurnId, now);
|
||||
}
|
||||
|
||||
if (event.type === "turn.started" && eventTurnId !== undefined) {
|
||||
const providerRefs = providerTurnWorkUnitRefs(event);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
|
||||
turnId: eventTurnId,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
updatedAt: now,
|
||||
startedAt: now,
|
||||
...(providerRefs ? { providerRefs } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
if (event.type === "turn.completed" && eventTurnId !== undefined) {
|
||||
const providerRefs = providerTurnWorkUnitRefs(event);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
|
||||
turnId: eventTurnId,
|
||||
kind: "primary_agent",
|
||||
state: runtimeTurnStateToWorkUnitState(runtimeTurnState(event)),
|
||||
title: "Primary agent",
|
||||
updatedAt: now,
|
||||
completedAt: now,
|
||||
...(providerRefs ? { providerRefs } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
(event.type === "task.started" ||
|
||||
event.type === "task.progress" ||
|
||||
event.type === "task.completed") &&
|
||||
eventTurnId !== undefined
|
||||
) {
|
||||
const taskId = String(event.payload.taskId);
|
||||
const workUnitId = taskWorkUnitIdForTurn(thread.id, eventTurnId, taskId);
|
||||
const taskState =
|
||||
event.type === "task.completed"
|
||||
? runtimeTaskStateToWorkUnitState(event.payload.status)
|
||||
: "running";
|
||||
const taskTitle =
|
||||
event.type === "task.started"
|
||||
? (event.payload.description ?? event.payload.taskType ?? "Delegated task")
|
||||
: event.type === "task.completed"
|
||||
? (event.payload.summary ?? "Delegated task")
|
||||
: (event.payload.summary ?? event.payload.description);
|
||||
const taskDetail =
|
||||
event.type === "task.started"
|
||||
? (event.payload.description ?? null)
|
||||
: event.type === "task.completed"
|
||||
? (event.payload.summary ?? null)
|
||||
: (event.payload.summary ?? event.payload.description);
|
||||
yield* upsertWorkUnit({
|
||||
thread,
|
||||
event,
|
||||
workUnitId,
|
||||
turnId: eventTurnId,
|
||||
parentWorkUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
|
||||
kind: "delegated_agent",
|
||||
state: taskState,
|
||||
title: taskTitle,
|
||||
detail: taskDetail,
|
||||
updatedAt: now,
|
||||
...(event.type === "task.started" ? { startedAt: now } : {}),
|
||||
...(event.type === "task.completed" ? { completedAt: now } : {}),
|
||||
providerRefs: {
|
||||
runtimeTaskId: RuntimeTaskId.makeUnsafe(taskId),
|
||||
...(event.itemId ? { runtimeItemId: event.itemId } : {}),
|
||||
...(event.providerRefs?.providerTurnId !== undefined
|
||||
? { providerTurnId: event.providerRefs.providerTurnId }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const assistantDelta =
|
||||
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
|
||||
? event.payload.delta
|
||||
@@ -1155,4 +1475,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));
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
|
||||
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
|
||||
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
|
||||
ThreadWorkUnitUpsertedPayload as ContractsThreadWorkUnitUpsertedPayloadSchema,
|
||||
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
|
||||
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
|
||||
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
|
||||
@@ -37,6 +38,7 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
|
||||
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
|
||||
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
|
||||
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
|
||||
export const ThreadWorkUnitUpsertedPayload = ContractsThreadWorkUnitUpsertedPayloadSchema;
|
||||
|
||||
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
|
||||
export const ThreadTurnInterruptRequestedPayload =
|
||||
|
||||
@@ -62,6 +62,7 @@ const readModel: OrchestrationReadModel = {
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
@@ -81,6 +82,7 @@ const readModel: OrchestrationReadModel = {
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
|
||||
@@ -262,11 +262,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",
|
||||
@@ -306,12 +330,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
? { 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,
|
||||
},
|
||||
};
|
||||
@@ -610,6 +631,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.work-unit.upsert": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.work-unit-upserted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
workUnit: command.workUnit,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
default: {
|
||||
command satisfies never;
|
||||
const fallback = command as never as { type: string };
|
||||
|
||||
@@ -85,6 +85,7 @@ describe("orchestration projector", () => {
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
@@ -122,6 +123,88 @@ describe("orchestration projector", () => {
|
||||
).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it("applies thread.work-unit-upserted events", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const model = createEmptyReadModel(now);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-thread-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const next = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.work-unit-upserted",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: now,
|
||||
commandId: "cmd-work-unit-upsert",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
workUnit: {
|
||||
id: "wu:thread-1:turn:turn-1:root",
|
||||
turnId: "turn-1",
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.threads[0]?.workUnits).toEqual([
|
||||
{
|
||||
id: "wu:thread-1:turn:turn-1:root",
|
||||
turnId: "turn-1",
|
||||
parentWorkUnitId: null,
|
||||
kind: "primary_agent",
|
||||
state: "running",
|
||||
title: "Primary agent",
|
||||
detail: null,
|
||||
spawnedByActivityId: null,
|
||||
providerRefs: {
|
||||
providerTurnId: "provider-turn-1",
|
||||
},
|
||||
startedAt: now,
|
||||
updatedAt: now,
|
||||
completedAt: null,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps projector forward-compatible for unhandled event types", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const model = createEmptyReadModel(now);
|
||||
@@ -453,6 +536,7 @@ describe("orchestration projector", () => {
|
||||
summary: "Edit file started",
|
||||
payload: { toolKind: "command" },
|
||||
turnId: "turn-1",
|
||||
workUnitId: null,
|
||||
createdAt: "2026-02-23T10:00:02.750Z",
|
||||
},
|
||||
},
|
||||
@@ -527,6 +611,7 @@ describe("orchestration projector", () => {
|
||||
summary: "Edit file complete",
|
||||
payload: { toolKind: "command" },
|
||||
turnId: "turn-2",
|
||||
workUnitId: null,
|
||||
createdAt: "2026-02-23T10:00:04.750Z",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
ThreadWorkUnitUpsertedPayload,
|
||||
} from "./Schemas.ts";
|
||||
|
||||
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
|
||||
@@ -136,6 +137,17 @@ function retainThreadProposedPlansAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainThreadWorkUnitsAfterRevert(
|
||||
workUnits: ReadonlyArray<OrchestrationThread["workUnits"][number]>,
|
||||
retainedTurnIds: ReadonlySet<string>,
|
||||
): ReadonlyArray<OrchestrationThread["workUnits"][number]> {
|
||||
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
|
||||
const retainedIds = new Set(retained.map((workUnit) => workUnit.id));
|
||||
return retained.filter(
|
||||
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
|
||||
);
|
||||
}
|
||||
|
||||
function compareThreadActivities(
|
||||
left: OrchestrationThread["activities"][number],
|
||||
right: OrchestrationThread["activities"][number],
|
||||
@@ -262,7 +274,9 @@ export function projectEvent(
|
||||
updatedAt: payload.updatedAt,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
},
|
||||
@@ -563,6 +577,7 @@ export function projectEvent(
|
||||
retainedTurnIds,
|
||||
).slice(-200);
|
||||
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
||||
const workUnits = retainThreadWorkUnitsAfterRevert(thread.workUnits, retainedTurnIds);
|
||||
|
||||
const latestCheckpoint = checkpoints.at(-1) ?? null;
|
||||
const latestTurn =
|
||||
@@ -584,6 +599,7 @@ export function projectEvent(
|
||||
messages,
|
||||
proposedPlans,
|
||||
activities,
|
||||
workUnits,
|
||||
latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
@@ -621,6 +637,37 @@ export function projectEvent(
|
||||
}),
|
||||
);
|
||||
|
||||
case "thread.work-unit-upserted":
|
||||
return decodeForEvent(
|
||||
ThreadWorkUnitUpsertedPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => {
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
const workUnits = [
|
||||
...thread.workUnits.filter((entry) => entry.id !== payload.workUnit.id),
|
||||
payload.workUnit,
|
||||
].toSorted(
|
||||
(left, right) =>
|
||||
left.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id),
|
||||
);
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
workUnits,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
default:
|
||||
return Effect.succeed(nextBase);
|
||||
}
|
||||
|
||||
@@ -38,6 +38,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
activity_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
work_unit_id,
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -49,6 +50,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
${row.activityId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.workUnitId},
|
||||
${row.tone},
|
||||
${row.kind},
|
||||
${row.summary},
|
||||
@@ -60,6 +62,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
work_unit_id = excluded.work_unit_id,
|
||||
tone = excluded.tone,
|
||||
kind = excluded.kind,
|
||||
summary = excluded.summary,
|
||||
@@ -78,6 +81,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
activity_id AS "activityId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
work_unit_id AS "workUnitId",
|
||||
tone,
|
||||
kind,
|
||||
summary,
|
||||
@@ -126,6 +130,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
activityId: row.activityId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
workUnitId: row.workUnitId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadWorkUnitsInput,
|
||||
ListProjectionThreadWorkUnitsInput,
|
||||
ProjectionThreadWorkUnit,
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
type ProjectionThreadWorkUnitRepositoryShape,
|
||||
} from "../Services/ProjectionThreadWorkUnits.ts";
|
||||
|
||||
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
|
||||
Struct.assign({
|
||||
providerRefs: Schema.NullOr(
|
||||
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown) =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const makeProjectionThreadWorkUnitRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionThreadWorkUnitRow = SqlSchema.void({
|
||||
Request: ProjectionThreadWorkUnit,
|
||||
execute: (row) => sql`
|
||||
INSERT INTO projection_thread_work_units (
|
||||
work_unit_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
parent_work_unit_id,
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id,
|
||||
provider_refs_json,
|
||||
started_at,
|
||||
updated_at,
|
||||
completed_at
|
||||
)
|
||||
VALUES (
|
||||
${row.workUnitId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.parentWorkUnitId},
|
||||
${row.kind},
|
||||
${row.state},
|
||||
${row.title},
|
||||
${row.detail},
|
||||
${row.spawnedByActivityId},
|
||||
${row.providerRefs ? JSON.stringify(row.providerRefs) : null},
|
||||
${row.startedAt},
|
||||
${row.updatedAt},
|
||||
${row.completedAt}
|
||||
)
|
||||
ON CONFLICT (work_unit_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
parent_work_unit_id = excluded.parent_work_unit_id,
|
||||
kind = excluded.kind,
|
||||
state = excluded.state,
|
||||
title = excluded.title,
|
||||
detail = excluded.detail,
|
||||
spawned_by_activity_id = excluded.spawned_by_activity_id,
|
||||
provider_refs_json = excluded.provider_refs_json,
|
||||
started_at = excluded.started_at,
|
||||
updated_at = excluded.updated_at,
|
||||
completed_at = excluded.completed_at
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionThreadWorkUnitRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadWorkUnitsInput,
|
||||
Result: ProjectionThreadWorkUnitDbRowSchema,
|
||||
execute: ({ threadId }) => sql`
|
||||
SELECT
|
||||
work_unit_id AS "workUnitId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
parent_work_unit_id AS "parentWorkUnitId",
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id AS "spawnedByActivityId",
|
||||
provider_refs_json AS "providerRefs",
|
||||
started_at AS "startedAt",
|
||||
updated_at AS "updatedAt",
|
||||
completed_at AS "completedAt"
|
||||
FROM projection_thread_work_units
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY started_at ASC, work_unit_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteProjectionThreadWorkUnitRows = SqlSchema.void({
|
||||
Request: DeleteProjectionThreadWorkUnitsInput,
|
||||
execute: ({ threadId }) => sql`
|
||||
DELETE FROM projection_thread_work_units
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProjectionThreadWorkUnitRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionThreadWorkUnitRow(row).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadWorkUnitRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const listByThreadId: ProjectionThreadWorkUnitRepositoryShape["listByThreadId"] = (input) =>
|
||||
listProjectionThreadWorkUnitRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionThreadWorkUnitRepository.listByThreadId:query",
|
||||
"ProjectionThreadWorkUnitRepository.listByThreadId:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
workUnitId: row.workUnitId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
parentWorkUnitId: row.parentWorkUnitId,
|
||||
kind: row.kind,
|
||||
state: row.state,
|
||||
title: row.title,
|
||||
detail: row.detail,
|
||||
spawnedByActivityId: row.spawnedByActivityId,
|
||||
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
|
||||
startedAt: row.startedAt,
|
||||
updatedAt: row.updatedAt,
|
||||
completedAt: row.completedAt,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProjectionThreadWorkUnitRepositoryShape["deleteByThreadId"] = (input) =>
|
||||
deleteProjectionThreadWorkUnitRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadWorkUnitRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionThreadWorkUnitRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProjectionThreadWorkUnitRepositoryLive = Layer.effect(
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
makeProjectionThreadWorkUnitRepository,
|
||||
);
|
||||
@@ -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",
|
||||
|
||||
@@ -25,6 +25,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 Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
|
||||
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
|
||||
import Migration0016 from "./Migrations/016_ProjectionThreadWorkUnits.ts";
|
||||
import { Effect } from "effect";
|
||||
|
||||
/**
|
||||
@@ -51,6 +54,9 @@ const loader = Migrator.fromRecord({
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
|
||||
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
|
||||
"16_ProjectionThreadWorkUnits": Migration0016,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
+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,88 @@
|
||||
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_activities
|
||||
ADD COLUMN work_unit_id TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS projection_thread_work_units (
|
||||
work_unit_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
turn_id TEXT NOT NULL,
|
||||
parent_work_unit_id TEXT,
|
||||
kind TEXT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
title TEXT NOT NULL,
|
||||
detail TEXT,
|
||||
spawned_by_activity_id TEXT,
|
||||
provider_refs_json TEXT,
|
||||
started_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL,
|
||||
completed_at TEXT
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_turn
|
||||
ON projection_thread_work_units(thread_id, turn_id, started_at)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_parent
|
||||
ON projection_thread_work_units(thread_id, parent_work_unit_id, started_at)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
INSERT INTO projection_thread_work_units (
|
||||
work_unit_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
parent_work_unit_id,
|
||||
kind,
|
||||
state,
|
||||
title,
|
||||
detail,
|
||||
spawned_by_activity_id,
|
||||
provider_refs_json,
|
||||
started_at,
|
||||
updated_at,
|
||||
completed_at
|
||||
)
|
||||
SELECT
|
||||
'wu:' || thread_id || ':turn:' || turn_id || ':root',
|
||||
thread_id,
|
||||
turn_id,
|
||||
NULL,
|
||||
'primary_agent',
|
||||
CASE state
|
||||
WHEN 'completed' THEN 'completed'
|
||||
WHEN 'error' THEN 'failed'
|
||||
WHEN 'interrupted' THEN 'stopped'
|
||||
ELSE 'running'
|
||||
END,
|
||||
'Primary agent',
|
||||
NULL,
|
||||
NULL,
|
||||
NULL,
|
||||
COALESCE(started_at, requested_at),
|
||||
COALESCE(completed_at, started_at, requested_at),
|
||||
CASE
|
||||
WHEN state IN ('completed', 'error', 'interrupted') THEN COALESCE(completed_at, started_at, requested_at)
|
||||
ELSE NULL
|
||||
END
|
||||
FROM projection_turns
|
||||
WHERE turn_id IS NOT NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_thread_activities
|
||||
SET work_unit_id = 'wu:' || thread_id || ':turn:' || turn_id || ':root'
|
||||
WHERE turn_id IS NOT NULL
|
||||
AND work_unit_id 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
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
OrchestrationThreadActivityTone,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
@@ -23,6 +24,7 @@ export const ProjectionThreadActivity = Schema.Struct({
|
||||
activityId: EventId,
|
||||
threadId: ThreadId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
workUnitId: Schema.NullOr(WorkUnitId),
|
||||
tone: OrchestrationThreadActivityTone,
|
||||
kind: Schema.String,
|
||||
summary: Schema.String,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import {
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
OrchestrationWorkUnitKind,
|
||||
OrchestrationWorkUnitProviderRefs,
|
||||
OrchestrationWorkUnitState,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
TrimmedNonEmptyString,
|
||||
WorkUnitId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProjectionThreadWorkUnit = Schema.Struct({
|
||||
workUnitId: WorkUnitId,
|
||||
threadId: ThreadId,
|
||||
turnId: TurnId,
|
||||
parentWorkUnitId: Schema.NullOr(WorkUnitId),
|
||||
kind: OrchestrationWorkUnitKind,
|
||||
state: OrchestrationWorkUnitState,
|
||||
title: TrimmedNonEmptyString,
|
||||
detail: Schema.NullOr(TrimmedNonEmptyString),
|
||||
spawnedByActivityId: Schema.NullOr(EventId),
|
||||
providerRefs: Schema.optional(OrchestrationWorkUnitProviderRefs),
|
||||
startedAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
completedAt: Schema.NullOr(IsoDateTime),
|
||||
});
|
||||
export type ProjectionThreadWorkUnit = typeof ProjectionThreadWorkUnit.Type;
|
||||
|
||||
export const ListProjectionThreadWorkUnitsInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type ListProjectionThreadWorkUnitsInput = typeof ListProjectionThreadWorkUnitsInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadWorkUnitsInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type DeleteProjectionThreadWorkUnitsInput = typeof DeleteProjectionThreadWorkUnitsInput.Type;
|
||||
|
||||
export interface ProjectionThreadWorkUnitRepositoryShape {
|
||||
readonly upsert: (
|
||||
workUnit: ProjectionThreadWorkUnit,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadWorkUnitsInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionThreadWorkUnit>, ProjectionRepositoryError>;
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProjectionThreadWorkUnitsInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
export class ProjectionThreadWorkUnitRepository extends ServiceMap.Service<
|
||||
ProjectionThreadWorkUnitRepository,
|
||||
ProjectionThreadWorkUnitRepositoryShape
|
||||
>()("t3/persistence/Services/ProjectionThreadWorkUnits/ProjectionThreadWorkUnitRepository") {}
|
||||
@@ -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
@@ -0,0 +1,149 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PassThrough } from "node:stream";
|
||||
import { query, type SpawnOptions, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
|
||||
|
||||
class FakeClaudeCodeProcess implements SpawnedProcess {
|
||||
readonly stdin = new PassThrough();
|
||||
readonly stdout = new PassThrough();
|
||||
killed = false;
|
||||
exitCode: number | null = null;
|
||||
|
||||
private readonly events = new EventEmitter();
|
||||
private bufferedInput = "";
|
||||
|
||||
constructor(
|
||||
private readonly onMessage: (
|
||||
message: Record<string, unknown>,
|
||||
process: FakeClaudeCodeProcess,
|
||||
) => void,
|
||||
) {
|
||||
this.stdin.setEncoding("utf8");
|
||||
this.stdin.on("data", (chunk: string) => {
|
||||
this.bufferedInput += chunk;
|
||||
this.drainInput();
|
||||
});
|
||||
}
|
||||
|
||||
emitJson(message: unknown): void {
|
||||
this.stdout.write(`${JSON.stringify(message)}\n`);
|
||||
}
|
||||
|
||||
kill(_signal: NodeJS.Signals): boolean {
|
||||
this.killed = true;
|
||||
this.exitCode = 0;
|
||||
this.stdout.end();
|
||||
this.events.emit("exit", 0, null);
|
||||
return true;
|
||||
}
|
||||
|
||||
on(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.on(event, listener);
|
||||
}
|
||||
|
||||
once(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.once(event, listener);
|
||||
}
|
||||
|
||||
off(
|
||||
event: "exit" | "error",
|
||||
listener:
|
||||
| ((code: number | null, signal: NodeJS.Signals | null) => void)
|
||||
| ((error: Error) => void),
|
||||
): void {
|
||||
this.events.off(event, listener);
|
||||
}
|
||||
|
||||
private drainInput(): void {
|
||||
while (true) {
|
||||
const newlineIndex = this.bufferedInput.indexOf("\n");
|
||||
if (newlineIndex === -1) {
|
||||
return;
|
||||
}
|
||||
const line = this.bufferedInput.slice(0, newlineIndex).trim();
|
||||
this.bufferedInput = this.bufferedInput.slice(newlineIndex + 1);
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
this.onMessage(JSON.parse(line) as Record<string, unknown>, this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe("Claude SDK fast mode probe", () => {
|
||||
let activeQuery: ReturnType<typeof query> | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
activeQuery?.close();
|
||||
activeQuery = null;
|
||||
});
|
||||
|
||||
it("passes fast mode through the SDK settings flag", async () => {
|
||||
let spawnOptions: SpawnOptions | undefined;
|
||||
|
||||
activeQuery = query({
|
||||
prompt: emptyPrompt(),
|
||||
options: {
|
||||
persistSession: false,
|
||||
settings: {
|
||||
fastMode: true,
|
||||
},
|
||||
spawnClaudeCodeProcess: (options): SpawnedProcess => {
|
||||
spawnOptions = options;
|
||||
return new FakeClaudeCodeProcess((message, process) => {
|
||||
if (
|
||||
message.type !== "control_request" ||
|
||||
typeof message.request_id !== "string" ||
|
||||
!message.request ||
|
||||
typeof message.request !== "object" ||
|
||||
(message.request as { subtype?: unknown }).subtype !== "initialize"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.emitJson({
|
||||
type: "control_response",
|
||||
response: {
|
||||
subtype: "success",
|
||||
request_id: message.request_id,
|
||||
response: {
|
||||
commands: [],
|
||||
agents: [],
|
||||
output_style: "default",
|
||||
available_output_styles: ["default"],
|
||||
models: [],
|
||||
account: {
|
||||
subscriptionType: "max",
|
||||
},
|
||||
fast_mode_state: "on",
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const initialization = await activeQuery.initializationResult();
|
||||
expect(initialization.fast_mode_state).toBe("on");
|
||||
|
||||
expect(spawnOptions).toBeDefined();
|
||||
const settingsFlagIndex = spawnOptions?.args.indexOf("--settings") ?? -1;
|
||||
expect(settingsFlagIndex).toBeGreaterThan(-1);
|
||||
expect(JSON.parse(spawnOptions?.args[settingsFlagIndex + 1] ?? "")).toEqual({
|
||||
fastMode: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
@@ -776,6 +800,48 @@ 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"),
|
||||
itemId: asItemId("call-collab-1"),
|
||||
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.itemId, "call-collab-1");
|
||||
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
|
||||
assert.equal(firstEvent.value.providerRefs?.providerItemId, "call-collab-1");
|
||||
assert.equal(firstEvent.value.payload.taskId, "turn-child");
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
|
||||
@@ -109,6 +109,14 @@ function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
|
||||
}
|
||||
|
||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||
return value?.trim() ? ProviderItemId.makeUnsafe(value) : undefined;
|
||||
}
|
||||
|
||||
function toTurnStatus(value: unknown): "completed" | "failed" | "cancelled" | "interrupted" {
|
||||
switch (value) {
|
||||
case "completed":
|
||||
@@ -164,7 +172,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 +423,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 } : {}),
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
@@ -217,12 +217,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 +250,7 @@ function makeProviderServiceLayer() {
|
||||
|
||||
return {
|
||||
codex,
|
||||
claude,
|
||||
layer,
|
||||
};
|
||||
}
|
||||
@@ -533,6 +537,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 +600,57 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("recovers stale claudeAgent sessions for sendTurn using persisted cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
|
||||
const initial = yield* provider.startSession(asThreadId("thread-claude-send-turn"), {
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-claude-send-turn"),
|
||||
cwd: "/tmp/project-claude-send-turn",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* routing.claude.stopAll();
|
||||
routing.claude.startSession.mockClear();
|
||||
routing.claude.sendTurn.mockClear();
|
||||
|
||||
yield* provider.sendTurn({
|
||||
threadId: initial.threadId,
|
||||
input: "resume with claude",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
assert.equal(routing.claude.startSession.mock.calls.length, 1);
|
||||
const resumedStartInput = routing.claude.startSession.mock.calls[0]?.[0];
|
||||
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
|
||||
if (resumedStartInput && typeof resumedStartInput === "object") {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
modelOptions?: unknown;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "claudeAgent");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
|
||||
assert.deepEqual(startPayload.modelOptions, {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
|
||||
assert.equal(startPayload.threadId, initial.threadId);
|
||||
}
|
||||
assert.equal(routing.claude.sendTurn.mock.calls.length, 1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("lists no sessions after adapter runtime clears", () =>
|
||||
Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
@@ -589,6 +667,7 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
});
|
||||
|
||||
yield* routing.codex.stopAll();
|
||||
yield* routing.claude.stopAll();
|
||||
|
||||
const remaining = yield* provider.listSessions();
|
||||
assert.equal(remaining.length, 0);
|
||||
@@ -703,7 +782,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 +792,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",
|
||||
@@ -768,7 +847,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
|
||||
threadId: session.threadId,
|
||||
turnId: asTurnId("turn-1"),
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
title: "Ran command",
|
||||
detail: "echo one",
|
||||
},
|
||||
{
|
||||
|
||||
@@ -88,17 +88,29 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
cwd: session.cwd ?? null,
|
||||
model: session.model ?? null,
|
||||
activeTurnId: session.activeTurnId ?? null,
|
||||
lastError: session.lastError ?? null,
|
||||
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
|
||||
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedModelOptions(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return undefined;
|
||||
}
|
||||
const raw = "modelOptions" in runtimePayload ? runtimePayload.modelOptions : undefined;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
|
||||
return raw as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function readPersistedProviderOptions(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
@@ -150,7 +162,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
const upsertSessionBinding = (
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: { readonly providerOptions?: unknown },
|
||||
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
|
||||
) =>
|
||||
directory.upsert({
|
||||
threadId,
|
||||
@@ -213,12 +225,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
|
||||
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
|
||||
|
||||
const resumed = yield* adapter.startSession({
|
||||
threadId: input.binding.threadId,
|
||||
provider: input.binding.provider,
|
||||
...(persistedCwd ? { cwd: persistedCwd } : {}),
|
||||
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
|
||||
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
@@ -292,6 +306,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelOptions: input.modelOptions,
|
||||
providerOptions: input.providerOptions,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* ClaudeAdapter - Claude Agent implementation of the generic provider adapter contract.
|
||||
*
|
||||
* This service owns Claude runtime/session semantics and emits canonical
|
||||
* provider runtime events. It does not perform cross-provider routing, shared
|
||||
* event fan-out, or checkpoint orchestration.
|
||||
*
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and returns the
|
||||
* shared provider-adapter error channel with `provider: "claudeAgent"` context.
|
||||
*
|
||||
* @module ClaudeAdapter
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
|
||||
import type { ProviderAdapterError } from "../Errors.ts";
|
||||
import type { ProviderAdapterShape } from "./ProviderAdapter.ts";
|
||||
|
||||
/**
|
||||
* ClaudeAdapterShape - Service API for the Claude Agent provider adapter.
|
||||
*/
|
||||
export interface ClaudeAdapterShape extends ProviderAdapterShape<ProviderAdapterError> {
|
||||
readonly provider: "claudeAgent";
|
||||
}
|
||||
|
||||
/**
|
||||
* ClaudeAdapter - Service tag for Claude Agent provider adapter operations.
|
||||
*/
|
||||
export class ClaudeAdapter extends ServiceMap.Service<ClaudeAdapter, ClaudeAdapterShape>()(
|
||||
"t3/provider/Services/ClaudeAdapter",
|
||||
) {}
|
||||
@@ -1,8 +1,8 @@
|
||||
/**
|
||||
* ProviderHealth - Provider readiness snapshot service.
|
||||
*
|
||||
* Owns startup-time provider health checks (install/auth reachability) and
|
||||
* exposes the cached results to transport layers.
|
||||
* Owns provider health checks (install/auth reachability) and exposes the
|
||||
* latest results to transport layers.
|
||||
*
|
||||
* @module ProviderHealth
|
||||
*/
|
||||
@@ -12,7 +12,7 @@ import type { Effect } from "effect";
|
||||
|
||||
export interface ProviderHealthShape {
|
||||
/**
|
||||
* Read provider health statuses computed at server startup.
|
||||
* Read the latest provider health statuses.
|
||||
*/
|
||||
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers
|
||||
import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion";
|
||||
import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus";
|
||||
import { ProviderUnsupportedError } from "./provider/Errors";
|
||||
import { makeClaudeAdapterLive } from "./provider/Layers/ClaudeAdapter";
|
||||
import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter";
|
||||
import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry";
|
||||
import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
|
||||
@@ -58,8 +59,12 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
const codexAdapterLayer = makeCodexAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const claudeAdapterLayer = makeClaudeAdapterLive(
|
||||
nativeEventLogger ? { nativeEventLogger } : undefined,
|
||||
);
|
||||
const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(
|
||||
Layer.provide(codexAdapterLayer),
|
||||
Layer.provide(claudeAdapterLayer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
return makeProviderServiceLive(
|
||||
|
||||
@@ -70,6 +70,32 @@ describe("searchWorkspaceEntries", () => {
|
||||
assert.isTrue(result.entries.every((entry) => entry.path.toLowerCase().includes("compo")));
|
||||
});
|
||||
|
||||
it("supports fuzzy subsequence queries for composer path search", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-fuzzy-query-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 10 });
|
||||
const paths = result.entries.map((entry) => entry.path);
|
||||
|
||||
assert.isAbove(result.entries.length, 0);
|
||||
assert.include(paths, "src/components");
|
||||
assert.include(paths, "src/components/Composer.tsx");
|
||||
});
|
||||
|
||||
it("tracks truncation without sorting every fuzzy match", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-fuzzy-limit-");
|
||||
writeFile(cwd, "src/components/Composer.tsx");
|
||||
writeFile(cwd, "src/components/composePrompt.ts");
|
||||
writeFile(cwd, "docs/composition.md");
|
||||
|
||||
const result = await searchWorkspaceEntries({ cwd, query: "cmp", limit: 1 });
|
||||
|
||||
assert.lengthOf(result.entries, 1);
|
||||
assert.isTrue(result.truncated);
|
||||
});
|
||||
|
||||
it("excludes gitignored paths for git repositories", async () => {
|
||||
const cwd = makeTempDir("t3code-workspace-gitignore-");
|
||||
runGit(cwd, ["init"]);
|
||||
|
||||
@@ -28,10 +28,20 @@ const IGNORED_DIRECTORY_NAMES = new Set([
|
||||
|
||||
interface WorkspaceIndex {
|
||||
scannedAt: number;
|
||||
entries: ProjectEntry[];
|
||||
entries: SearchableWorkspaceEntry[];
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
interface SearchableWorkspaceEntry extends ProjectEntry {
|
||||
normalizedPath: string;
|
||||
normalizedName: string;
|
||||
}
|
||||
|
||||
interface RankedWorkspaceEntry {
|
||||
entry: SearchableWorkspaceEntry;
|
||||
score: number;
|
||||
}
|
||||
|
||||
const workspaceIndexCache = new Map<string, WorkspaceIndex>();
|
||||
const inFlightWorkspaceIndexBuilds = new Map<string, Promise<WorkspaceIndex>>();
|
||||
|
||||
@@ -55,6 +65,15 @@ function basenameOf(input: string): string {
|
||||
return input.slice(separatorIndex + 1);
|
||||
}
|
||||
|
||||
function toSearchableWorkspaceEntry(entry: ProjectEntry): SearchableWorkspaceEntry {
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
return {
|
||||
...entry,
|
||||
normalizedPath,
|
||||
normalizedName: basenameOf(normalizedPath),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuery(input: string): string {
|
||||
return input
|
||||
.trim()
|
||||
@@ -62,20 +81,120 @@ function normalizeQuery(input: string): string {
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
function scoreEntry(entry: ProjectEntry, query: string): number {
|
||||
function scoreSubsequenceMatch(value: string, query: string): number | null {
|
||||
if (!query) return 0;
|
||||
|
||||
let queryIndex = 0;
|
||||
let firstMatchIndex = -1;
|
||||
let previousMatchIndex = -1;
|
||||
let gapPenalty = 0;
|
||||
|
||||
for (let valueIndex = 0; valueIndex < value.length; valueIndex += 1) {
|
||||
if (value[valueIndex] !== query[queryIndex]) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (firstMatchIndex === -1) {
|
||||
firstMatchIndex = valueIndex;
|
||||
}
|
||||
if (previousMatchIndex !== -1) {
|
||||
gapPenalty += valueIndex - previousMatchIndex - 1;
|
||||
}
|
||||
|
||||
previousMatchIndex = valueIndex;
|
||||
queryIndex += 1;
|
||||
if (queryIndex === query.length) {
|
||||
const spanPenalty = valueIndex - firstMatchIndex + 1 - query.length;
|
||||
const lengthPenalty = Math.min(64, value.length - query.length);
|
||||
return firstMatchIndex * 2 + gapPenalty * 3 + spanPenalty + lengthPenalty;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function scoreEntry(entry: SearchableWorkspaceEntry, query: string): number | null {
|
||||
if (!query) {
|
||||
return entry.kind === "directory" ? 0 : 1;
|
||||
}
|
||||
|
||||
const normalizedPath = entry.path.toLowerCase();
|
||||
const normalizedName = basenameOf(normalizedPath);
|
||||
const { normalizedPath, normalizedName } = entry;
|
||||
|
||||
if (normalizedName === query) return 0;
|
||||
if (normalizedPath === query) return 1;
|
||||
if (normalizedName.startsWith(query)) return 2;
|
||||
if (normalizedPath.startsWith(query)) return 3;
|
||||
if (normalizedPath.includes(`/${query}`)) return 4;
|
||||
return 5;
|
||||
if (normalizedName.includes(query)) return 5;
|
||||
if (normalizedPath.includes(query)) return 6;
|
||||
|
||||
const nameFuzzyScore = scoreSubsequenceMatch(normalizedName, query);
|
||||
if (nameFuzzyScore !== null) {
|
||||
return 100 + nameFuzzyScore;
|
||||
}
|
||||
|
||||
const pathFuzzyScore = scoreSubsequenceMatch(normalizedPath, query);
|
||||
if (pathFuzzyScore !== null) {
|
||||
return 200 + pathFuzzyScore;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function compareRankedWorkspaceEntries(
|
||||
left: RankedWorkspaceEntry,
|
||||
right: RankedWorkspaceEntry,
|
||||
): number {
|
||||
const scoreDelta = left.score - right.score;
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.entry.path.localeCompare(right.entry.path);
|
||||
}
|
||||
|
||||
function findInsertionIndex(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
): number {
|
||||
let low = 0;
|
||||
let high = rankedEntries.length;
|
||||
|
||||
while (low < high) {
|
||||
const middle = low + Math.floor((high - low) / 2);
|
||||
const current = rankedEntries[middle];
|
||||
if (!current) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (compareRankedWorkspaceEntries(candidate, current) < 0) {
|
||||
high = middle;
|
||||
} else {
|
||||
low = middle + 1;
|
||||
}
|
||||
}
|
||||
|
||||
return low;
|
||||
}
|
||||
|
||||
function insertRankedEntry(
|
||||
rankedEntries: RankedWorkspaceEntry[],
|
||||
candidate: RankedWorkspaceEntry,
|
||||
limit: number,
|
||||
): void {
|
||||
if (limit <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const insertionIndex = findInsertionIndex(rankedEntries, candidate);
|
||||
if (rankedEntries.length < limit) {
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
return;
|
||||
}
|
||||
|
||||
if (insertionIndex >= limit) {
|
||||
return;
|
||||
}
|
||||
|
||||
rankedEntries.splice(insertionIndex, 0, candidate);
|
||||
rankedEntries.pop();
|
||||
}
|
||||
|
||||
function isPathInIgnoredDirectory(relativePath: string): boolean {
|
||||
@@ -253,20 +372,26 @@ async function buildWorkspaceIndexFromGit(cwd: string): Promise<WorkspaceIndex |
|
||||
}
|
||||
}
|
||||
|
||||
const directoryEntries: ProjectEntry[] = [...directorySet]
|
||||
const directoryEntries = [...directorySet]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((directoryPath) => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}));
|
||||
const fileEntries: ProjectEntry[] = [...new Set(filePaths)]
|
||||
.map(
|
||||
(directoryPath): ProjectEntry => ({
|
||||
path: directoryPath,
|
||||
kind: "directory",
|
||||
parentPath: parentPathOf(directoryPath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
const fileEntries = [...new Set(filePaths)]
|
||||
.toSorted((left, right) => left.localeCompare(right))
|
||||
.map((filePath) => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}));
|
||||
.map(
|
||||
(filePath): ProjectEntry => ({
|
||||
path: filePath,
|
||||
kind: "file",
|
||||
parentPath: parentPathOf(filePath),
|
||||
}),
|
||||
)
|
||||
.map(toSearchableWorkspaceEntry);
|
||||
|
||||
const entries = [...directoryEntries, ...fileEntries];
|
||||
return {
|
||||
@@ -284,7 +409,7 @@ async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
const shouldFilterWithGitIgnore = await isInsideGitWorkTree(cwd);
|
||||
|
||||
let pendingDirectories: string[] = [""];
|
||||
const entries: ProjectEntry[] = [];
|
||||
const entries: SearchableWorkspaceEntry[] = [];
|
||||
let truncated = false;
|
||||
|
||||
while (pendingDirectories.length > 0 && !truncated) {
|
||||
@@ -351,11 +476,11 @@ async function buildWorkspaceIndex(cwd: string): Promise<WorkspaceIndex> {
|
||||
continue;
|
||||
}
|
||||
|
||||
const entry: ProjectEntry = {
|
||||
const entry = toSearchableWorkspaceEntry({
|
||||
path: candidate.relativePath,
|
||||
kind: candidate.dirent.isDirectory() ? "directory" : "file",
|
||||
parentPath: parentPathOf(candidate.relativePath),
|
||||
};
|
||||
});
|
||||
entries.push(entry);
|
||||
|
||||
if (candidate.dirent.isDirectory()) {
|
||||
@@ -419,18 +544,22 @@ export async function searchWorkspaceEntries(
|
||||
): Promise<ProjectSearchEntriesResult> {
|
||||
const index = await getWorkspaceIndex(input.cwd);
|
||||
const normalizedQuery = normalizeQuery(input.query);
|
||||
const candidates = normalizedQuery
|
||||
? index.entries.filter((entry) => entry.path.toLowerCase().includes(normalizedQuery))
|
||||
: index.entries;
|
||||
const limit = Math.max(0, Math.floor(input.limit));
|
||||
const rankedEntries: RankedWorkspaceEntry[] = [];
|
||||
let matchedEntryCount = 0;
|
||||
|
||||
const ranked = candidates.toSorted((left, right) => {
|
||||
const scoreDelta = scoreEntry(left, normalizedQuery) - scoreEntry(right, normalizedQuery);
|
||||
if (scoreDelta !== 0) return scoreDelta;
|
||||
return left.path.localeCompare(right.path);
|
||||
});
|
||||
for (const entry of index.entries) {
|
||||
const score = scoreEntry(entry, normalizedQuery);
|
||||
if (score === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
matchedEntryCount += 1;
|
||||
insertRankedEntry(rankedEntries, { entry, score }, limit);
|
||||
}
|
||||
|
||||
return {
|
||||
entries: ranked.slice(0, input.limit),
|
||||
truncated: index.truncated || ranked.length > input.limit,
|
||||
entries: rankedEntries.map((candidate) => candidate.entry),
|
||||
truncated: index.truncated || matchedEntryCount > limit,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.9",
|
||||
"version": "0.0.10",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -42,18 +42,20 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "catalog:",
|
||||
"@rolldown/plugin-babel": "^0.2.0",
|
||||
"@tailwindcss/vite": "^4.0.0",
|
||||
"@tanstack/router-plugin": "^1.161.0",
|
||||
"@types/babel__core": "^7.20.5",
|
||||
"@types/react": "^19.0.0",
|
||||
"@types/react-dom": "^19.0.0",
|
||||
"@vitejs/plugin-react": "^5.1.4",
|
||||
"@vitejs/plugin-react": "^6.0.0",
|
||||
"@vitest/browser-playwright": "^4.0.18",
|
||||
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
|
||||
"msw": "^2.12.10",
|
||||
"playwright": "^1.58.2",
|
||||
"tailwindcss": "^4.0.0",
|
||||
"typescript": "catalog:",
|
||||
"vite": "^8.0.0-beta.12",
|
||||
"vite": "^8.0.0",
|
||||
"vitest": "catalog:",
|
||||
"vitest-browser-react": "^2.0.5"
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - Please do NOT modify this file.
|
||||
*/
|
||||
|
||||
const PACKAGE_VERSION = '2.12.9'
|
||||
const PACKAGE_VERSION = '2.12.10'
|
||||
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
|
||||
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
|
||||
const activeClientIds = new Set()
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Schema } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AppSettingsSchema,
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
getAppModelOptions,
|
||||
getSlashModelOptions,
|
||||
normalizeCustomModelSlugs,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
@@ -20,6 +22,13 @@ describe("normalizeCustomModelSlugs", () => {
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
|
||||
it("normalizes provider-specific aliases for claude", () => {
|
||||
expect(normalizeCustomModelSlugs(["sonnet"], "claudeAgent")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeAgent")).toEqual([
|
||||
"claude/custom-sonnet",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
@@ -28,6 +37,7 @@ describe("getAppModelOptions", () => {
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.4",
|
||||
"gpt-5.4-mini",
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
@@ -45,6 +55,13 @@ describe("getAppModelOptions", () => {
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
it("keeps a saved custom provider model available as an exact slug option", () => {
|
||||
const options = getAppModelOptions("claudeAgent", ["claude/custom-opus"], "claude/custom-opus");
|
||||
|
||||
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAppModelSelection", () => {
|
||||
@@ -59,16 +76,40 @@ describe("resolveAppModelSelection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getSlashModelOptions", () => {
|
||||
it("includes saved custom model slugs for /model command suggestions", () => {
|
||||
const options = getSlashModelOptions("codex", ["custom/internal-model"], "", "gpt-5.3-codex");
|
||||
|
||||
expect(options.some((option) => option.slug === "custom/internal-model")).toBe(true);
|
||||
});
|
||||
|
||||
it("filters slash-model suggestions across built-in and custom model names", () => {
|
||||
const options = getSlashModelOptions("codex", ["openai/gpt-oss-120b"], "oss", "gpt-5.3-codex");
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual(["openai/gpt-oss-120b"]);
|
||||
describe("timestamp format defaults", () => {
|
||||
it("defaults timestamp format to locale", () => {
|
||||
expect(DEFAULT_TIMESTAMP_FORMAT).toBe("locale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider-specific custom models", () => {
|
||||
it("includes provider-specific custom slugs in non-codex model lists", () => {
|
||||
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
|
||||
|
||||
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("AppSettingsSchema", () => {
|
||||
it("fills decoding defaults for persisted settings that predate newer keys", () => {
|
||||
const decode = Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema));
|
||||
|
||||
expect(
|
||||
decode(
|
||||
JSON.stringify({
|
||||
codexBinaryPath: "/usr/local/bin/codex",
|
||||
confirmThreadDelete: false,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
codexBinaryPath: "/usr/local/bin/codex",
|
||||
codexHomePath: "",
|
||||
defaultThreadEnvMode: "local",
|
||||
confirmThreadDelete: false,
|
||||
enableAssistantStreaming: false,
|
||||
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
});
|
||||
});
|
||||
});
|
||||
+46
-122
@@ -1,29 +1,46 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
||||
import { EnvMode } from "./components/BranchToolbar.logic";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
|
||||
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
|
||||
export type TimestampFormat = typeof TimestampFormat.Type;
|
||||
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
||||
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
const withDefaults =
|
||||
<
|
||||
S extends Schema.Top & Schema.WithoutConstructorDefault,
|
||||
D extends S["~type.make.in"] & S["Encoded"],
|
||||
>(
|
||||
fallback: () => D,
|
||||
) =>
|
||||
(schema: S) =>
|
||||
schema.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(fallback())),
|
||||
Schema.withDecodingDefault(() => fallback()),
|
||||
);
|
||||
|
||||
export const AppSettingsSchema = Schema.Struct({
|
||||
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
|
||||
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
|
||||
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
@@ -34,10 +51,6 @@ export interface AppModelOption {
|
||||
|
||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let cachedRawSettings: string | null | undefined;
|
||||
let cachedSnapshot: AppSettings = DEFAULT_APP_SETTINGS;
|
||||
|
||||
export function normalizeCustomModelSlugs(
|
||||
models: Iterable<string | null | undefined>,
|
||||
provider: ProviderKind = "codex",
|
||||
@@ -71,9 +84,9 @@ function normalizeAppSettings(settings: AppSettings): AppSettings {
|
||||
return {
|
||||
...settings,
|
||||
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
|
||||
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
@@ -143,112 +156,23 @@ export function resolveAppModelSelection(
|
||||
);
|
||||
}
|
||||
|
||||
export function getSlashModelOptions(
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
query: string,
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const normalizedQuery = query.trim().toLowerCase();
|
||||
const options = getAppModelOptions(provider, customModels, selectedModel);
|
||||
if (!normalizedQuery) {
|
||||
return options;
|
||||
}
|
||||
|
||||
return options.filter((option) => {
|
||||
const searchSlug = option.slug.toLowerCase();
|
||||
const searchName = option.name.toLowerCase();
|
||||
return searchSlug.includes(normalizedQuery) || searchName.includes(normalizedQuery);
|
||||
});
|
||||
}
|
||||
|
||||
function emitChange(): void {
|
||||
for (const listener of listeners) {
|
||||
listener();
|
||||
}
|
||||
}
|
||||
|
||||
function parsePersistedSettings(value: string | null): AppSettings {
|
||||
if (!value) {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeAppSettings(Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema))(value));
|
||||
} catch {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
}
|
||||
|
||||
export function getAppSettingsSnapshot(): AppSettings {
|
||||
if (typeof window === "undefined") {
|
||||
return DEFAULT_APP_SETTINGS;
|
||||
}
|
||||
|
||||
const raw = window.localStorage.getItem(APP_SETTINGS_STORAGE_KEY);
|
||||
if (raw === cachedRawSettings) {
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
cachedRawSettings = raw;
|
||||
cachedSnapshot = parsePersistedSettings(raw);
|
||||
return cachedSnapshot;
|
||||
}
|
||||
|
||||
function persistSettings(next: AppSettings): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const raw = JSON.stringify(next);
|
||||
try {
|
||||
if (raw !== cachedRawSettings) {
|
||||
window.localStorage.setItem(APP_SETTINGS_STORAGE_KEY, raw);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort persistence only.
|
||||
}
|
||||
|
||||
cachedRawSettings = raw;
|
||||
cachedSnapshot = next;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.push(listener);
|
||||
|
||||
const onStorage = (event: StorageEvent) => {
|
||||
if (event.key === APP_SETTINGS_STORAGE_KEY) {
|
||||
emitChange();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("storage", onStorage);
|
||||
return () => {
|
||||
listeners = listeners.filter((entry) => entry !== listener);
|
||||
window.removeEventListener("storage", onStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function useAppSettings() {
|
||||
const settings = useSyncExternalStore(
|
||||
subscribe,
|
||||
getAppSettingsSnapshot,
|
||||
() => DEFAULT_APP_SETTINGS,
|
||||
const [settings, setSettings] = useLocalStorage(
|
||||
APP_SETTINGS_STORAGE_KEY,
|
||||
DEFAULT_APP_SETTINGS,
|
||||
AppSettingsSchema,
|
||||
);
|
||||
|
||||
const updateSettings = useCallback((patch: Partial<AppSettings>) => {
|
||||
const next = normalizeAppSettings(
|
||||
Schema.decodeSync(AppSettingsSchema)({
|
||||
...getAppSettingsSnapshot(),
|
||||
...patch,
|
||||
}),
|
||||
);
|
||||
persistSettings(next);
|
||||
emitChange();
|
||||
}, []);
|
||||
const updateSettings = useCallback(
|
||||
(patch: Partial<AppSettings>) => {
|
||||
setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
|
||||
},
|
||||
[setSettings],
|
||||
);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
persistSettings(DEFAULT_APP_SETTINGS);
|
||||
emitChange();
|
||||
}, []);
|
||||
setSettings(DEFAULT_APP_SETTINGS);
|
||||
}, [setSettings]);
|
||||
|
||||
return {
|
||||
settings,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { GitBranch } from "@t3tools/contracts";
|
||||
import { Schema } from "effect";
|
||||
|
||||
export type EnvMode = "local" | "worktree";
|
||||
export const EnvMode = Schema.Literals(["local", "worktree"]);
|
||||
export type EnvMode = typeof EnvMode.Type;
|
||||
|
||||
export function resolveEffectiveEnvMode(input: {
|
||||
activeWorktreePath: string | null;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ThreadId } from "@t3tools/contracts";
|
||||
import { FolderIcon, GitForkIcon } from "lucide-react";
|
||||
import { useCallback } from "react";
|
||||
|
||||
import { newCommandId } from "../lib/utils";
|
||||
@@ -11,7 +12,12 @@ import {
|
||||
resolveEffectiveEnvMode,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { BranchToolbarBranchSelector } from "./BranchToolbarBranchSelector";
|
||||
import { Button } from "./ui/button";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "./ui/select";
|
||||
|
||||
const envModeItems = [
|
||||
{ value: "local", label: "Local" },
|
||||
{ value: "worktree", label: "New worktree" },
|
||||
] as const;
|
||||
|
||||
interface BranchToolbarProps {
|
||||
threadId: ThreadId;
|
||||
@@ -104,23 +110,50 @@ export default function BranchToolbar({
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl items-center justify-between px-5 pb-3 pt-1">
|
||||
<div className="flex items-center gap-2">
|
||||
{envLocked || activeWorktreePath ? (
|
||||
<span className="border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
|
||||
{activeWorktreePath ? "Worktree" : "Local"}
|
||||
</span>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
className="text-muted-foreground/70 hover:text-foreground/80"
|
||||
size="xs"
|
||||
onClick={() => onEnvModeChange(effectiveEnvMode === "local" ? "worktree" : "local")}
|
||||
>
|
||||
{effectiveEnvMode === "worktree" ? "New worktree" : "Local"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{envLocked || activeWorktreePath ? (
|
||||
<span className="inline-flex items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:text-xs">
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<GitForkIcon className="size-3" />
|
||||
Worktree
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<FolderIcon className="size-3" />
|
||||
Local
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
) : (
|
||||
<Select
|
||||
value={effectiveEnvMode}
|
||||
onValueChange={(value) => onEnvModeChange(value as EnvMode)}
|
||||
items={envModeItems}
|
||||
>
|
||||
<SelectTrigger variant="ghost" size="xs" className="font-medium">
|
||||
{effectiveEnvMode === "worktree" ? (
|
||||
<GitForkIcon className="size-3" />
|
||||
) : (
|
||||
<FolderIcon className="size-3" />
|
||||
)}
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectPopup>
|
||||
<SelectItem value="local">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<FolderIcon className="size-3" />
|
||||
Local
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value="worktree">
|
||||
<span className="inline-flex items-center gap-1.5">
|
||||
<GitForkIcon className="size-3" />
|
||||
New worktree
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
)}
|
||||
|
||||
<BranchToolbarBranchSelector
|
||||
activeProjectCwd={activeProject.cwd}
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
getSharedHighlighter,
|
||||
type DiffsHighlighter,
|
||||
type SupportedLanguages,
|
||||
} from "@pierre/diffs";
|
||||
import { DiffsHighlighter, getSharedHighlighter, SupportedLanguages } from "@pierre/diffs";
|
||||
import { CheckIcon, CopyIcon } from "lucide-react";
|
||||
import React, {
|
||||
Children,
|
||||
@@ -20,13 +16,13 @@ import React, {
|
||||
import type { Components } from "react-markdown";
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor } from "../terminal-links";
|
||||
|
||||
class CodeHighlightErrorBoundary extends React.Component<
|
||||
{ fallback: ReactNode; children: ReactNode },
|
||||
@@ -213,7 +209,12 @@ function SuspenseShikiCodeBlock({
|
||||
const highlightedHtml = useMemo(() => {
|
||||
try {
|
||||
return highlighter.codeToHtml(code, { lang: language, theme: themeName });
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// Log highlighting failures for debugging while falling back to plain text
|
||||
console.warn(
|
||||
`Code highlighting failed for language "${language}", falling back to plain text.`,
|
||||
error instanceof Error ? error.message : error,
|
||||
);
|
||||
// If highlighting fails for this language, render as plain text
|
||||
return highlighter.codeToHtml(code, { lang: "text", theme: themeName });
|
||||
}
|
||||
@@ -254,7 +255,7 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
event.stopPropagation();
|
||||
const api = readNativeApi();
|
||||
if (api) {
|
||||
void api.shell.openInEditor(targetPath, preferredTerminalEditor());
|
||||
void openInPreferredEditor(api, targetPath);
|
||||
} else {
|
||||
console.warn("Native API not found. Unable to open file in editor.");
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type WsWelcomePayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
OrchestrationSessionStatus,
|
||||
} from "@t3tools/contracts";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { HttpResponse, http, ws } from "msw";
|
||||
@@ -20,6 +21,11 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
@@ -148,10 +154,30 @@ function createAssistantMessage(options: { id: MessageId; text: string; offsetSe
|
||||
};
|
||||
}
|
||||
|
||||
function createTerminalContext(input: {
|
||||
id: string;
|
||||
terminalLabel: string;
|
||||
lineStart: number;
|
||||
lineEnd: number;
|
||||
text: string;
|
||||
}): TerminalContextDraft {
|
||||
return {
|
||||
id: input.id,
|
||||
threadId: THREAD_ID,
|
||||
terminalId: `terminal-${input.id}`,
|
||||
terminalLabel: input.terminalLabel,
|
||||
lineStart: input.lineStart,
|
||||
lineEnd: input.lineEnd,
|
||||
text: input.text,
|
||||
createdAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
targetAttachmentCount?: number;
|
||||
sessionStatus?: OrchestrationSessionStatus;
|
||||
}): OrchestrationReadModel {
|
||||
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
|
||||
|
||||
@@ -218,10 +244,11 @@ function createSnapshotForTargetUser(options: {
|
||||
messages,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "ready",
|
||||
status: options.sessionStatus ?? "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
@@ -272,6 +299,7 @@ function addThreadToSnapshot(
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId,
|
||||
@@ -342,6 +370,8 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
id: "plan-browser-test",
|
||||
turnId: null,
|
||||
planMarkdown,
|
||||
implementedAt: null,
|
||||
implementationThreadId: null,
|
||||
createdAt: isoAt(1_000),
|
||||
updatedAt: isoAt(1_001),
|
||||
},
|
||||
@@ -353,7 +383,8 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function resolveWsRpc(tag: string): unknown {
|
||||
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
const tag = body._tag;
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
}
|
||||
@@ -395,6 +426,19 @@ function resolveWsRpc(tag: string): unknown {
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
if (tag === WS_METHODS.terminalOpen) {
|
||||
return {
|
||||
threadId: typeof body.threadId === "string" ? body.threadId : THREAD_ID,
|
||||
terminalId: typeof body.terminalId === "string" ? body.terminalId : "default",
|
||||
cwd: typeof body.cwd === "string" ? body.cwd : "/repo/project",
|
||||
status: "running",
|
||||
pid: 123,
|
||||
history: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: NOW_ISO,
|
||||
};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -423,7 +467,7 @@ const worker = setupWorker(
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
result: resolveWsRpc(request.body),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -514,6 +558,13 @@ async function waitForComposerEditor(): Promise<HTMLElement> {
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForSendButton(): Promise<HTMLButtonElement> {
|
||||
return waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Send message"]'),
|
||||
"Unable to find send button.",
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForInteractionModeButton(
|
||||
expectedLabel: "Chat" | "Plan",
|
||||
): Promise<HTMLButtonElement> {
|
||||
@@ -994,6 +1045,188 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps backspaced terminal context pills removed when a new one is added", async () => {
|
||||
const removedLabel = "Terminal 1 lines 1-2";
|
||||
const addedLabel = "Terminal 2 lines 9-10";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-removed",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 1,
|
||||
lineEnd: 2,
|
||||
text: "bun i\nno changes",
|
||||
}),
|
||||
);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-terminal-pill-backspace" as MessageId,
|
||||
targetText: "terminal pill backspace target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
composerEditor.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Backspace",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[THREAD_ID]).toBeUndefined();
|
||||
expect(document.body.textContent).not.toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-added",
|
||||
terminalLabel: "Terminal 2",
|
||||
lineStart: 9,
|
||||
lineEnd: 10,
|
||||
text: "git status\nOn branch main",
|
||||
}),
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[THREAD_ID];
|
||||
expect(draft?.terminalContexts.map((context) => context.id)).toEqual(["ctx-added"]);
|
||||
expect(document.body.textContent).toContain(addedLabel);
|
||||
expect(document.body.textContent).not.toContain(removedLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("disables send when the composer only contains an expired terminal pill", async () => {
|
||||
const expiredLabel = "Terminal 1 line 4";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-expired-only",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
}),
|
||||
);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-expired-pill-disabled" as MessageId,
|
||||
targetText: "expired pill disabled target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(expiredLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(true);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("warns when sending text while omitting expired terminal pills", async () => {
|
||||
const expiredLabel = "Terminal 1 line 4";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
THREAD_ID,
|
||||
createTerminalContext({
|
||||
id: "ctx-expired-send-warning",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
}),
|
||||
);
|
||||
useComposerDraftStore
|
||||
.getState()
|
||||
.setPrompt(THREAD_ID, `yoo${INLINE_TERMINAL_CONTEXT_PLACEHOLDER}waddup`);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-expired-pill-warning" as MessageId,
|
||||
targetText: "expired pill warning target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(expiredLabel);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const sendButton = await waitForSendButton();
|
||||
expect(sendButton.disabled).toBe(false);
|
||||
sendButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(document.body.textContent).toContain(
|
||||
"Expired terminal context omitted from message",
|
||||
);
|
||||
expect(document.body.textContent).not.toContain(expiredLabel);
|
||||
expect(document.body.textContent).toContain("yoowaddup");
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a pointer cursor for the running stop button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-stop-button-cursor" as MessageId,
|
||||
targetText: "stop button cursor target",
|
||||
sessionStatus: "running",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const stopButton = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]'),
|
||||
"Unable to find stop generation button.",
|
||||
);
|
||||
|
||||
expect(getComputedStyle(stopButton).cursor).toBe("pointer");
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the new thread selected after clicking the new-thread button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -1048,6 +1281,130 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a new thread from the global chat.new shortcut", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-chat-shortcut-test" as MessageId,
|
||||
targetText: "chat shortcut test",
|
||||
}),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
keybindings: [
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "o",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: true,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a new draft thread UUID from the shortcut.",
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a fresh draft after the previous draft thread is promoted", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-promoted-draft-shortcut-test" as MessageId,
|
||||
targetText: "promoted draft shortcut test",
|
||||
}),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
keybindings: [
|
||||
{
|
||||
command: "chat.new",
|
||||
shortcut: {
|
||||
key: "o",
|
||||
metaKey: false,
|
||||
ctrlKey: false,
|
||||
shiftKey: true,
|
||||
altKey: false,
|
||||
modKey: true,
|
||||
},
|
||||
whenAst: {
|
||||
type: "not",
|
||||
node: { type: "identifier", name: "terminalFocus" },
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
await newThreadButton.click();
|
||||
|
||||
const promotedThreadPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a promoted draft thread UUID.",
|
||||
);
|
||||
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
|
||||
|
||||
const { syncServerReadModel } = useStore.getState();
|
||||
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
|
||||
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
|
||||
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
const freshThreadPath = await waitForURL(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath,
|
||||
"Shortcut should create a fresh draft instead of reusing the promoted thread.",
|
||||
);
|
||||
expect(freshThreadPath).not.toBe(promotedThreadPath);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps long proposed plans lightweight until the user expands them", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
|
||||
|
||||
describe("deriveComposerSendState", () => {
|
||||
it("treats expired terminal pills as non-sendable content", () => {
|
||||
const state = deriveComposerSendState({
|
||||
prompt: "\uFFFC",
|
||||
imageCount: 0,
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T12:52:29.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(state.trimmedPrompt).toBe("");
|
||||
expect(state.sendableTerminalContexts).toEqual([]);
|
||||
expect(state.expiredTerminalContextCount).toBe(1);
|
||||
expect(state.hasSendableContent).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps text sendable while excluding expired terminal pills", () => {
|
||||
const state = deriveComposerSendState({
|
||||
prompt: `yoo \uFFFC waddup`,
|
||||
imageCount: 0,
|
||||
terminalContexts: [
|
||||
{
|
||||
id: "ctx-expired",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
terminalId: "default",
|
||||
terminalLabel: "Terminal 1",
|
||||
lineStart: 4,
|
||||
lineEnd: 4,
|
||||
text: "",
|
||||
createdAt: "2026-03-17T12:52:29.000Z",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(state.trimmedPrompt).toBe("yoo waddup");
|
||||
expect(state.expiredTerminalContextCount).toBe(1);
|
||||
expect(state.hasSendableContent).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildExpiredTerminalContextToastCopy", () => {
|
||||
it("formats clear empty-state guidance", () => {
|
||||
expect(buildExpiredTerminalContextToastCopy(1, "empty")).toEqual({
|
||||
title: "Expired terminal context won't be sent",
|
||||
description: "Remove it or re-add it to include terminal output.",
|
||||
});
|
||||
});
|
||||
|
||||
it("formats omission guidance for sent messages", () => {
|
||||
expect(buildExpiredTerminalContextToastCopy(2, "omitted")).toEqual({
|
||||
title: "Expired terminal contexts omitted from message",
|
||||
description: "Re-add it if you want that terminal output included.",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
import { ProjectId, type ProviderKind, type ThreadId } from "@t3tools/contracts";
|
||||
import { type ChatMessage, type Thread } from "../types";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { getAppModelOptions } from "../appSettings";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
import { Schema } from "effect";
|
||||
import {
|
||||
filterTerminalContextsWithText,
|
||||
stripInlineTerminalContextPlaceholders,
|
||||
type TerminalContextDraft,
|
||||
} from "../lib/terminalContext";
|
||||
|
||||
export const LAST_INVOKED_SCRIPT_BY_PROJECT_KEY = "t3code:last-invoked-script-by-project";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
|
||||
export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.String);
|
||||
|
||||
export function buildLocalDraftThread(
|
||||
threadId: ThreadId,
|
||||
draftThread: DraftThreadState,
|
||||
fallbackModel: string,
|
||||
error: string | null,
|
||||
): Thread {
|
||||
return {
|
||||
id: threadId,
|
||||
codexThreadId: null,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
model: fallbackModel,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
session: null,
|
||||
messages: [],
|
||||
error,
|
||||
createdAt: draftThread.createdAt,
|
||||
latestTurn: null,
|
||||
lastVisitedAt: draftThread.createdAt,
|
||||
branch: draftThread.branch,
|
||||
worktreePath: draftThread.worktreePath,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function revokeBlobPreviewUrl(previewUrl: string | undefined): void {
|
||||
if (!previewUrl || typeof URL === "undefined" || !previewUrl.startsWith("blob:")) {
|
||||
return;
|
||||
}
|
||||
URL.revokeObjectURL(previewUrl);
|
||||
}
|
||||
|
||||
export function revokeUserMessagePreviewUrls(message: ChatMessage): void {
|
||||
if (message.role !== "user" || !message.attachments) {
|
||||
return;
|
||||
}
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") {
|
||||
continue;
|
||||
}
|
||||
revokeBlobPreviewUrl(attachment.previewUrl);
|
||||
}
|
||||
}
|
||||
|
||||
export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[] {
|
||||
if (message.role !== "user" || !message.attachments) {
|
||||
return [];
|
||||
}
|
||||
const previewUrls: string[] = [];
|
||||
for (const attachment of message.attachments) {
|
||||
if (attachment.type !== "image") continue;
|
||||
if (!attachment.previewUrl || !attachment.previewUrl.startsWith("blob:")) continue;
|
||||
previewUrls.push(attachment.previewUrl);
|
||||
}
|
||||
return previewUrls;
|
||||
}
|
||||
|
||||
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
|
||||
|
||||
export interface PullRequestDialogState {
|
||||
initialReference: string | null;
|
||||
key: number;
|
||||
}
|
||||
|
||||
export function readFileAsDataUrl(file: File): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.addEventListener("load", () => {
|
||||
if (typeof reader.result === "string") {
|
||||
resolve(reader.result);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Could not read image data."));
|
||||
});
|
||||
reader.addEventListener("error", () => {
|
||||
reject(reader.error ?? new Error("Failed to read image."));
|
||||
});
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
export function buildTemporaryWorktreeBranchName(): string {
|
||||
// Keep the 8-hex suffix shape for backend temporary-branch detection.
|
||||
const token = randomUUID().slice(0, 8).toLowerCase();
|
||||
return `${WORKTREE_BRANCH_PREFIX}/${token}`;
|
||||
}
|
||||
|
||||
export function cloneComposerImageForRetry(
|
||||
image: ComposerImageAttachment,
|
||||
): ComposerImageAttachment {
|
||||
if (typeof URL === "undefined" || !image.previewUrl.startsWith("blob:")) {
|
||||
return image;
|
||||
}
|
||||
try {
|
||||
return {
|
||||
...image,
|
||||
previewUrl: URL.createObjectURL(image.file),
|
||||
};
|
||||
} catch {
|
||||
return image;
|
||||
}
|
||||
}
|
||||
|
||||
export function getCustomModelOptionsByProvider(settings: {
|
||||
customCodexModels: readonly string[];
|
||||
customClaudeModels: readonly string[];
|
||||
}): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
return {
|
||||
codex: getAppModelOptions("codex", settings.customCodexModels),
|
||||
claudeAgent: getAppModelOptions("claudeAgent", settings.customClaudeModels),
|
||||
};
|
||||
}
|
||||
|
||||
export function deriveComposerSendState(options: {
|
||||
prompt: string;
|
||||
imageCount: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
}): {
|
||||
trimmedPrompt: string;
|
||||
sendableTerminalContexts: TerminalContextDraft[];
|
||||
expiredTerminalContextCount: number;
|
||||
hasSendableContent: boolean;
|
||||
} {
|
||||
const trimmedPrompt = stripInlineTerminalContextPlaceholders(options.prompt).trim();
|
||||
const sendableTerminalContexts = filterTerminalContextsWithText(options.terminalContexts);
|
||||
const expiredTerminalContextCount =
|
||||
options.terminalContexts.length - sendableTerminalContexts.length;
|
||||
return {
|
||||
trimmedPrompt,
|
||||
sendableTerminalContexts,
|
||||
expiredTerminalContextCount,
|
||||
hasSendableContent:
|
||||
trimmedPrompt.length > 0 || options.imageCount > 0 || sendableTerminalContexts.length > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildExpiredTerminalContextToastCopy(
|
||||
expiredTerminalContextCount: number,
|
||||
variant: "omitted" | "empty",
|
||||
): { title: string; description: string } {
|
||||
const count = Math.max(1, Math.floor(expiredTerminalContextCount));
|
||||
const noun = count === 1 ? "Expired terminal context" : "Expired terminal contexts";
|
||||
if (variant === "empty") {
|
||||
return {
|
||||
title: `${noun} won't be sent`,
|
||||
description: "Remove it or re-add it to include terminal output.",
|
||||
};
|
||||
}
|
||||
return {
|
||||
title: `${noun} omitted from message`,
|
||||
description: "Re-add it if you want that terminal output included.",
|
||||
};
|
||||
}
|
||||
+1038
-2933
File diff suppressed because it is too large.
Load diff
@@ -26,8 +26,10 @@ import {
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
KEY_BACKSPACE_COMMAND,
|
||||
$getRoot,
|
||||
DecoratorNode,
|
||||
type ElementNode,
|
||||
type LexicalNode,
|
||||
type SerializedLexicalNode,
|
||||
TextNode,
|
||||
type EditorConfig,
|
||||
type EditorState,
|
||||
@@ -36,21 +38,39 @@ import {
|
||||
type Spread,
|
||||
} from "lexical";
|
||||
import {
|
||||
createContext,
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useImperativeHandle,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
type ClipboardEventHandler,
|
||||
type ReactElement,
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
|
||||
import {
|
||||
clampCollapsedComposerCursor,
|
||||
collapseExpandedComposerCursor,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToInlineToken,
|
||||
} from "~/composer-logic";
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry, inferEntryKindFromPath } from "~/vscode-icons";
|
||||
import {
|
||||
COMPOSER_INLINE_CHIP_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
|
||||
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
|
||||
} from "./composerInlineChip";
|
||||
import { ComposerPendingTerminalContextChip } from "./chat/ComposerPendingTerminalContexts";
|
||||
|
||||
const COMPOSER_EDITOR_HMR_KEY = `composer-editor-${Math.random().toString(36).slice(2)}`;
|
||||
|
||||
@@ -63,6 +83,21 @@ type SerializedComposerMentionNode = Spread<
|
||||
SerializedTextNode
|
||||
>;
|
||||
|
||||
type SerializedComposerTerminalContextNode = Spread<
|
||||
{
|
||||
context: TerminalContextDraft;
|
||||
type: "composer-terminal-context";
|
||||
version: 1;
|
||||
},
|
||||
SerializedLexicalNode
|
||||
>;
|
||||
|
||||
const ComposerTerminalContextActionsContext = createContext<{
|
||||
onRemoveTerminalContext: (contextId: string) => void;
|
||||
}>({
|
||||
onRemoveTerminalContext: () => {},
|
||||
});
|
||||
|
||||
class ComposerMentionNode extends TextNode {
|
||||
__path: string;
|
||||
|
||||
@@ -95,8 +130,7 @@ class ComposerMentionNode extends TextNode {
|
||||
|
||||
override createDOM(_config: EditorConfig): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className =
|
||||
"inline-flex select-none items-center gap-1 rounded-md border border-border/70 bg-accent/40 px-1.5 py-px font-medium text-[12px] leading-[1.1] text-foreground align-middle";
|
||||
dom.className = COMPOSER_INLINE_CHIP_CLASS_NAME;
|
||||
dom.contentEditable = "false";
|
||||
dom.setAttribute("spellcheck", "false");
|
||||
renderMentionChipDom(dom, this.__path);
|
||||
@@ -136,15 +170,76 @@ function $createComposerMentionNode(path: string): ComposerMentionNode {
|
||||
return $applyNodeReplacement(new ComposerMentionNode(path));
|
||||
}
|
||||
|
||||
function inferMentionPathKind(pathValue: string): "file" | "directory" {
|
||||
const base = basenameOfPath(pathValue);
|
||||
if (base.startsWith(".") && !base.slice(1).includes(".")) {
|
||||
return "directory";
|
||||
function ComposerTerminalContextDecorator(props: { context: TerminalContextDraft }) {
|
||||
return <ComposerPendingTerminalContextChip context={props.context} />;
|
||||
}
|
||||
|
||||
class ComposerTerminalContextNode extends DecoratorNode<ReactElement> {
|
||||
__context: TerminalContextDraft;
|
||||
|
||||
static override getType(): string {
|
||||
return "composer-terminal-context";
|
||||
}
|
||||
if (base.includes(".")) {
|
||||
return "file";
|
||||
|
||||
static override clone(node: ComposerTerminalContextNode): ComposerTerminalContextNode {
|
||||
return new ComposerTerminalContextNode(node.__context, node.__key);
|
||||
}
|
||||
return "directory";
|
||||
|
||||
static override importJSON(
|
||||
serializedNode: SerializedComposerTerminalContextNode,
|
||||
): ComposerTerminalContextNode {
|
||||
return $createComposerTerminalContextNode(serializedNode.context);
|
||||
}
|
||||
|
||||
constructor(context: TerminalContextDraft, key?: NodeKey) {
|
||||
super(key);
|
||||
this.__context = context;
|
||||
}
|
||||
|
||||
override exportJSON(): SerializedComposerTerminalContextNode {
|
||||
return {
|
||||
...super.exportJSON(),
|
||||
context: this.__context,
|
||||
type: "composer-terminal-context",
|
||||
version: 1,
|
||||
};
|
||||
}
|
||||
|
||||
override createDOM(): HTMLElement {
|
||||
const dom = document.createElement("span");
|
||||
dom.className = "inline-flex align-middle leading-none";
|
||||
return dom;
|
||||
}
|
||||
|
||||
override updateDOM(): false {
|
||||
return false;
|
||||
}
|
||||
|
||||
override getTextContent(): string {
|
||||
return INLINE_TERMINAL_CONTEXT_PLACEHOLDER;
|
||||
}
|
||||
|
||||
override isInline(): true {
|
||||
return true;
|
||||
}
|
||||
|
||||
override decorate(): ReactElement {
|
||||
return <ComposerTerminalContextDecorator context={this.__context} />;
|
||||
}
|
||||
}
|
||||
|
||||
function $createComposerTerminalContextNode(
|
||||
context: TerminalContextDraft,
|
||||
): ComposerTerminalContextNode {
|
||||
return $applyNodeReplacement(new ComposerTerminalContextNode(context));
|
||||
}
|
||||
|
||||
type ComposerInlineTokenNode = ComposerMentionNode | ComposerTerminalContextNode;
|
||||
|
||||
function isComposerInlineTokenNode(candidate: unknown): candidate is ComposerInlineTokenNode {
|
||||
return (
|
||||
candidate instanceof ComposerMentionNode || candidate instanceof ComposerTerminalContextNode
|
||||
);
|
||||
}
|
||||
|
||||
function resolvedThemeFromDocument(): "light" | "dark" {
|
||||
@@ -160,25 +255,91 @@ function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||
const icon = document.createElement("img");
|
||||
icon.alt = "";
|
||||
icon.ariaHidden = "true";
|
||||
icon.className = "size-3.5 shrink-0 opacity-85";
|
||||
icon.className = COMPOSER_INLINE_CHIP_ICON_CLASS_NAME;
|
||||
icon.loading = "lazy";
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferMentionPathKind(pathValue), theme);
|
||||
icon.src = getVscodeIconUrlForEntry(pathValue, inferEntryKindFromPath(pathValue), theme);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "truncate select-none leading-tight";
|
||||
label.className = COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME;
|
||||
label.textContent = basenameOfPath(pathValue);
|
||||
|
||||
container.append(icon, label);
|
||||
}
|
||||
|
||||
function clampCursor(value: string, cursor: number): number {
|
||||
function terminalContextSignature(contexts: ReadonlyArray<TerminalContextDraft>): string {
|
||||
return contexts
|
||||
.map((context) =>
|
||||
[
|
||||
context.id,
|
||||
context.threadId,
|
||||
context.terminalId,
|
||||
context.terminalLabel,
|
||||
context.lineStart,
|
||||
context.lineEnd,
|
||||
context.createdAt,
|
||||
context.text,
|
||||
].join("\u001f"),
|
||||
)
|
||||
.join("\u001e");
|
||||
}
|
||||
|
||||
function clampExpandedCursor(value: string, cursor: number): number {
|
||||
if (!Number.isFinite(cursor)) return value.length;
|
||||
return Math.max(0, Math.min(value.length, Math.floor(cursor)));
|
||||
}
|
||||
|
||||
function getComposerInlineTokenTextLength(_node: ComposerInlineTokenNode): 1 {
|
||||
return 1;
|
||||
}
|
||||
|
||||
function getComposerInlineTokenExpandedTextLength(node: ComposerInlineTokenNode): number {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
|
||||
function getAbsoluteOffsetForInlineTokenPoint(
|
||||
node: ComposerInlineTokenNode,
|
||||
absoluteOffset: number,
|
||||
pointOffset: number,
|
||||
): number {
|
||||
return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenTextLength(node) : 0);
|
||||
}
|
||||
|
||||
function getExpandedAbsoluteOffsetForInlineTokenPoint(
|
||||
node: ComposerInlineTokenNode,
|
||||
absoluteOffset: number,
|
||||
pointOffset: number,
|
||||
): number {
|
||||
return absoluteOffset + (pointOffset > 0 ? getComposerInlineTokenExpandedTextLength(node) : 0);
|
||||
}
|
||||
|
||||
function findSelectionPointForInlineToken(
|
||||
node: ComposerInlineTokenNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "element" } | null {
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === getComposerInlineTokenTextLength(node)) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= getComposerInlineTokenTextLength(node);
|
||||
return null;
|
||||
}
|
||||
|
||||
function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return 1;
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenTextLength(node);
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
@@ -192,6 +353,24 @@ function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
function getComposerNodeExpandedTextLength(node: LexicalNode): number {
|
||||
if (isComposerInlineTokenNode(node)) {
|
||||
return getComposerInlineTokenExpandedTextLength(node);
|
||||
}
|
||||
if ($isTextNode(node)) {
|
||||
return node.getTextContentSize();
|
||||
}
|
||||
if ($isLineBreakNode(node)) {
|
||||
return 1;
|
||||
}
|
||||
if ($isElementNode(node)) {
|
||||
return node
|
||||
.getChildren()
|
||||
.reduce((total, child) => total + getComposerNodeExpandedTextLength(child), 0);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
|
||||
let offset = 0;
|
||||
let current: LexicalNode | null = node;
|
||||
@@ -213,10 +392,13 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return offset + (pointOffset > 0 ? 1 : 0);
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return getAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
@@ -236,30 +418,62 @@ function getAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): numb
|
||||
return offset;
|
||||
}
|
||||
|
||||
function getExpandedAbsoluteOffsetForPoint(node: LexicalNode, pointOffset: number): number {
|
||||
let offset = 0;
|
||||
let current: LexicalNode | null = node;
|
||||
|
||||
while (current) {
|
||||
const nextParent = current.getParent() as LexicalNode | null;
|
||||
if (!nextParent || !$isElementNode(nextParent)) {
|
||||
break;
|
||||
}
|
||||
const siblings = nextParent.getChildren();
|
||||
const index = current.getIndexWithinParent();
|
||||
for (let i = 0; i < index; i += 1) {
|
||||
const sibling = siblings[i];
|
||||
if (!sibling) continue;
|
||||
offset += getComposerNodeExpandedTextLength(sibling);
|
||||
}
|
||||
current = nextParent;
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return getExpandedAbsoluteOffsetForInlineTokenPoint(node, offset, pointOffset);
|
||||
}
|
||||
|
||||
if ($isLineBreakNode(node)) {
|
||||
return offset + Math.min(pointOffset, 1);
|
||||
}
|
||||
|
||||
if ($isElementNode(node)) {
|
||||
const children = node.getChildren();
|
||||
const clampedOffset = Math.max(0, Math.min(pointOffset, children.length));
|
||||
for (let i = 0; i < clampedOffset; i += 1) {
|
||||
const child = children[i];
|
||||
if (!child) continue;
|
||||
offset += getComposerNodeExpandedTextLength(child);
|
||||
}
|
||||
return offset;
|
||||
}
|
||||
|
||||
return offset;
|
||||
}
|
||||
|
||||
function findSelectionPointAtOffset(
|
||||
node: LexicalNode,
|
||||
remainingRef: { value: number },
|
||||
): { key: string; offset: number; type: "text" | "element" } | null {
|
||||
if (node instanceof ComposerMentionNode) {
|
||||
const parent = node.getParent();
|
||||
if (!parent || !$isElementNode(parent)) return null;
|
||||
const index = node.getIndexWithinParent();
|
||||
if (remainingRef.value === 0) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
if (remainingRef.value === 1) {
|
||||
return {
|
||||
key: parent.getKey(),
|
||||
offset: index + 1,
|
||||
type: "element",
|
||||
};
|
||||
}
|
||||
remainingRef.value -= 1;
|
||||
return null;
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return findSelectionPointForInlineToken(node, remainingRef);
|
||||
}
|
||||
|
||||
if ($isTextNode(node)) {
|
||||
@@ -350,6 +564,17 @@ function $readSelectionOffsetFromEditorState(fallback: number): number {
|
||||
return Math.max(0, Math.min(offset, composerLength));
|
||||
}
|
||||
|
||||
function $readExpandedSelectionOffsetFromEditorState(fallback: number): number {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) {
|
||||
return fallback;
|
||||
}
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const offset = getExpandedAbsoluteOffsetForPoint(anchorNode, selection.anchor.offset);
|
||||
const expandedLength = $getRoot().getTextContent().length;
|
||||
return Math.max(0, Math.min(offset, expandedLength));
|
||||
}
|
||||
|
||||
function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
const lines = text.split("\n");
|
||||
for (let index = 0; index < lines.length; index += 1) {
|
||||
@@ -363,36 +588,68 @@ function $appendTextWithLineBreaks(parent: ElementNode, text: string): void {
|
||||
}
|
||||
}
|
||||
|
||||
function $setComposerEditorPrompt(prompt: string): void {
|
||||
function $setComposerEditorPrompt(
|
||||
prompt: string,
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>,
|
||||
): void {
|
||||
const root = $getRoot();
|
||||
root.clear();
|
||||
const paragraph = $createParagraphNode();
|
||||
root.append(paragraph);
|
||||
|
||||
const segments = splitPromptIntoComposerSegments(prompt);
|
||||
const segments = splitPromptIntoComposerSegments(prompt, terminalContexts);
|
||||
for (const segment of segments) {
|
||||
if (segment.type === "mention") {
|
||||
paragraph.append($createComposerMentionNode(segment.path));
|
||||
continue;
|
||||
}
|
||||
if (segment.type === "terminal-context") {
|
||||
if (segment.context) {
|
||||
paragraph.append($createComposerTerminalContextNode(segment.context));
|
||||
}
|
||||
continue;
|
||||
}
|
||||
$appendTextWithLineBreaks(paragraph, segment.text);
|
||||
}
|
||||
}
|
||||
|
||||
function collectTerminalContextIds(node: LexicalNode): string[] {
|
||||
if (node instanceof ComposerTerminalContextNode) {
|
||||
return [node.__context.id];
|
||||
}
|
||||
if ($isElementNode(node)) {
|
||||
return node.getChildren().flatMap((child) => collectTerminalContextIds(child));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export interface ComposerPromptEditorHandle {
|
||||
focus: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
focusAtEnd: () => void;
|
||||
readSnapshot: () => { value: string; cursor: number };
|
||||
readSnapshot: () => {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
};
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorProps {
|
||||
value: string;
|
||||
cursor: number;
|
||||
terminalContexts: ReadonlyArray<TerminalContextDraft>;
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
|
||||
onRemoveTerminalContext: (contextId: string) => void;
|
||||
onChange: (
|
||||
nextValue: string,
|
||||
nextCursor: number,
|
||||
expandedCursor: number,
|
||||
cursorAdjacentToMention: boolean,
|
||||
terminalContextIds: string[],
|
||||
) => void;
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
@@ -460,7 +717,7 @@ function ComposerCommandKeyPlugin(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionArrowPlugin() {
|
||||
function ComposerInlineTokenArrowPlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -474,7 +731,7 @@ function ComposerMentionArrowPlugin() {
|
||||
const currentOffset = $readSelectionOffsetFromEditorState(0);
|
||||
if (currentOffset <= 0) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "left")) {
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "left")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset - 1;
|
||||
@@ -501,7 +758,7 @@ function ComposerMentionArrowPlugin() {
|
||||
const composerLength = $getComposerRootLength();
|
||||
if (currentOffset >= composerLength) return;
|
||||
const promptValue = $getRoot().getTextContent();
|
||||
if (!isCollapsedCursorAdjacentToMention(promptValue, currentOffset, "right")) {
|
||||
if (!isCollapsedCursorAdjacentToInlineToken(promptValue, currentOffset, "right")) {
|
||||
return;
|
||||
}
|
||||
nextOffset = currentOffset + 1;
|
||||
@@ -526,7 +783,7 @@ function ComposerMentionArrowPlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionSelectionNormalizePlugin() {
|
||||
function ComposerInlineTokenSelectionNormalizePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
|
||||
useEffect(() => {
|
||||
@@ -536,7 +793,7 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
const selection = $getSelection();
|
||||
if (!$isRangeSelection(selection) || !selection.isCollapsed()) return;
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
if (!(anchorNode instanceof ComposerMentionNode)) return;
|
||||
if (!isComposerInlineTokenNode(anchorNode)) return;
|
||||
if (selection.anchor.offset === 0) return;
|
||||
const beforeOffset = getAbsoluteOffsetForPoint(anchorNode, 0);
|
||||
afterOffset = beforeOffset + 1;
|
||||
@@ -554,8 +811,9 @@ function ComposerMentionSelectionNormalizePlugin() {
|
||||
return null;
|
||||
}
|
||||
|
||||
function ComposerMentionBackspacePlugin() {
|
||||
function ComposerInlineTokenBackspacePlugin() {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const { onRemoveTerminalContext } = useContext(ComposerTerminalContextActionsContext);
|
||||
|
||||
useEffect(() => {
|
||||
return editor.registerCommand(
|
||||
@@ -567,18 +825,23 @@ function ComposerMentionBackspacePlugin() {
|
||||
}
|
||||
|
||||
const anchorNode = selection.anchor.getNode();
|
||||
const removeMentionNode = (candidate: unknown): boolean => {
|
||||
if (!(candidate instanceof ComposerMentionNode)) {
|
||||
const selectionOffset = $readSelectionOffsetFromEditorState(0);
|
||||
const removeInlineTokenNode = (candidate: unknown): boolean => {
|
||||
if (!isComposerInlineTokenNode(candidate)) {
|
||||
return false;
|
||||
}
|
||||
const mentionStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
const tokenStart = getAbsoluteOffsetForPoint(candidate, 0);
|
||||
candidate.remove();
|
||||
$setSelectionAtComposerOffset(mentionStart);
|
||||
if (candidate instanceof ComposerTerminalContextNode) {
|
||||
onRemoveTerminalContext(candidate.__context.id);
|
||||
$setSelectionAtComposerOffset(selectionOffset);
|
||||
} else {
|
||||
$setSelectionAtComposerOffset(tokenStart);
|
||||
}
|
||||
event?.preventDefault();
|
||||
return true;
|
||||
};
|
||||
|
||||
if (removeMentionNode(anchorNode)) {
|
||||
if (removeInlineTokenNode(anchorNode)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -586,13 +849,13 @@ function ComposerMentionBackspacePlugin() {
|
||||
if (selection.anchor.offset > 0) {
|
||||
return false;
|
||||
}
|
||||
if (removeMentionNode(anchorNode.getPreviousSibling())) {
|
||||
if (removeInlineTokenNode(anchorNode.getPreviousSibling())) {
|
||||
return true;
|
||||
}
|
||||
const parent = anchorNode.getParent();
|
||||
if ($isElementNode(parent)) {
|
||||
const index = anchorNode.getIndexWithinParent();
|
||||
if (index > 0 && removeMentionNode(parent.getChildAtIndex(index - 1))) {
|
||||
if (index > 0 && removeInlineTokenNode(parent.getChildAtIndex(index - 1))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -601,7 +864,7 @@ function ComposerMentionBackspacePlugin() {
|
||||
|
||||
if ($isElementNode(anchorNode)) {
|
||||
const childIndex = selection.anchor.offset - 1;
|
||||
if (childIndex >= 0 && removeMentionNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
if (childIndex >= 0 && removeInlineTokenNode(anchorNode.getChildAtIndex(childIndex))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -610,7 +873,7 @@ function ComposerMentionBackspacePlugin() {
|
||||
},
|
||||
COMMAND_PRIORITY_HIGH,
|
||||
);
|
||||
}, [editor]);
|
||||
}, [editor, onRemoveTerminalContext]);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -618,9 +881,11 @@ function ComposerMentionBackspacePlugin() {
|
||||
function ComposerPromptEditorInner({
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
@@ -628,7 +893,20 @@ function ComposerPromptEditorInner({
|
||||
}: ComposerPromptEditorInnerProps) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const onChangeRef = useRef(onChange);
|
||||
const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
|
||||
const initialCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const terminalContextsSignature = terminalContextSignature(terminalContexts);
|
||||
const terminalContextsSignatureRef = useRef(terminalContextsSignature);
|
||||
const snapshotRef = useRef({
|
||||
value,
|
||||
cursor: initialCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, initialCursor),
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
});
|
||||
const isApplyingControlledUpdateRef = useRef(false);
|
||||
const terminalContextActions = useMemo(
|
||||
() => ({ onRemoveTerminalContext }),
|
||||
[onRemoveTerminalContext],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
@@ -639,35 +917,51 @@ function ComposerPromptEditorInner({
|
||||
}, [disabled, editor]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const normalizedCursor = clampCursor(value, cursor);
|
||||
const normalizedCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === value && previousSnapshot.cursor === normalizedCursor) {
|
||||
const contextsChanged = terminalContextsSignatureRef.current !== terminalContextsSignature;
|
||||
if (
|
||||
previousSnapshot.value === value &&
|
||||
previousSnapshot.cursor === normalizedCursor &&
|
||||
!contextsChanged
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousSnapshot.value !== value) {
|
||||
editor.update(() => {
|
||||
$setComposerEditorPrompt(value);
|
||||
});
|
||||
}
|
||||
|
||||
snapshotRef.current = { value, cursor: normalizedCursor };
|
||||
snapshotRef.current = {
|
||||
value,
|
||||
cursor: normalizedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, normalizedCursor),
|
||||
terminalContextIds: terminalContexts.map((context) => context.id),
|
||||
};
|
||||
terminalContextsSignatureRef.current = terminalContextsSignature;
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
if (!rootElement || document.activeElement !== rootElement) {
|
||||
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
|
||||
if (previousSnapshot.value === value && !contextsChanged && !isFocused) {
|
||||
return;
|
||||
}
|
||||
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
const shouldRewriteEditorState = previousSnapshot.value !== value || contextsChanged;
|
||||
if (shouldRewriteEditorState) {
|
||||
$setComposerEditorPrompt(value, terminalContexts);
|
||||
}
|
||||
if (shouldRewriteEditorState || isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
}
|
||||
});
|
||||
}, [cursor, editor, value]);
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
}, [cursor, editor, terminalContexts, terminalContextsSignature, value]);
|
||||
|
||||
const focusAt = useCallback(
|
||||
(nextCursor: number) => {
|
||||
const rootElement = editor.getRootElement();
|
||||
if (!rootElement) return;
|
||||
const boundedCursor = clampCursor(snapshotRef.current.value, nextCursor);
|
||||
const boundedCursor = clampCollapsedComposerCursor(snapshotRef.current.value, nextCursor);
|
||||
rootElement.focus();
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(boundedCursor);
|
||||
@@ -675,24 +969,48 @@ function ComposerPromptEditorInner({
|
||||
snapshotRef.current = {
|
||||
value: snapshotRef.current.value,
|
||||
cursor: boundedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
|
||||
terminalContextIds: snapshotRef.current.terminalContextIds,
|
||||
};
|
||||
onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
|
||||
onChangeRef.current(
|
||||
snapshotRef.current.value,
|
||||
boundedCursor,
|
||||
snapshotRef.current.expandedCursor,
|
||||
false,
|
||||
snapshotRef.current.terminalContextIds,
|
||||
);
|
||||
},
|
||||
[editor],
|
||||
);
|
||||
|
||||
const readSnapshot = useCallback((): { value: string; cursor: number } => {
|
||||
const readSnapshot = useCallback((): {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
terminalContextIds: string[];
|
||||
} => {
|
||||
let snapshot = snapshotRef.current;
|
||||
editor.getEditorState().read(() => {
|
||||
const nextValue = $getRoot().getTextContent();
|
||||
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCursor(
|
||||
const fallbackCursor = clampCollapsedComposerCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCollapsedComposerCursor(
|
||||
nextValue,
|
||||
$readSelectionOffsetFromEditorState(fallbackCursor),
|
||||
);
|
||||
const fallbackExpandedCursor = clampExpandedCursor(
|
||||
nextValue,
|
||||
snapshotRef.current.expandedCursor,
|
||||
);
|
||||
const nextExpandedCursor = clampExpandedCursor(
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
snapshot = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
});
|
||||
snapshotRef.current = snapshot;
|
||||
@@ -705,11 +1023,14 @@ function ComposerPromptEditorInner({
|
||||
focus: () => {
|
||||
focusAt(snapshotRef.current.cursor);
|
||||
},
|
||||
focusAt: (nextCursor: number) => {
|
||||
focusAt(nextCursor);
|
||||
},
|
||||
focusAt,
|
||||
focusAtEnd: () => {
|
||||
focusAt(snapshotRef.current.value.length);
|
||||
focusAt(
|
||||
collapseExpandedComposerCursor(
|
||||
snapshotRef.current.value,
|
||||
snapshotRef.current.value.length,
|
||||
),
|
||||
);
|
||||
},
|
||||
readSnapshot,
|
||||
}),
|
||||
@@ -719,55 +1040,85 @@ function ComposerPromptEditorInner({
|
||||
const handleEditorChange = useCallback((editorState: EditorState) => {
|
||||
editorState.read(() => {
|
||||
const nextValue = $getRoot().getTextContent();
|
||||
const fallbackCursor = clampCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCursor(
|
||||
const fallbackCursor = clampCollapsedComposerCursor(nextValue, snapshotRef.current.cursor);
|
||||
const nextCursor = clampCollapsedComposerCursor(
|
||||
nextValue,
|
||||
$readSelectionOffsetFromEditorState(fallbackCursor),
|
||||
);
|
||||
const fallbackExpandedCursor = clampExpandedCursor(
|
||||
nextValue,
|
||||
snapshotRef.current.expandedCursor,
|
||||
);
|
||||
const nextExpandedCursor = clampExpandedCursor(
|
||||
nextValue,
|
||||
$readExpandedSelectionOffsetFromEditorState(fallbackExpandedCursor),
|
||||
);
|
||||
const terminalContextIds = collectTerminalContextIds($getRoot());
|
||||
const previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
|
||||
if (
|
||||
previousSnapshot.value === nextValue &&
|
||||
previousSnapshot.cursor === nextCursor &&
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor &&
|
||||
previousSnapshot.terminalContextIds.length === terminalContextIds.length &&
|
||||
previousSnapshot.terminalContextIds.every((id, index) => id === terminalContextIds[index])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (isApplyingControlledUpdateRef.current) {
|
||||
return;
|
||||
}
|
||||
snapshotRef.current = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
terminalContextIds,
|
||||
};
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToInlineToken(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(
|
||||
nextValue,
|
||||
nextCursor,
|
||||
nextExpandedCursor,
|
||||
cursorAdjacentToMention,
|
||||
terminalContextIds,
|
||||
);
|
||||
});
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerMentionArrowPlugin />
|
||||
<ComposerMentionSelectionNormalizePlugin />
|
||||
<ComposerMentionBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
<ComposerTerminalContextActionsContext.Provider value={terminalContextActions}>
|
||||
<div className="relative">
|
||||
<PlainTextPlugin
|
||||
contentEditable={
|
||||
<ContentEditable
|
||||
className={cn(
|
||||
"block max-h-[200px] min-h-17.5 w-full overflow-y-auto whitespace-pre-wrap break-words bg-transparent text-[14px] leading-relaxed text-foreground focus:outline-none",
|
||||
className,
|
||||
)}
|
||||
data-testid="composer-editor"
|
||||
aria-placeholder={placeholder}
|
||||
placeholder={<span />}
|
||||
onPaste={onPaste}
|
||||
/>
|
||||
}
|
||||
placeholder={
|
||||
terminalContexts.length > 0 ? null : (
|
||||
<div className="pointer-events-none absolute inset-0 text-[14px] leading-relaxed text-muted-foreground/35">
|
||||
{placeholder}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
ErrorBoundary={LexicalErrorBoundary}
|
||||
/>
|
||||
<OnChangePlugin onChange={handleEditorChange} />
|
||||
<ComposerCommandKeyPlugin {...(onCommandKeyDown ? { onCommandKeyDown } : {})} />
|
||||
<ComposerInlineTokenArrowPlugin />
|
||||
<ComposerInlineTokenSelectionNormalizePlugin />
|
||||
<ComposerInlineTokenBackspacePlugin />
|
||||
<HistoryPlugin />
|
||||
</div>
|
||||
</ComposerTerminalContextActionsContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -775,17 +1126,29 @@ export const ComposerPromptEditor = forwardRef<
|
||||
ComposerPromptEditorHandle,
|
||||
ComposerPromptEditorProps
|
||||
>(function ComposerPromptEditor(
|
||||
{ value, cursor, disabled, placeholder, className, onChange, onCommandKeyDown, onPaste },
|
||||
{
|
||||
value,
|
||||
cursor,
|
||||
terminalContexts,
|
||||
disabled,
|
||||
placeholder,
|
||||
className,
|
||||
onRemoveTerminalContext,
|
||||
onChange,
|
||||
onCommandKeyDown,
|
||||
onPaste,
|
||||
},
|
||||
ref,
|
||||
) {
|
||||
const initialValueRef = useRef(value);
|
||||
const initialTerminalContextsRef = useRef(terminalContexts);
|
||||
const initialConfig = useMemo<InitialConfigType>(
|
||||
() => ({
|
||||
namespace: "t3tools-composer-editor",
|
||||
editable: true,
|
||||
nodes: [ComposerMentionNode],
|
||||
nodes: [ComposerMentionNode, ComposerTerminalContextNode],
|
||||
editorState: () => {
|
||||
$setComposerEditorPrompt(initialValueRef.current);
|
||||
$setComposerEditorPrompt(initialValueRef.current, initialTerminalContextsRef.current);
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
@@ -799,8 +1162,10 @@ export const ComposerPromptEditor = forwardRef<
|
||||
<ComposerPromptEditorInner
|
||||
value={value}
|
||||
cursor={cursor}
|
||||
terminalContexts={terminalContexts}
|
||||
disabled={disabled}
|
||||
placeholder={placeholder}
|
||||
onRemoveTerminalContext={onRemoveTerminalContext}
|
||||
onChange={onChange}
|
||||
onPaste={onPaste}
|
||||
editorRef={ref}
|
||||
|
||||
@@ -12,18 +12,21 @@ import {
|
||||
useRef,
|
||||
useState,
|
||||
} from "react";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { gitBranchesQueryOptions } from "~/lib/gitReactQuery";
|
||||
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { preferredTerminalEditor, resolvePathLinkTarget } from "../terminal-links";
|
||||
import { resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { isElectron } from "../env";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
|
||||
type DiffRenderMode = "stacked" | "split";
|
||||
@@ -148,15 +151,8 @@ function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
|
||||
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
|
||||
}
|
||||
|
||||
function formatTurnChipTimestamp(isoDate: string): string {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
}).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
interface DiffPanelProps {
|
||||
mode?: "inline" | "sheet" | "sidebar";
|
||||
mode?: DiffPanelMode;
|
||||
}
|
||||
|
||||
export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
@@ -164,6 +160,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { settings } = useAppSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
@@ -311,7 +308,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const targetPath = activeCwd ? resolvePathLinkTarget(filePath, activeCwd) : filePath;
|
||||
void api.shell.openInEditor(targetPath, preferredTerminalEditor()).catch((error) => {
|
||||
void openInPreferredEditor(api, targetPath).catch((error) => {
|
||||
console.warn("Failed to open diff file in editor.", error);
|
||||
});
|
||||
},
|
||||
@@ -401,7 +398,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
|
||||
}, [selectedTurn?.turnId, selectedTurnId]);
|
||||
|
||||
const shouldUseDragRegion = isElectron && mode !== "sheet";
|
||||
const headerRow = (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
|
||||
@@ -486,7 +482,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
"?"}
|
||||
</span>
|
||||
<span className="text-[9px] leading-tight opacity-70">
|
||||
{formatTurnChipTimestamp(summary.completedAt)}
|
||||
{formatShortTimestamp(summary.completedAt, settings.timestampFormat)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -515,28 +511,9 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</ToggleGroup>
|
||||
</>
|
||||
);
|
||||
const headerRowClassName = cn(
|
||||
"flex items-center justify-between gap-2 px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-background",
|
||||
mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
)}
|
||||
>
|
||||
{shouldUseDragRegion ? (
|
||||
<div className={headerRowClassName}>{headerRow}</div>
|
||||
) : (
|
||||
<div className="border-b border-border">
|
||||
<div className={headerRowClassName}>{headerRow}</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<DiffPanelShell mode={mode} header={headerRow}>
|
||||
{!activeThread ? (
|
||||
<div className="flex flex-1 items-center justify-center px-5 text-center text-xs text-muted-foreground/70">
|
||||
Select a thread to inspect turn diffs.
|
||||
@@ -561,15 +538,17 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
)}
|
||||
{!renderablePatch ? (
|
||||
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
|
||||
<p>
|
||||
{isLoadingCheckpointDiff
|
||||
? "Loading checkpoint diff..."
|
||||
: hasNoNetChanges
|
||||
isLoadingCheckpointDiff ? (
|
||||
<DiffPanelLoadingState label="Loading checkpoint diff..." />
|
||||
) : (
|
||||
<div className="flex h-full items-center justify-center px-3 py-2 text-xs text-muted-foreground/70">
|
||||
<p>
|
||||
{hasNoNetChanges
|
||||
? "No net changes in this selection."
|
||||
: "No patch available for this selection."}
|
||||
</p>
|
||||
</div>
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
) : renderablePatch.kind === "files" ? (
|
||||
<Virtualizer
|
||||
className="diff-render-surface h-full min-h-0 overflow-auto px-2 pb-2"
|
||||
@@ -625,6 +604,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</DiffPanelShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { isElectron } from "~/env";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
import { Skeleton } from "./ui/skeleton";
|
||||
|
||||
export type DiffPanelMode = "inline" | "sheet" | "sidebar";
|
||||
|
||||
function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) {
|
||||
const shouldUseDragRegion = isElectron && mode !== "sheet";
|
||||
return cn(
|
||||
"flex items-center justify-between gap-2 px-4",
|
||||
shouldUseDragRegion ? "drag-region h-[52px] border-b border-border" : "h-12",
|
||||
);
|
||||
}
|
||||
|
||||
export function DiffPanelShell(props: {
|
||||
mode: DiffPanelMode;
|
||||
header: ReactNode;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const shouldUseDragRegion = isElectron && props.mode !== "sheet";
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"flex h-full min-w-0 flex-col bg-background",
|
||||
props.mode === "inline"
|
||||
? "w-[42vw] min-w-[360px] max-w-[560px] shrink-0 border-l border-border"
|
||||
: "w-full",
|
||||
)}
|
||||
>
|
||||
{shouldUseDragRegion ? (
|
||||
<div className={getDiffPanelHeaderRowClassName(props.mode)}>{props.header}</div>
|
||||
) : (
|
||||
<div className="border-b border-border">
|
||||
<div className={getDiffPanelHeaderRowClassName(props.mode)}>{props.header}</div>
|
||||
</div>
|
||||
)}
|
||||
{props.children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function DiffPanelHeaderSkeleton() {
|
||||
return (
|
||||
<>
|
||||
<div className="relative min-w-0 flex-1">
|
||||
<Skeleton className="absolute left-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50" />
|
||||
<Skeleton className="absolute right-0 top-1/2 size-6 -translate-y-1/2 rounded-md border border-border/50" />
|
||||
<div className="flex gap-1 overflow-hidden px-8 py-0.5">
|
||||
<Skeleton className="h-6 w-16 shrink-0 rounded-md" />
|
||||
<Skeleton className="h-6 w-24 shrink-0 rounded-md" />
|
||||
<Skeleton className="h-6 w-24 shrink-0 rounded-md max-sm:hidden" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 gap-1">
|
||||
<Skeleton className="size-7 rounded-md" />
|
||||
<Skeleton className="size-7 rounded-md" />
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function DiffPanelLoadingState(props: { label: string }) {
|
||||
return (
|
||||
<div className="flex min-h-0 flex-1 flex-col p-2">
|
||||
<div
|
||||
className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-md border border-border/60 bg-card/25"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-label={props.label}
|
||||
>
|
||||
<div className="flex items-center gap-2 border-b border-border/50 px-3 py-2">
|
||||
<Skeleton className="h-4 w-32 rounded-full" />
|
||||
<Skeleton className="ml-auto h-4 w-20 rounded-full" />
|
||||
</div>
|
||||
<div className="flex min-h-0 flex-1 flex-col gap-4 px-3 py-4">
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-3 w-full rounded-full" />
|
||||
<Skeleton className="h-3 w-full rounded-full" />
|
||||
<Skeleton className="h-3 w-10/12 rounded-full" />
|
||||
<Skeleton className="h-3 w-11/12 rounded-full" />
|
||||
<Skeleton className="h-3 w-9/12 rounded-full" />
|
||||
</div>
|
||||
<span className="sr-only">{props.label}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -15,7 +15,9 @@ import {
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
import { useAppSettings } from "~/appSettings";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Checkbox } from "~/components/ui/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
@@ -31,6 +33,7 @@ import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import { toastManager } from "~/components/ui/toast";
|
||||
import { openInPreferredEditor } from "~/editorPreferences";
|
||||
import {
|
||||
gitBranchesQueryOptions,
|
||||
gitInitMutationOptions,
|
||||
@@ -40,7 +43,7 @@ import {
|
||||
gitStatusQueryOptions,
|
||||
invalidateGitQueries,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { preferredTerminalEditor, resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
interface GitActionsControlProps {
|
||||
@@ -55,6 +58,7 @@ interface PendingDefaultBranchAction {
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress: boolean;
|
||||
onConfirmed?: () => void;
|
||||
filePaths?: string[];
|
||||
}
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
@@ -151,6 +155,7 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
|
||||
const { settings } = useAppSettings();
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||
[activeThreadId],
|
||||
@@ -158,6 +163,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const queryClient = useQueryClient();
|
||||
const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false);
|
||||
const [dialogCommitMessage, setDialogCommitMessage] = useState("");
|
||||
const [excludedFiles, setExcludedFiles] = useState<ReadonlySet<string>>(new Set());
|
||||
const [isEditingFiles, setIsEditingFiles] = useState(false);
|
||||
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||
useState<PendingDefaultBranchAction | null>(null);
|
||||
|
||||
@@ -178,10 +185,19 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
|
||||
const gitStatusForActions = isGitStatusOutOfSync ? null : gitStatus;
|
||||
|
||||
const allFiles = gitStatusForActions?.workingTree.files ?? [];
|
||||
const selectedFiles = allFiles.filter((f) => !excludedFiles.has(f.path));
|
||||
const allSelected = excludedFiles.size === 0;
|
||||
const noneSelected = selectedFiles.length === 0;
|
||||
|
||||
const initMutation = useMutation(gitInitMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
const runImmediateGitActionMutation = useMutation(
|
||||
gitRunStackedActionMutationOptions({ cwd: gitCwd, queryClient }),
|
||||
gitRunStackedActionMutationOptions({
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
model: settings.textGenerationModel ?? null,
|
||||
}),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
|
||||
@@ -256,6 +272,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
featureBranch = false,
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
filePaths,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
@@ -266,6 +283,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
featureBranch?: boolean;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
filePaths?: string[];
|
||||
}) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
@@ -288,6 +306,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -337,6 +356,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -438,7 +458,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
|
||||
const continuePendingDefaultBranchAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
|
||||
pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
void runGitActionWithToast({
|
||||
@@ -446,6 +466,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, runGitActionWithToast]);
|
||||
@@ -456,6 +477,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
filePaths?: string[];
|
||||
}) => {
|
||||
void runGitActionWithToast({
|
||||
...actionParams,
|
||||
@@ -468,7 +490,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
|
||||
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed } =
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
|
||||
pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
checkoutNewBranchAndRunAction({
|
||||
@@ -476,6 +498,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
});
|
||||
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
|
||||
|
||||
@@ -485,12 +508,21 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
|
||||
checkoutNewBranchAndRunAction({
|
||||
action: "commit",
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
|
||||
});
|
||||
}, [isCommitDialogOpen, dialogCommitMessage, checkoutNewBranchAndRunAction]);
|
||||
}, [
|
||||
allSelected,
|
||||
isCommitDialogOpen,
|
||||
dialogCommitMessage,
|
||||
checkoutNewBranchAndRunAction,
|
||||
selectedFiles,
|
||||
]);
|
||||
|
||||
const runQuickAction = useCallback(() => {
|
||||
if (quickAction.kind === "open_pr") {
|
||||
@@ -547,6 +579,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
void runGitActionWithToast({ action: "commit_push_pr" });
|
||||
return;
|
||||
}
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
setIsCommitDialogOpen(true);
|
||||
},
|
||||
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
|
||||
@@ -557,14 +591,19 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const commitMessage = dialogCommitMessage.trim();
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
void runGitActionWithToast({
|
||||
action: "commit",
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
|
||||
});
|
||||
}, [
|
||||
allSelected,
|
||||
dialogCommitMessage,
|
||||
isCommitDialogOpen,
|
||||
runGitActionWithToast,
|
||||
selectedFiles,
|
||||
setDialogCommitMessage,
|
||||
setIsCommitDialogOpen,
|
||||
]);
|
||||
@@ -581,7 +620,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
return;
|
||||
}
|
||||
const target = resolvePathLinkTarget(filePath, gitCwd);
|
||||
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
|
||||
void openInPreferredEditor(api, target).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Unable to open file",
|
||||
@@ -729,6 +768,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
if (!open) {
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -751,37 +792,99 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
</span>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<p className="text-muted-foreground">Files</p>
|
||||
{!gitStatusForActions || gitStatusForActions.workingTree.files.length === 0 ? (
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
{isEditingFiles && allFiles.length > 0 && (
|
||||
<Checkbox
|
||||
checked={allSelected}
|
||||
indeterminate={!allSelected && !noneSelected}
|
||||
onCheckedChange={() => {
|
||||
setExcludedFiles(
|
||||
allSelected ? new Set(allFiles.map((f) => f.path)) : new Set(),
|
||||
);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<span className="text-muted-foreground">Files</span>
|
||||
{!allSelected && !isEditingFiles && (
|
||||
<span className="text-muted-foreground">
|
||||
({selectedFiles.length} of {allFiles.length})
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{allFiles.length > 0 && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
onClick={() => setIsEditingFiles((prev) => !prev)}
|
||||
>
|
||||
{isEditingFiles ? "Done" : "Edit"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
{!gitStatusForActions || allFiles.length === 0 ? (
|
||||
<p className="font-medium">none</p>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<ScrollArea className="h-44 rounded-md border border-input bg-background">
|
||||
<div className="space-y-1 p-1">
|
||||
{gitStatusForActions.workingTree.files.map((file) => (
|
||||
<button
|
||||
type="button"
|
||||
key={file.path}
|
||||
className="flex w-full items-center justify-between gap-3 rounded-md px-2 py-1 font-mono text-left transition-colors hover:bg-accent/50"
|
||||
onClick={() => openChangedFileInEditor(file.path)}
|
||||
>
|
||||
<span className="truncate">{file.path}</span>
|
||||
<span className="shrink-0">
|
||||
<span className="text-success">+{file.insertions}</span>
|
||||
<span className="text-muted-foreground"> / </span>
|
||||
<span className="text-destructive">-{file.deletions}</span>
|
||||
</span>
|
||||
</button>
|
||||
))}
|
||||
{allFiles.map((file) => {
|
||||
const isExcluded = excludedFiles.has(file.path);
|
||||
return (
|
||||
<div
|
||||
key={file.path}
|
||||
className="flex w-full items-center gap-2 rounded-md px-2 py-1 font-mono text-xs transition-colors hover:bg-accent/50"
|
||||
>
|
||||
{isEditingFiles && (
|
||||
<Checkbox
|
||||
checked={!excludedFiles.has(file.path)}
|
||||
onCheckedChange={() => {
|
||||
setExcludedFiles((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(file.path)) {
|
||||
next.delete(file.path);
|
||||
} else {
|
||||
next.add(file.path);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
className="flex flex-1 items-center justify-between gap-3 text-left truncate"
|
||||
onClick={() => openChangedFileInEditor(file.path)}
|
||||
>
|
||||
<span
|
||||
className={`truncate${isExcluded ? " text-muted-foreground" : ""}`}
|
||||
>
|
||||
{file.path}
|
||||
</span>
|
||||
<span className="shrink-0">
|
||||
{isExcluded ? (
|
||||
<span className="text-muted-foreground">Excluded</span>
|
||||
) : (
|
||||
<>
|
||||
<span className="text-success">+{file.insertions}</span>
|
||||
<span className="text-muted-foreground"> / </span>
|
||||
<span className="text-destructive">-{file.deletions}</span>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
<div className="flex justify-end font-mono">
|
||||
<span className="text-success">
|
||||
+{gitStatusForActions.workingTree.insertions}
|
||||
+{selectedFiles.reduce((sum, f) => sum + f.insertions, 0)}
|
||||
</span>
|
||||
<span className="text-muted-foreground"> / </span>
|
||||
<span className="text-destructive">
|
||||
-{gitStatusForActions.workingTree.deletions}
|
||||
-{selectedFiles.reduce((sum, f) => sum + f.deletions, 0)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -805,14 +908,21 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
onClick={() => {
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
}}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" onClick={runDialogActionOnNewBranch}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={noneSelected}
|
||||
onClick={runDialogActionOnNewBranch}
|
||||
>
|
||||
Commit on new branch
|
||||
</Button>
|
||||
<Button size="sm" onClick={runDialogAction}>
|
||||
<Button size="sm" disabled={noneSelected} onClick={runDialogAction}>
|
||||
Commit
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -146,7 +146,7 @@ export const OpenAI: Icon = (props) => (
|
||||
export const ClaudeAI: Icon = (props) => (
|
||||
<svg {...props} preserveAspectRatio="xMidYMid" viewBox="0 0 256 257">
|
||||
<path
|
||||
fill="#D97757"
|
||||
fill="currentColor"
|
||||
d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"
|
||||
/>
|
||||
</svg>
|
||||
@@ -287,6 +287,15 @@ export const Gemini: Icon = (props) => (
|
||||
</svg>
|
||||
);
|
||||
|
||||
const ANTIGRAVITY_ICON_DATA_URL =
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAYAAADDPmHLAAAAAXNSR0IArs4c6QAAAERlWElmTU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAgKADAAQAAAABAAAAgAAAAABIjgR3AAAjOElEQVR4Ae1dCYxkV3W9tfdW3T0z3bMvPcxge2zGy2BjY0MwxEAWEBACihSCEiMUSFCiRJEsRygIiIKySUlYAkmMQSxJQAKi4AQngDcMAe87nsF4xuPxrJ6ll+rqri3n3Pfv71e/f1XP4u7+Zdeb+XXvu+/9999/57z7lv+rOiVnF1ILnNYuvV3aAsW+JJIbbe6yXRpPWyh9XtFnCsZC+ePS42ysSCv7vEq2MbwQZbQp/rSTzrjhY0puVUacPc7mF7lQepj3TBqwVd44e9QWjbMCcbawYqeR7uftBH0hUOLSo7ZonPcdZ2tnb2qrhUBg5nZ5/DRfj57XLs0qFM1j9herjAMuavPjvs428eO+Hm2vdmltwWVBrUDx7S+U7lfcL9O3d7reCgzf/kLpflv5Zfr2lgAzUxwIUZvFo9I/v12an4+6BTvH4i8WGQeEb4vTzWaSbWF6VFo7md3i/jm+LRZkZogDwLeZfq4y7lpWZlNFX0SRKDh+3PRzlWwuK8Nvunm2uMZeyGbpvjwdnRXx8/nxqM44g+V3sc79nNfwuBXfZno76ae10tlClhbVGWfw0yXrbOFnXIObrZ1kmp++UJwX9PNbBcxmcZOt7JaeVNnU2F4lfbvpcZI2Hrx/01mMxam3Cv55fp6mc/2G9XU7wWxxkjbfbvGoZFmp3t6+wtDwim25XO6KdDp9JUyXpFKpMaT143gph6lGo7EX+D5Ur9d/XKlU7jl18sRT09OlGTQKQWQw8ONkNN3icZI2C1q2D6AlmIym+XHqCx4AOr127YZduXz+9wD2r1nBXblwC4AU36jMzn7m0KED94MYdZwRB34rGy+gAMdIplloGIhmMOmDTZufz3Rfpr08KQK/bv2mX0Rv/wLsL/UejiY4pzAFr/DbB5/b/70YIrQiBi9o5DDdl9Q1GIgWp6SNwZdRnfEm0C2+es26rXD3X0KPv4iFdMML0wLwCI9hWPitI4cPPo0SCW4U/GicF16QBATSwOUJpvsyqvvAm65y46axd2ez2c+yoG5YnBaoVqsfeHb/3q+hdJ8EPvi+zkq0JUEGGXyAeQIDbb7d4gY449T1gMfPbNq89eOZTOajsHXDIrYA2votg0PDxYmJU3fAK/BKhpNdNRpvmyeOACzACjGd0sAPgadNwd809knI63mlblj8FsDwesXg4NAmkOA7AQnsoj5uZjNpaRZXaQSwRF9S949YAqDnf6wLflObLkkEJNhZHBwaOHXqxO1neEEfY4kjgA+66bHgb9y05V2ZTPajZ1iBbvYXqAXoCQaKxafHx089EVOkAR2TNGdiJoLLYGCbbqBbHsbDY3T1mq39/cV7mLkblrcFpqYmrjh65PDTqAUngNHDJoE2OWRlzdYEPhMYokSweCix0M/09Q180WXvfi53CxALYuJhF2IV2FhFs1FnYDwkgBksky/NE4S9f926Da+H+7mQJ3XD8rcAsSAmqEmIEXRiaNj5eJquFbcMGvE+LJNJy4drpTP5fOEmL29XTUALEBNig6rMw8yzRWuaIrAMdpLJOBvzptesWbcLsru9yxZKVugPsFGcUDXD0iRra7rJpiHAbscSfWkeIJ0vFH7XMnZlslogwCbECrXzMTS9qdLM7AdmYrDMviT4Baz53+aydD+T1gLEhhihXkYCHz8f27Dq0YxMiJ4UxoeGVmwLz+wqiWyBAKMQsxg8We8wPc4DMJHBMoUkwUTjlS6p+5nUFggwmoddUF+zh9X3CWDAM9F0O4H50njYc0V4Zgcq3P2o46OGLZEaJHWN0xboHXhbTVUOMFK8kGD4MY9h2qTzncBoJovPk1gD7uTZnRb40IxAF3tExlaKbMexoS8txXRKGpW0jJdSsn+iIXvG6/JMqS4lsAFJTS3WKfccYDQPO9Tft6E13O35L4UygwU/c6ij8M2WoVMkX6ZaMSDyhleIvGmHyAUrUjKMOVJ2Ni2pckZSM+gskNXptJycEnnkeF1uOTQrdxyflcmqI0Kn3CvrGWAUYkaTdzALA20kQexbwUxk8E80vePW/688PyXXvzEluzaK5Kvo8eWUVMtpqYEEqfBISQpdfmUhLW8Yyco1xYLcdawin3m2JI+XKjqldk3SEZ/EyPDyJStvcQWfBvMATPBDXDxq8/MnSufdZdCx33x1Rt73K2lZ3ScAPYVx3kGOHTO4eOjcB1Md8XRa6rDVcGQyKbluVY9sL+Tlr56ZkNtOlbXlEnWT7StjQPu5ovgx3rA5ADPaSZbRj5vuF5hYneP3L12bk+vfnpMBbI7yBWv2d2AbAk/w08ioZIC0eAaZ+KpsA3JLb1o+snlI0s+IfK+zSGB4+TKKsc4DzANEwfRPpM5g0sUS+snJ3tVX5OXd7+iVNLZESrMOfPR1RwLchjp/EIBgZxR82OAB6DUaOEgMOAElwmg+LTduGJaT1RNy7+QMiJLQG2+ultWS0j+acyHGdmGwE6K6xa0QxhMbOOHbsiUr7/z1ouT681Kq56XcwCF5mZaCHmXIciovM6kcDidn03mppLNSSWWlClnFM5UqCFHDQbmukJM/Xjck6/IZfdie2AaYq5jh5ePKVD+uuu8B7CTLGI3PFZ9AjUu93t6U/Orbh2TFuh51++zCKdjTerDnu7Gfj8zoBbLqATAR0h7fgMRyEUcWJzVwkhsKnH7JQI/8zuig/PXBE7pnkMAmiFbJwDYco3G0ytwkMHqyH/dP9O2J0kmAS68akPMuK2IdD/et4IMAwT+6OhIACz/n+nFXdPMkQY6gA/A6QeeRwYGxRHXEuYmQAineivXknRNluWt8Ws9NVAM0V+a0MfMngVaEncy46SYtT6IkwR9elZVXv2mF1LJ5mZ1FdclvDOipOiiAQ8d93A5JwJsm+DkcJEAN4JIAuYAA9XQdZKirjSQQ6CREEUz5zZEheWhqRiYx3iS6UeKxi1YZg158YMZ5meOzJsN68dVDsnLzgExV09r76QGUAPQECrsjgXoAWIwAJEEVBCD4tQB46iRAo+kAERp1uXygD/sEffLfJyeT7AXisIvaFLgoAeIyxdmSgTpqwd4/uDInF75mlcxislcB4A0M5O4g3I4AKXiDNNIyONjrs3ARFdwZ3T8m+iBBzREgVQ+J0EjXQhI4L1CTApjzjlVDcvdEqZO8gI9XE55GABqbEvwzFkiLZF3aKL8Ysf2VwzK0gWM/Zu4NzNQBdkMPTPcgObNLKwE4B4D7BwlyJAF6fh5EqOHOqwC7FoBPT0Dw695Bb5DDikAaNXlF/4Dsgie4/dQEvEC7ZlvatohcrV3FmMZDN4Ii5zVF2xXSlHFZIuj9Pf1Z2X7ViHApNwv3X6uDADgaPAISsPenQAybB2SDeUAu8AIVEKFgHgBA16HX01UlgPMC9AQ8qlpmIZuRN64Ylh9OTIFwqESyQ1sMzQP4t9DqhFZ2/9wl1eto/LUvL8qKrcMyXc1JFSBXSQDwug5dSYA4pvUggPMCpAEHhixw483ncQBqDAHuqCkRHAEIOL2AAg8de8QoCxJe4NLikGztOSa7S9O6u7ikN77wxVphNc8eRwArfl5mS0iKTGM83nL5qNTzPTJbceBX61l4ARAARyMgAR2d8wIAHzYlAO4uhxvB86E58NH7awC6RtefIvjuUCJkKiiPcQ4vVRnExOHVg8NKgKS0R5t6tMSyFQH8E3y9zTWWNoljf3GkV1ZfOCLlWk4q6OnVOrxAQIAavQBJQA8AmYJMYS5AAnA+QA9AAjgSzPV+Hfc98EmCRprgo6kCEmD6CB9Sk1cNr5JvHjsqE7Va2wnU0rZM09V87Hw9zNSKAGGGxCrY9l19/grJrxqUchXbtyRBDRIkUA+AeA06vQAJICBAWsGn5CogpTByHoB+7SaAAJXjP72AAx5SQac3qbihBXEdXuAFNvUPy/a+otw3fiLJk8G2EHYsAdJYv63ZuQbuG+4f4FYANg/1AAC/Dt0Ogu/mAZj+2VwAm0M5EAH9G7DzIAkcAZzrB9AZEADAqwcg8KCMDiuYC9AL9KQysmt4RB6YONm2kZOc2JEEoPvvH+mToW2j6P05EAAPcvDgh16ARw06wVcPwGGAc4DAC3A1kCEJ1Im7/QDuBHIJqO4fE7xGPfAA9TnwG41ZLaeRQXnYccA+IbaHq3Lh0GoZPLhPxqscFjovdCQBgICs3DYimaEhmali8wegV2oggHqAvAJfBwlqsDd4EHydCHIe4OYA3AvgW0EcAgA9/mHvn74AXkAnfXDxbuxnr8ehwNMLgAiYRmLzGEdFRvtXyZb+IXn45FEQovMo0JEESOPB/Yod65z7x7iv4JMAetALYHsHh/MAJACmeuYBgk0h0EBXA5hK6BBQhwdo0AtwAqhDQUAAHSQIugOcPZ86iVDHTnoPHh/vGF6rBOi8/u+WwqdT7+RQG+4/P9wrA2NrZAYgzwJc5/4dAWoEHkedB7wAwacH4KErAbh/Lgk5kbNXwV3vhydg71ciYK2PiaA0uEagB8D50On6HREQB/iN2izeKMvJthUbpe/ZJ2W6lqhh4LQw6zgPAPxlYNMqyQyvxNqf7p9HQcf9qrp99nwHfl3dvyOAbnoCdM4BHAG4JMRzg+Af0MbmKPyBEgDPk7n8094PoINe38Ckj+6fPb8Bz6MS84SR4lq8dzgke8c7bxjoOAJwmB3cvh6Pffvx2JfLP/Z8EMCkjf1KAuf+dQ4AwNxKwBEAT/gBJjZ19B+SMBFs4GkfPYBgI0gwERQMBw24eDpK3QeAVD0FTxCSYFZ6erOyZXg9CHAE6afV8ZAvGaGzCIBOmuktSN/YRpnVnu+7/YLine truncated
|
||||
|
||||
export const AntigravityIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 128 128" fill="none">
|
||||
<image href={ANTIGRAVITY_ICON_DATA_URL} width="128" height="128" />
|
||||
</svg>
|
||||
);
|
||||
|
||||
export const OpenCodeIcon: Icon = (props) => (
|
||||
<svg {...props} viewBox="0 0 32 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<g clipPath="url(#opencode__clip0_1311_94969)">
|
||||
|
||||
@@ -98,6 +98,7 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
workUnits: [],
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
|
||||
Loaded 100 of 203 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user