Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
63ff52e33a | ||
|
|
f98679d217 | ||
|
|
5c9cfcd4c3 | ||
|
|
e6254a8451 | ||
|
|
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
|
||||
@@ -303,7 +309,7 @@ jobs:
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
@@ -314,7 +320,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
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
.idea/
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
@@ -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,10 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
commitMessage?: string;
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd);
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
@@ -680,6 +681,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
filePaths?: readonly string[],
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
@@ -688,6 +690,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
@@ -964,12 +967,18 @@ 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[],
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
});
|
||||
if (!suggestion) {
|
||||
@@ -1018,6 +1027,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.filePaths,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
@@ -1033,6 +1043,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
|
||||
@@ -101,6 +101,7 @@ export interface GitCoreShape {
|
||||
*/
|
||||
readonly prepareCommitContext: (
|
||||
cwd: string,
|
||||
filePaths?: readonly string[],
|
||||
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderModelOptions,
|
||||
type ProviderKind,
|
||||
ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
type OrchestrationSession,
|
||||
ThreadId,
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -74,6 +75,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 +142,7 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
const threadModelOptions = new Map<string, ProviderModelOptions>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -205,9 +212,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,8 +295,18 @@ 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;
|
||||
}
|
||||
|
||||
@@ -287,6 +325,7 @@ const make = Effect.gen(function* () {
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelOptionsChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
@@ -326,15 +365,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
|
||||
@@ -475,7 +517,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 +677,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,11 @@ 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,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -45,7 +49,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;
|
||||
@@ -402,6 +406,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();
|
||||
@@ -1354,6 +1412,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
payload: {
|
||||
taskId: "turn-task-1",
|
||||
description: "Comparing the desktop rollout chunks to the app-server stream.",
|
||||
summary: "Code reviewer is validating the desktop rollout chunks.",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1416,8 +1475,9 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(started?.kind).toBe("task.started");
|
||||
expect(started?.summary).toBe("Plan task started");
|
||||
expect(progress?.kind).toBe("task.progress");
|
||||
expect(progressPayload?.detail).toBe(
|
||||
"Comparing the desktop rollout chunks to the app-server stream.",
|
||||
expect(progressPayload?.detail).toBe("Code reviewer is validating the desktop rollout chunks.");
|
||||
expect(progressPayload?.summary).toBe(
|
||||
"Code reviewer is validating the desktop rollout chunks.",
|
||||
);
|
||||
expect(completed?.kind).toBe("task.completed");
|
||||
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
MessageId,
|
||||
type OrchestrationEvent,
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
@@ -173,18 +174,6 @@ function requestKindFromCanonicalRequestType(
|
||||
}
|
||||
}
|
||||
|
||||
function isToolLifecycleItemType(itemType: string): boolean {
|
||||
return (
|
||||
itemType === "command_execution" ||
|
||||
itemType === "file_change" ||
|
||||
itemType === "mcp_tool_call" ||
|
||||
itemType === "dynamic_tool_call" ||
|
||||
itemType === "collab_agent_tool_call" ||
|
||||
itemType === "web_search" ||
|
||||
itemType === "image_view"
|
||||
);
|
||||
}
|
||||
|
||||
function runtimeEventToActivities(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ReadonlyArray<OrchestrationThreadActivity> {
|
||||
@@ -381,7 +370,8 @@ function runtimeEventToActivities(
|
||||
summary: "Reasoning update",
|
||||
payload: {
|
||||
taskId: event.payload.taskId,
|
||||
detail: truncateDetail(event.payload.description),
|
||||
detail: truncateDetail(event.payload.summary ?? event.payload.description),
|
||||
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
|
||||
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
|
||||
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
|
||||
},
|
||||
@@ -449,7 +439,7 @@ function runtimeEventToActivities(
|
||||
createdAt: event.createdAt,
|
||||
tone: "tool",
|
||||
kind: "tool.completed",
|
||||
summary: `${event.payload.title ?? "Tool"} complete`,
|
||||
summary: event.payload.title ?? "Tool",
|
||||
payload: {
|
||||
itemType: event.payload.itemType,
|
||||
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
|
||||
|
||||
@@ -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
|
||||
|
||||
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();
|
||||
|
||||
@@ -164,7 +164,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":
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
getAppModelOptions,
|
||||
getSlashModelOptions,
|
||||
normalizeCustomModelSlugs,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
@@ -20,6 +20,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", () => {
|
||||
@@ -45,6 +52,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 +73,16 @@ 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);
|
||||
});
|
||||
});
|
||||
+28
-107
@@ -1,13 +1,18 @@
|
||||
import { useCallback, useSyncExternalStore } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
export const TIMESTAMP_FORMAT_OPTIONS = ["locale", "12-hour", "24-hour"] as const;
|
||||
export type TimestampFormat = (typeof TIMESTAMP_FORMAT_OPTIONS)[number];
|
||||
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({
|
||||
@@ -17,13 +22,22 @@ const AppSettingsSchema = Schema.Struct({
|
||||
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("")),
|
||||
),
|
||||
defaultThreadEnvMode: Schema.Literals(["local", "worktree"]).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some("local")),
|
||||
),
|
||||
confirmThreadDelete: Schema.Boolean.pipe(Schema.withConstructorDefault(() => Option.some(true))),
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(false)),
|
||||
),
|
||||
timestampFormat: Schema.Literals(["locale", "12-hour", "24-hour"]).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(DEFAULT_TIMESTAMP_FORMAT)),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some([])),
|
||||
),
|
||||
});
|
||||
export type AppSettings = typeof AppSettingsSchema.Type;
|
||||
export interface AppModelOption {
|
||||
@@ -34,10 +48,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 +81,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 +153,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,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,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { getRouter } from "../router";
|
||||
import { useStore } from "../store";
|
||||
import { estimateTimelineMessageHeight } from "./timelineHeight";
|
||||
@@ -152,6 +154,7 @@ function createSnapshotForTargetUser(options: {
|
||||
targetMessageId: MessageId;
|
||||
targetText: string;
|
||||
targetAttachmentCount?: number;
|
||||
sessionStatus?: OrchestrationSessionStatus;
|
||||
}): OrchestrationReadModel {
|
||||
const messages: Array<OrchestrationReadModel["threads"][number]["messages"][number]> = [];
|
||||
|
||||
@@ -221,7 +224,7 @@ function createSnapshotForTargetUser(options: {
|
||||
checkpoints: [],
|
||||
session: {
|
||||
threadId: THREAD_ID,
|
||||
status: "ready",
|
||||
status: options.sessionStatus ?? "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: null,
|
||||
@@ -353,7 +356,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 +399,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 +440,7 @@ const worker = setupWorker(
|
||||
client.send(
|
||||
JSON.stringify({
|
||||
id: request.id,
|
||||
result: resolveWsRpc(method),
|
||||
result: resolveWsRpc(request.body),
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -994,6 +1011,28 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
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 +1087,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,127 @@
|
||||
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";
|
||||
|
||||
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),
|
||||
};
|
||||
}
|
||||
+797
-2903
File diff suppressed because it is too large.
Load diff
@@ -47,7 +47,12 @@ import {
|
||||
type Ref,
|
||||
} from "react";
|
||||
|
||||
import { isCollapsedCursorAdjacentToMention } from "~/composer-logic";
|
||||
import {
|
||||
clampCollapsedComposerCursor,
|
||||
collapseExpandedComposerCursor,
|
||||
expandCollapsedComposerCursor,
|
||||
isCollapsedCursorAdjacentToMention,
|
||||
} from "~/composer-logic";
|
||||
import { splitPromptIntoComposerSegments } from "~/composer-editor-mentions";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { basenameOfPath, getVscodeIconUrlForEntry } from "~/vscode-icons";
|
||||
@@ -171,7 +176,7 @@ function renderMentionChipDom(container: HTMLElement, pathValue: string): void {
|
||||
container.append(icon, label);
|
||||
}
|
||||
|
||||
function clampCursor(value: string, cursor: number): number {
|
||||
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)));
|
||||
}
|
||||
@@ -192,6 +197,21 @@ function getComposerNodeTextLength(node: LexicalNode): number {
|
||||
return 0;
|
||||
}
|
||||
|
||||
function getComposerNodeExpandedTextLength(node: LexicalNode): number {
|
||||
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;
|
||||
@@ -236,6 +256,50 @@ 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 offset + (pointOffset > 0 ? node.getTextContentSize() : 0);
|
||||
}
|
||||
return offset + Math.min(pointOffset, node.getTextContentSize());
|
||||
}
|
||||
|
||||
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 },
|
||||
@@ -350,6 +414,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) {
|
||||
@@ -383,7 +458,7 @@ export interface ComposerPromptEditorHandle {
|
||||
focus: () => void;
|
||||
focusAt: (cursor: number) => void;
|
||||
focusAtEnd: () => void;
|
||||
readSnapshot: () => { value: string; cursor: number };
|
||||
readSnapshot: () => { value: string; cursor: number; expandedCursor: number };
|
||||
}
|
||||
|
||||
interface ComposerPromptEditorProps {
|
||||
@@ -392,7 +467,12 @@ interface ComposerPromptEditorProps {
|
||||
disabled: boolean;
|
||||
placeholder: string;
|
||||
className?: string;
|
||||
onChange: (nextValue: string, nextCursor: number, cursorAdjacentToMention: boolean) => void;
|
||||
onChange: (
|
||||
nextValue: string,
|
||||
nextCursor: number,
|
||||
expandedCursor: number,
|
||||
cursorAdjacentToMention: boolean,
|
||||
) => void;
|
||||
onCommandKeyDown?: (
|
||||
key: "ArrowDown" | "ArrowUp" | "Enter" | "Tab",
|
||||
event: KeyboardEvent,
|
||||
@@ -628,7 +708,13 @@ function ComposerPromptEditorInner({
|
||||
}: ComposerPromptEditorInnerProps) {
|
||||
const [editor] = useLexicalComposerContext();
|
||||
const onChangeRef = useRef(onChange);
|
||||
const snapshotRef = useRef({ value, cursor: clampCursor(value, cursor) });
|
||||
const initialCursor = clampCollapsedComposerCursor(value, cursor);
|
||||
const snapshotRef = useRef({
|
||||
value,
|
||||
cursor: initialCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, initialCursor),
|
||||
});
|
||||
const isApplyingControlledUpdateRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
onChangeRef.current = onChange;
|
||||
@@ -639,27 +725,36 @@ 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) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (previousSnapshot.value !== value) {
|
||||
editor.update(() => {
|
||||
$setComposerEditorPrompt(value);
|
||||
});
|
||||
}
|
||||
|
||||
snapshotRef.current = { value, cursor: normalizedCursor };
|
||||
snapshotRef.current = {
|
||||
value,
|
||||
cursor: normalizedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(value, normalizedCursor),
|
||||
};
|
||||
|
||||
const rootElement = editor.getRootElement();
|
||||
if (!rootElement || document.activeElement !== rootElement) {
|
||||
const isFocused = Boolean(rootElement && document.activeElement === rootElement);
|
||||
if (previousSnapshot.value === value && !isFocused) {
|
||||
return;
|
||||
}
|
||||
|
||||
isApplyingControlledUpdateRef.current = true;
|
||||
editor.update(() => {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
const valueChanged = previousSnapshot.value !== value;
|
||||
if (previousSnapshot.value !== value) {
|
||||
$setComposerEditorPrompt(value);
|
||||
}
|
||||
if (valueChanged || isFocused) {
|
||||
$setSelectionAtComposerOffset(normalizedCursor);
|
||||
}
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
isApplyingControlledUpdateRef.current = false;
|
||||
});
|
||||
}, [cursor, editor, value]);
|
||||
|
||||
@@ -667,7 +762,7 @@ function ComposerPromptEditorInner({
|
||||
(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 +770,43 @@ function ComposerPromptEditorInner({
|
||||
snapshotRef.current = {
|
||||
value: snapshotRef.current.value,
|
||||
cursor: boundedCursor,
|
||||
expandedCursor: expandCollapsedComposerCursor(snapshotRef.current.value, boundedCursor),
|
||||
};
|
||||
onChangeRef.current(snapshotRef.current.value, boundedCursor, false);
|
||||
onChangeRef.current(
|
||||
snapshotRef.current.value,
|
||||
boundedCursor,
|
||||
snapshotRef.current.expandedCursor,
|
||||
false,
|
||||
);
|
||||
},
|
||||
[editor],
|
||||
);
|
||||
|
||||
const readSnapshot = useCallback((): { value: string; cursor: number } => {
|
||||
const readSnapshot = useCallback((): {
|
||||
value: string;
|
||||
cursor: number;
|
||||
expandedCursor: number;
|
||||
} => {
|
||||
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),
|
||||
);
|
||||
snapshot = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
};
|
||||
});
|
||||
snapshotRef.current = snapshot;
|
||||
@@ -705,11 +819,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,23 +836,39 @@ 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 previousSnapshot = snapshotRef.current;
|
||||
if (previousSnapshot.value === nextValue && previousSnapshot.cursor === nextCursor) {
|
||||
if (
|
||||
previousSnapshot.value === nextValue &&
|
||||
previousSnapshot.cursor === nextCursor &&
|
||||
previousSnapshot.expandedCursor === nextExpandedCursor
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (isApplyingControlledUpdateRef.current) {
|
||||
return;
|
||||
}
|
||||
snapshotRef.current = {
|
||||
value: nextValue,
|
||||
cursor: nextCursor,
|
||||
expandedCursor: nextExpandedCursor,
|
||||
};
|
||||
const cursorAdjacentToMention =
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "left") ||
|
||||
isCollapsedCursorAdjacentToMention(nextValue, nextCursor, "right");
|
||||
onChangeRef.current(nextValue, nextCursor, cursorAdjacentToMention);
|
||||
onChangeRef.current(nextValue, nextCursor, nextExpandedCursor, cursorAdjacentToMention);
|
||||
});
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Checkbox } from "~/components/ui/checkbox";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
@@ -31,6 +32,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 +42,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 +57,7 @@ interface PendingDefaultBranchAction {
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress: boolean;
|
||||
onConfirmed?: () => void;
|
||||
filePaths?: string[];
|
||||
}
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
@@ -158,6 +161,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,6 +183,11 @@ 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(
|
||||
@@ -256,6 +266,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
featureBranch = false,
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
filePaths,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
@@ -266,6 +277,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 +300,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -337,6 +350,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -438,7 +452,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 +460,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, runGitActionWithToast]);
|
||||
@@ -456,6 +471,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
filePaths?: string[];
|
||||
}) => {
|
||||
void runGitActionWithToast({
|
||||
...actionParams,
|
||||
@@ -468,7 +484,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 +492,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
});
|
||||
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
|
||||
|
||||
@@ -485,12 +502,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 +573,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 +585,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 +614,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 +762,8 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
if (!open) {
|
||||
setIsCommitDialogOpen(false);
|
||||
setDialogCommitMessage("");
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -751,37 +786,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 +902,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)">
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { memo, useState, useCallback } from "react";
|
||||
import { type TimestampFormat } from "../appSettings";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Button } from "./ui/button";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
@@ -12,9 +13,9 @@ import {
|
||||
PanelRightCloseIcon,
|
||||
} from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { formatTimestamp } from "../session-logic";
|
||||
import type { ActivePlanState } from "../session-logic";
|
||||
import type { LatestProposedPlanState } from "../session-logic";
|
||||
import { formatTimestamp } from "../timestampFormat";
|
||||
import {
|
||||
proposedPlanTitle,
|
||||
buildProposedPlanMarkdownFilename,
|
||||
@@ -25,6 +26,7 @@ import {
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
|
||||
function stepStatusIcon(status: string): React.ReactNode {
|
||||
if (status === "completed") {
|
||||
@@ -53,6 +55,7 @@ interface PlanSidebarProps {
|
||||
activeProposedPlan: LatestProposedPlanState | null;
|
||||
markdownCwd: string | undefined;
|
||||
workspaceRoot: string | undefined;
|
||||
timestampFormat: TimestampFormat;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -61,11 +64,12 @@ const PlanSidebar = memo(function PlanSidebar({
|
||||
activeProposedPlan,
|
||||
markdownCwd,
|
||||
workspaceRoot,
|
||||
timestampFormat,
|
||||
onClose,
|
||||
}: PlanSidebarProps) {
|
||||
const [proposedPlanExpanded, setProposedPlanExpanded] = useState(false);
|
||||
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
|
||||
const planMarkdown = activeProposedPlan?.planMarkdown ?? null;
|
||||
const displayedPlanMarkdown = planMarkdown ? stripDisplayedPlanMarkdown(planMarkdown) : null;
|
||||
@@ -73,10 +77,8 @@ const PlanSidebar = memo(function PlanSidebar({
|
||||
|
||||
const handleCopyPlan = useCallback(() => {
|
||||
if (!planMarkdown) return;
|
||||
void navigator.clipboard.writeText(planMarkdown);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 2000);
|
||||
}, [planMarkdown]);
|
||||
copyToClipboard(planMarkdown);
|
||||
}, [planMarkdown, copyToClipboard]);
|
||||
|
||||
const handleDownload = useCallback(() => {
|
||||
if (!planMarkdown) return;
|
||||
@@ -128,7 +130,7 @@ const PlanSidebar = memo(function PlanSidebar({
|
||||
</Badge>
|
||||
{activePlan ? (
|
||||
<span className="text-[11px] text-muted-foreground/60">
|
||||
{formatTimestamp(activePlan.createdAt)}
|
||||
{formatTimestamp(activePlan.createdAt, timestampFormat)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
@@ -149,7 +151,7 @@ const PlanSidebar = memo(function PlanSidebar({
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
<MenuItem onClick={handleCopyPlan}>
|
||||
{copied ? "Copied!" : "Copy to clipboard"}
|
||||
{isCopied ? "Copied!" : "Copy to clipboard"}
|
||||
</MenuItem>
|
||||
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
|
||||
<MenuItem
|
||||
|
||||
@@ -420,6 +420,7 @@ export default function ProjectScriptsControl({
|
||||
</Popover>
|
||||
<Input
|
||||
id="script-name"
|
||||
autoFocus
|
||||
placeholder="Test"
|
||||
value={name}
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
|
||||
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
hasUnseenCompletion,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
} from "./Sidebar.logic";
|
||||
@@ -62,6 +64,25 @@ describe("shouldClearThreadSelectionOnMouseDown", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveSidebarNewThreadEnvMode", () => {
|
||||
it("uses the app default when the caller does not request a specific mode", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("worktree");
|
||||
});
|
||||
|
||||
it("preserves an explicit requested mode over the app default", () => {
|
||||
expect(
|
||||
resolveSidebarNewThreadEnvMode({
|
||||
requestedEnvMode: "local",
|
||||
defaultEnvMode: "worktree",
|
||||
}),
|
||||
).toBe("local");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadStatusPill", () => {
|
||||
const baseThread = {
|
||||
interactionMode: "plan" as const,
|
||||
@@ -154,3 +175,27 @@ describe("resolveThreadStatusPill", () => {
|
||||
).toMatchObject({ label: "Completed", pulse: false });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveThreadRowClassName", () => {
|
||||
it("uses the darker selected palette when a thread is both selected and active", () => {
|
||||
const className = resolveThreadRowClassName({ isActive: true, isSelected: true });
|
||||
expect(className).toContain("bg-primary/22");
|
||||
expect(className).toContain("hover:bg-primary/26");
|
||||
expect(className).toContain("dark:bg-primary/30");
|
||||
expect(className).not.toContain("bg-accent/85");
|
||||
});
|
||||
|
||||
it("uses selected hover colors for selected threads", () => {
|
||||
const className = resolveThreadRowClassName({ isActive: false, isSelected: true });
|
||||
expect(className).toContain("bg-primary/15");
|
||||
expect(className).toContain("hover:bg-primary/19");
|
||||
expect(className).toContain("dark:bg-primary/22");
|
||||
expect(className).not.toContain("hover:bg-accent");
|
||||
});
|
||||
|
||||
it("keeps the accent palette for active-only threads", () => {
|
||||
const className = resolveThreadRowClassName({ isActive: true, isSelected: false });
|
||||
expect(className).toContain("bg-accent/85");
|
||||
expect(className).toContain("hover:bg-accent");
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,9 @@
|
||||
import type { Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import { findLatestProposedPlan, isLatestTurnSettled } from "../session-logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
|
||||
export interface ThreadStatusPill {
|
||||
label:
|
||||
@@ -37,6 +39,44 @@ export function shouldClearThreadSelectionOnMouseDown(target: HTMLElement | null
|
||||
return !target.closest(THREAD_SELECTION_SAFE_SELECTOR);
|
||||
}
|
||||
|
||||
export function resolveSidebarNewThreadEnvMode(input: {
|
||||
requestedEnvMode?: SidebarNewThreadEnvMode;
|
||||
defaultEnvMode: SidebarNewThreadEnvMode;
|
||||
}): SidebarNewThreadEnvMode {
|
||||
return input.requestedEnvMode ?? input.defaultEnvMode;
|
||||
}
|
||||
|
||||
export function resolveThreadRowClassName(input: {
|
||||
isActive: boolean;
|
||||
isSelected: boolean;
|
||||
}): string {
|
||||
const baseClassName =
|
||||
"h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-ring";
|
||||
|
||||
if (input.isSelected && input.isActive) {
|
||||
return cn(
|
||||
baseClassName,
|
||||
"bg-primary/22 text-foreground font-medium hover:bg-primary/26 hover:text-foreground dark:bg-primary/30 dark:hover:bg-primary/36",
|
||||
);
|
||||
}
|
||||
|
||||
if (input.isSelected) {
|
||||
return cn(
|
||||
baseClassName,
|
||||
"bg-primary/15 text-foreground hover:bg-primary/19 hover:text-foreground dark:bg-primary/22 dark:hover:bg-primary/28",
|
||||
);
|
||||
}
|
||||
|
||||
if (input.isActive) {
|
||||
return cn(
|
||||
baseClassName,
|
||||
"bg-accent/85 text-foreground font-medium hover:bg-accent hover:text-foreground dark:bg-accent/55 dark:hover:bg-accent/70",
|
||||
);
|
||||
}
|
||||
|
||||
return cn(baseClassName, "text-muted-foreground hover:bg-accent hover:text-foreground");
|
||||
}
|
||||
|
||||
export function resolveThreadStatusPill(input: {
|
||||
thread: ThreadStatusInput;
|
||||
hasPendingApprovals: boolean;
|
||||
|
||||
@@ -27,7 +27,6 @@ import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-
|
||||
import { restrictToParentElement, restrictToVerticalAxis } from "@dnd-kit/modifiers";
|
||||
import { CSS } from "@dnd-kit/utilities";
|
||||
import {
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type DesktopUpdateState,
|
||||
ProjectId,
|
||||
@@ -40,14 +39,15 @@ import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
|
||||
import { isMacPlatform, newCommandId, newProjectId, newThreadId } from "../lib/utils";
|
||||
import { isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
|
||||
import { useStore } from "../store";
|
||||
import { isChatNewLocalShortcut, isChatNewShortcut, shortcutLabelForCommand } from "../keybindings";
|
||||
import { shortcutLabelForCommand } from "../keybindings";
|
||||
import { derivePendingApprovals, derivePendingUserInputs } from "../session-logic";
|
||||
import { gitRemoveWorktreeMutationOptions, gitStatusQueryOptions } from "../lib/gitReactQuery";
|
||||
import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { type DraftThreadEnvMode, useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { toastManager } from "./ui/toast";
|
||||
import {
|
||||
@@ -83,18 +83,17 @@ import {
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import { resolveThreadStatusPill, shouldClearThreadSelectionOnMouseDown } from "./Sidebar.logic";
|
||||
import {
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
} from "./Sidebar.logic";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
|
||||
async function copyTextToClipboard(text: string): Promise<void> {
|
||||
if (typeof navigator === "undefined" || navigator.clipboard?.writeText === undefined) {
|
||||
throw new Error("Clipboard API unavailable.");
|
||||
}
|
||||
await navigator.clipboard.writeText(text);
|
||||
}
|
||||
|
||||
function formatRelativeTime(iso: string): string {
|
||||
const diff = Date.now() - new Date(iso).getTime();
|
||||
const minutes = Math.floor(diff / 60_000);
|
||||
@@ -262,11 +261,8 @@ export default function Sidebar() {
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
(store) => store.getDraftThreadByProjectId,
|
||||
);
|
||||
const getDraftThread = useComposerDraftStore((store) => store.getDraftThread);
|
||||
const terminalStateByThreadId = useTerminalStateStore((state) => state.terminalStateByThreadId);
|
||||
const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
|
||||
const setProjectDraftThreadId = useComposerDraftStore((store) => store.setProjectDraftThreadId);
|
||||
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
|
||||
const clearProjectDraftThreadId = useComposerDraftStore(
|
||||
(store) => store.clearProjectDraftThreadId,
|
||||
);
|
||||
@@ -276,6 +272,7 @@ export default function Sidebar() {
|
||||
const navigate = useNavigate();
|
||||
const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const { handleNewThread } = useHandleNewThread();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
|
||||
@@ -310,20 +307,6 @@ export default function Sidebar() {
|
||||
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
|
||||
const shouldBrowseForProjectImmediately = isElectron;
|
||||
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
|
||||
const pendingApprovalByThreadId = useMemo(() => {
|
||||
const map = new Map<ThreadId, boolean>();
|
||||
for (const thread of threads) {
|
||||
map.set(thread.id, derivePendingApprovals(thread.activities).length > 0);
|
||||
}
|
||||
return map;
|
||||
}, [threads]);
|
||||
const pendingUserInputByThreadId = useMemo(() => {
|
||||
const map = new Map<ThreadId, boolean>();
|
||||
for (const thread of threads) {
|
||||
map.set(thread.id, derivePendingUserInputs(thread.activities).length > 0);
|
||||
}
|
||||
return map;
|
||||
}, [threads]);
|
||||
const projectCwdById = useMemo(
|
||||
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
|
||||
[projects],
|
||||
@@ -398,80 +381,6 @@ export default function Sidebar() {
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleNewThread = useCallback(
|
||||
(
|
||||
projectId: ProjectId,
|
||||
options?: {
|
||||
branch?: string | null;
|
||||
worktreePath?: string | null;
|
||||
envMode?: DraftThreadEnvMode;
|
||||
},
|
||||
): Promise<void> => {
|
||||
const hasBranchOption = options?.branch !== undefined;
|
||||
const hasWorktreePathOption = options?.worktreePath !== undefined;
|
||||
const hasEnvModeOption = options?.envMode !== undefined;
|
||||
const storedDraftThread = getDraftThreadByProjectId(projectId);
|
||||
if (storedDraftThread) {
|
||||
return (async () => {
|
||||
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
|
||||
setDraftThreadContext(storedDraftThread.threadId, {
|
||||
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
||||
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
||||
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
||||
});
|
||||
}
|
||||
setProjectDraftThreadId(projectId, storedDraftThread.threadId);
|
||||
if (routeThreadId === storedDraftThread.threadId) {
|
||||
return;
|
||||
}
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: storedDraftThread.threadId },
|
||||
});
|
||||
})();
|
||||
}
|
||||
clearProjectDraftThreadId(projectId);
|
||||
|
||||
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
|
||||
if (activeDraftThread && routeThreadId && activeDraftThread.projectId === projectId) {
|
||||
if (hasBranchOption || hasWorktreePathOption || hasEnvModeOption) {
|
||||
setDraftThreadContext(routeThreadId, {
|
||||
...(hasBranchOption ? { branch: options?.branch ?? null } : {}),
|
||||
...(hasWorktreePathOption ? { worktreePath: options?.worktreePath ?? null } : {}),
|
||||
...(hasEnvModeOption ? { envMode: options?.envMode } : {}),
|
||||
});
|
||||
}
|
||||
setProjectDraftThreadId(projectId, routeThreadId);
|
||||
return Promise.resolve();
|
||||
}
|
||||
const threadId = newThreadId();
|
||||
const createdAt = new Date().toISOString();
|
||||
return (async () => {
|
||||
setProjectDraftThreadId(projectId, threadId, {
|
||||
createdAt,
|
||||
branch: options?.branch ?? null,
|
||||
worktreePath: options?.worktreePath ?? null,
|
||||
envMode: options?.envMode ?? "local",
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
});
|
||||
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId },
|
||||
});
|
||||
})();
|
||||
},
|
||||
[
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThreadByProjectId,
|
||||
navigate,
|
||||
getDraftThread,
|
||||
routeThreadId,
|
||||
setDraftThreadContext,
|
||||
setProjectDraftThreadId,
|
||||
],
|
||||
);
|
||||
|
||||
const focusMostRecentThreadForProject = useCallback(
|
||||
(projectId: ProjectId) => {
|
||||
const latestThread = threads
|
||||
@@ -526,7 +435,9 @@ export default function Sidebar() {
|
||||
defaultModel: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
createdAt,
|
||||
});
|
||||
await handleNewThread(projectId).catch(() => undefined);
|
||||
await handleNewThread(projectId, {
|
||||
envMode: appSettings.defaultThreadEnvMode,
|
||||
}).catch(() => undefined);
|
||||
} catch (error) {
|
||||
const description =
|
||||
error instanceof Error ? error.message : "An error occurred while adding the project.";
|
||||
@@ -550,6 +461,7 @@ export default function Sidebar() {
|
||||
isAddingProject,
|
||||
projects,
|
||||
shouldBrowseForProjectImmediately,
|
||||
appSettings.defaultThreadEnvMode,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -753,6 +665,22 @@ export default function Sidebar() {
|
||||
],
|
||||
);
|
||||
|
||||
const { copyToClipboard } = useCopyToClipboard<{ threadId: ThreadId }>({
|
||||
onCopy: (ctx) => {
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Thread ID copied",
|
||||
description: ctx.threadId,
|
||||
});
|
||||
},
|
||||
onError: (error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy thread ID",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
},
|
||||
});
|
||||
const handleThreadContextMenu = useCallback(
|
||||
async (threadId: ThreadId, position: { x: number; y: number }) => {
|
||||
const api = readNativeApi();
|
||||
@@ -781,20 +709,7 @@ export default function Sidebar() {
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-thread-id") {
|
||||
try {
|
||||
await copyTextToClipboard(threadId);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Thread ID copied",
|
||||
description: threadId,
|
||||
});
|
||||
} catch (error) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to copy thread ID",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
}
|
||||
copyToClipboard(threadId, { threadId });
|
||||
return;
|
||||
}
|
||||
if (clicked !== "delete") return;
|
||||
@@ -811,7 +726,7 @@ export default function Sidebar() {
|
||||
}
|
||||
await deleteThread(threadId);
|
||||
},
|
||||
[appSettings.confirmThreadDelete, deleteThread, markThreadUnread, threads],
|
||||
[appSettings.confirmThreadDelete, copyToClipboard, deleteThread, markThreadUnread, threads],
|
||||
);
|
||||
|
||||
const handleMultiSelectContextMenu = useCallback(
|
||||
@@ -909,7 +824,7 @@ export default function Sidebar() {
|
||||
const api = readNativeApi();
|
||||
if (!api) return;
|
||||
const clicked = await api.contextMenu.show(
|
||||
[{ id: "delete", label: "Delete", destructive: true }],
|
||||
[{ id: "delete", label: "Remove project", destructive: true }],
|
||||
position,
|
||||
);
|
||||
if (clicked !== "delete") return;
|
||||
@@ -922,14 +837,12 @@ export default function Sidebar() {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Project is not empty",
|
||||
description: "Delete all threads in this project before deleting it.",
|
||||
description: "Delete all threads in this project before removing it.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const confirmed = await api.dialogs.confirm(
|
||||
[`Delete project "${project.name}"?`, "This action cannot be undone."].join("\n"),
|
||||
);
|
||||
const confirmed = await api.dialogs.confirm(`Remove project "${project.name}"?`);
|
||||
if (!confirmed) return;
|
||||
|
||||
try {
|
||||
@@ -944,11 +857,11 @@ export default function Sidebar() {
|
||||
projectId,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error deleting project.";
|
||||
const message = error instanceof Error ? error.message : "Unknown error removing project.";
|
||||
console.error("Failed to remove project", { projectId, error });
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: `Failed to delete "${project.name}"`,
|
||||
title: `Failed to remove "${project.name}"`,
|
||||
description: message,
|
||||
});
|
||||
}
|
||||
@@ -1037,37 +950,6 @@ export default function Sidebar() {
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape" && selectedThreadIds.size > 0) {
|
||||
event.preventDefault();
|
||||
clearSelection();
|
||||
return;
|
||||
}
|
||||
|
||||
const activeThread = routeThreadId
|
||||
? threads.find((thread) => thread.id === routeThreadId)
|
||||
: undefined;
|
||||
const activeDraftThread = routeThreadId ? getDraftThread(routeThreadId) : null;
|
||||
if (isChatNewLocalShortcut(event, keybindings)) {
|
||||
const projectId =
|
||||
activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isChatNewShortcut(event, keybindings)) return;
|
||||
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
|
||||
if (!projectId) return;
|
||||
event.preventDefault();
|
||||
void handleNewThread(projectId, {
|
||||
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
|
||||
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
|
||||
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
|
||||
});
|
||||
};
|
||||
|
||||
const onMouseDown = (event: globalThis.MouseEvent) => {
|
||||
if (selectedThreadIds.size === 0) return;
|
||||
const target = event.target instanceof HTMLElement ? event.target : null;
|
||||
@@ -1075,22 +957,11 @@ export default function Sidebar() {
|
||||
clearSelection();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
window.addEventListener("mousedown", onMouseDown);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onWindowKeyDown);
|
||||
window.removeEventListener("mousedown", onMouseDown);
|
||||
};
|
||||
}, [
|
||||
clearSelection,
|
||||
getDraftThread,
|
||||
handleNewThread,
|
||||
keybindings,
|
||||
projects,
|
||||
routeThreadId,
|
||||
selectedThreadIds.size,
|
||||
threads,
|
||||
]);
|
||||
}, [clearSelection, selectedThreadIds.size]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isElectron) return;
|
||||
@@ -1241,7 +1112,7 @@ export default function Sidebar() {
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 mt-1.5 ml-1 cursor-pointer">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-1 ml-1 cursor-pointer">
|
||||
<T3Wordmark />
|
||||
<span className="truncate text-sm font-medium tracking-tight text-muted-foreground">
|
||||
Code
|
||||
@@ -1485,7 +1356,11 @@ export default function Sidebar() {
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void handleNewThread(project.id);
|
||||
void handleNewThread(project.id, {
|
||||
envMode: resolveSidebarNewThreadEnvMode({
|
||||
defaultEnvMode: appSettings.defaultThreadEnvMode,
|
||||
}),
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SquarePenIcon className="size-3.5" />
|
||||
@@ -1509,9 +1384,9 @@ export default function Sidebar() {
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread,
|
||||
hasPendingApprovals:
|
||||
pendingApprovalByThreadId.get(thread.id) === true,
|
||||
derivePendingApprovals(thread.activities).length > 0,
|
||||
hasPendingUserInput:
|
||||
pendingUserInputByThreadId.get(thread.id) === true,
|
||||
derivePendingUserInputs(thread.activities).length > 0,
|
||||
});
|
||||
const prStatus = prStatusIndicator(
|
||||
prByThreadId.get(thread.id) ?? null,
|
||||
@@ -1531,13 +1406,10 @@ export default function Sidebar() {
|
||||
render={<div role="button" tabIndex={0} />}
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
className={`h-7 w-full translate-x-0 cursor-default justify-start px-2 text-left select-none hover:bg-accent hover:text-foreground focus-visible:ring-0 ${
|
||||
isSelected
|
||||
? "bg-primary/15 text-foreground dark:bg-primary/10"
|
||||
: isActive
|
||||
? "bg-accent/85 text-foreground font-medium dark:bg-accent/55"
|
||||
: "text-muted-foreground"
|
||||
}`}
|
||||
className={resolveThreadRowClassName({
|
||||
isActive,
|
||||
isSelected,
|
||||
})}
|
||||
onClick={(event) => {
|
||||
handleThreadClick(
|
||||
event,
|
||||
@@ -1675,7 +1547,7 @@ export default function Sidebar() {
|
||||
<span
|
||||
className={`text-[10px] ${
|
||||
isHighlighted
|
||||
? "text-foreground/65"
|
||||
? "text-foreground/72 dark:text-foreground/82"
|
||||
: "text-muted-foreground/40"
|
||||
}`}
|
||||
>
|
||||
|
||||
@@ -12,17 +12,17 @@ import {
|
||||
useState,
|
||||
} from "react";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { openInPreferredEditor } from "../editorPreferences";
|
||||
import {
|
||||
extractTerminalLinks,
|
||||
isTerminalLinkActivation,
|
||||
preferredTerminalEditor,
|
||||
resolvePathLinkTarget,
|
||||
} from "../terminal-links";
|
||||
import { isTerminalClearShortcut, terminalNavigationShortcutData } from "../keybindings";
|
||||
import {
|
||||
DEFAULT_THREAD_TERMINAL_HEIGHT,
|
||||
DEFAULT_THREAD_TERMINAL_ID,
|
||||
MAX_THREAD_TERMINAL_COUNT,
|
||||
MAX_TERMINALS_PER_GROUP,
|
||||
type ThreadTerminalGroup,
|
||||
} from "../types";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
@@ -236,7 +236,7 @@ function TerminalViewport({
|
||||
}
|
||||
|
||||
const target = resolvePathLinkTarget(match.text, cwd);
|
||||
void api.shell.openInEditor(target, preferredTerminalEditor()).catch((error) => {
|
||||
void openInPreferredEditor(api, target).catch((error) => {
|
||||
writeSystemMessage(
|
||||
latestTerminal,
|
||||
error instanceof Error ? error.message : "Unable to open path",
|
||||
@@ -605,7 +605,7 @@ export default function ThreadTerminalDrawer({
|
||||
const showGroupHeaders =
|
||||
resolvedTerminalGroups.length > 1 ||
|
||||
resolvedTerminalGroups.some((terminalGroup) => terminalGroup.terminalIds.length > 1);
|
||||
const hasReachedTerminalLimit = normalizedTerminalIds.length >= MAX_THREAD_TERMINAL_COUNT;
|
||||
const hasReachedSplitLimit = visibleTerminalIds.length >= MAX_TERMINALS_PER_GROUP;
|
||||
const terminalLabelById = useMemo(
|
||||
() =>
|
||||
new Map(
|
||||
@@ -613,27 +613,24 @@ export default function ThreadTerminalDrawer({
|
||||
),
|
||||
[normalizedTerminalIds],
|
||||
);
|
||||
const splitTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `Split Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
const splitTerminalActionLabel = hasReachedSplitLimit
|
||||
? `Split Terminal (max ${MAX_TERMINALS_PER_GROUP} per group)`
|
||||
: splitShortcutLabel
|
||||
? `Split Terminal (${splitShortcutLabel})`
|
||||
: "Split Terminal";
|
||||
const newTerminalActionLabel = hasReachedTerminalLimit
|
||||
? `New Terminal (max ${MAX_THREAD_TERMINAL_COUNT})`
|
||||
: newShortcutLabel
|
||||
? `New Terminal (${newShortcutLabel})`
|
||||
: "New Terminal";
|
||||
const newTerminalActionLabel = newShortcutLabel
|
||||
? `New Terminal (${newShortcutLabel})`
|
||||
: "New Terminal";
|
||||
const closeTerminalActionLabel = closeShortcutLabel
|
||||
? `Close Terminal (${closeShortcutLabel})`
|
||||
: "Close Terminal";
|
||||
const onSplitTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
if (hasReachedSplitLimit) return;
|
||||
onSplitTerminal();
|
||||
}, [hasReachedTerminalLimit, onSplitTerminal]);
|
||||
}, [hasReachedSplitLimit, onSplitTerminal]);
|
||||
const onNewTerminalAction = useCallback(() => {
|
||||
if (hasReachedTerminalLimit) return;
|
||||
onNewTerminal();
|
||||
}, [hasReachedTerminalLimit, onNewTerminal]);
|
||||
}, [onNewTerminal]);
|
||||
|
||||
useEffect(() => {
|
||||
onHeightChangeRef.current = onHeightChange;
|
||||
@@ -744,7 +741,7 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="pointer-events-auto inline-flex items-center overflow-hidden rounded-md border border-border/80 bg-background/70">
|
||||
<TerminalActionButton
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
hasReachedSplitLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
@@ -755,11 +752,7 @@ export default function ThreadTerminalDrawer({
|
||||
</TerminalActionButton>
|
||||
<div className="h-4 w-px bg-border/80" />
|
||||
<TerminalActionButton
|
||||
className={`p-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent"
|
||||
}`}
|
||||
className="p-1 text-foreground/90 transition-colors hover:bg-accent"
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
@@ -839,7 +832,7 @@ export default function ThreadTerminalDrawer({
|
||||
<div className="inline-flex h-full items-stretch">
|
||||
<TerminalActionButton
|
||||
className={`inline-flex h-full items-center px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
hasReachedSplitLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
@@ -849,11 +842,7 @@ export default function ThreadTerminalDrawer({
|
||||
<SquareSplitHorizontal className="size-3.25" />
|
||||
</TerminalActionButton>
|
||||
<TerminalActionButton
|
||||
className={`inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors ${
|
||||
hasReachedTerminalLimit
|
||||
? "cursor-not-allowed opacity-45 hover:bg-transparent"
|
||||
: "hover:bg-accent/70"
|
||||
}`}
|
||||
className="inline-flex h-full items-center border-l border-border/70 px-1 text-foreground/90 transition-colors hover:bg-accent/70"
|
||||
onClick={onNewTerminalAction}
|
||||
label={newTerminalActionLabel}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { type TurnId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { type TurnDiffFileChange } from "../../types";
|
||||
import { buildTurnDiffTree, type TurnDiffTreeNode } from "../../lib/turnDiffTree";
|
||||
import { ChevronRightIcon, FolderIcon, FolderClosedIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
|
||||
export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
turnId: TurnId;
|
||||
files: ReadonlyArray<TurnDiffFileChange>;
|
||||
allDirectoriesExpanded: boolean;
|
||||
resolvedTheme: "light" | "dark";
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
}) {
|
||||
const { files, allDirectoriesExpanded, onOpenTurnDiff, resolvedTheme, turnId } = props;
|
||||
const treeNodes = useMemo(() => buildTurnDiffTree(files), [files]);
|
||||
const directoryPathsKey = useMemo(
|
||||
() => collectDirectoryPaths(treeNodes).join("\u0000"),
|
||||
[treeNodes],
|
||||
);
|
||||
const allDirectoryExpansionState = useMemo(
|
||||
() =>
|
||||
buildDirectoryExpansionState(
|
||||
directoryPathsKey ? directoryPathsKey.split("\u0000") : [],
|
||||
allDirectoriesExpanded,
|
||||
),
|
||||
[allDirectoriesExpanded, directoryPathsKey],
|
||||
);
|
||||
const [expandedDirectories, setExpandedDirectories] = useState<Record<string, boolean>>(() =>
|
||||
buildDirectoryExpansionState(directoryPathsKey ? directoryPathsKey.split("\u0000") : [], true),
|
||||
);
|
||||
useEffect(() => {
|
||||
setExpandedDirectories(allDirectoryExpansionState);
|
||||
}, [allDirectoryExpansionState]);
|
||||
|
||||
const toggleDirectory = useCallback((pathValue: string, fallbackExpanded: boolean) => {
|
||||
setExpandedDirectories((current) => ({
|
||||
...current,
|
||||
[pathValue]: !(current[pathValue] ?? fallbackExpanded),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const renderTreeNode = (node: TurnDiffTreeNode, depth: number) => {
|
||||
const leftPadding = 8 + depth * 14;
|
||||
if (node.kind === "directory") {
|
||||
const isExpanded = expandedDirectories[node.path] ?? depth === 0;
|
||||
return (
|
||||
<div key={`dir:${node.path}`}>
|
||||
<button
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => toggleDirectory(node.path, depth === 0)}
|
||||
>
|
||||
<ChevronRightIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-3.5 shrink-0 text-muted-foreground/70 transition-transform group-hover:text-foreground/80",
|
||||
isExpanded && "rotate-90",
|
||||
)}
|
||||
/>
|
||||
{isExpanded ? (
|
||||
<FolderIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
|
||||
) : (
|
||||
<FolderClosedIcon className="size-3.5 shrink-0 text-muted-foreground/75" />
|
||||
)}
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground/90 group-hover:text-foreground/90">
|
||||
{node.name}
|
||||
</span>
|
||||
{hasNonZeroStat(node.stat) && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div className="space-y-0.5">
|
||||
{node.children.map((childNode) => renderTreeNode(childNode, depth + 1))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<button
|
||||
key={`file:${node.path}`}
|
||||
type="button"
|
||||
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => onOpenTurnDiff(turnId, node.path)}
|
||||
>
|
||||
<span aria-hidden="true" className="size-3.5 shrink-0" />
|
||||
<VscodeEntryIcon
|
||||
pathValue={node.path}
|
||||
kind="file"
|
||||
theme={resolvedTheme}
|
||||
className="size-3.5 text-muted-foreground/70"
|
||||
/>
|
||||
<span className="truncate font-mono text-[11px] text-muted-foreground/80 group-hover:text-foreground/90">
|
||||
{node.name}
|
||||
</span>
|
||||
{node.stat && (
|
||||
<span className="ml-auto shrink-0 font-mono text-[10px] tabular-nums">
|
||||
<DiffStatLabel additions={node.stat.additions} deletions={node.stat.deletions} />
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
return <div className="space-y-0.5">{treeNodes.map((node) => renderTreeNode(node, 0))}</div>;
|
||||
});
|
||||
|
||||
function collectDirectoryPaths(nodes: ReadonlyArray<TurnDiffTreeNode>): string[] {
|
||||
const paths: string[] = [];
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== "directory") continue;
|
||||
paths.push(node.path);
|
||||
paths.push(...collectDirectoryPaths(node.children));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
function buildDirectoryExpansionState(
|
||||
directoryPaths: ReadonlyArray<string>,
|
||||
expanded: boolean,
|
||||
): Record<string, boolean> {
|
||||
const expandedState: Record<string, boolean> = {};
|
||||
for (const directoryPath of directoryPaths) {
|
||||
expandedState[directoryPath] = expanded;
|
||||
}
|
||||
return expandedState;
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
type EditorId,
|
||||
type ProjectScript,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import GitActionsControl from "../GitActionsControl";
|
||||
import { DiffIcon } from "lucide-react";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
|
||||
import { Toggle } from "../ui/toggle";
|
||||
import { SidebarTrigger } from "../ui/sidebar";
|
||||
import { OpenInPicker } from "./OpenInPicker";
|
||||
|
||||
interface ChatHeaderProps {
|
||||
activeThreadId: ThreadId;
|
||||
activeThreadTitle: string;
|
||||
activeProjectName: string | undefined;
|
||||
isGitRepo: boolean;
|
||||
openInCwd: string | null;
|
||||
activeProjectScripts: ProjectScript[] | undefined;
|
||||
preferredScriptId: string | null;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
availableEditors: ReadonlyArray<EditorId>;
|
||||
diffToggleShortcutLabel: string | null;
|
||||
gitCwd: string | null;
|
||||
diffOpen: boolean;
|
||||
onRunProjectScript: (script: ProjectScript) => void;
|
||||
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
|
||||
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
|
||||
onDeleteProjectScript: (scriptId: string) => Promise<void>;
|
||||
onToggleDiff: () => void;
|
||||
}
|
||||
|
||||
export const ChatHeader = memo(function ChatHeader({
|
||||
activeThreadId,
|
||||
activeThreadTitle,
|
||||
activeProjectName,
|
||||
isGitRepo,
|
||||
openInCwd,
|
||||
activeProjectScripts,
|
||||
preferredScriptId,
|
||||
keybindings,
|
||||
availableEditors,
|
||||
diffToggleShortcutLabel,
|
||||
gitCwd,
|
||||
diffOpen,
|
||||
onRunProjectScript,
|
||||
onAddProjectScript,
|
||||
onUpdateProjectScript,
|
||||
onDeleteProjectScript,
|
||||
onToggleDiff,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<h2
|
||||
className="min-w-0 shrink truncate text-sm font-medium text-foreground"
|
||||
title={activeThreadTitle}
|
||||
>
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && (
|
||||
<Badge variant="outline" className="min-w-0 shrink truncate">
|
||||
{activeProjectName}
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isGitRepo && (
|
||||
<Badge variant="outline" className="shrink-0 text-[10px] text-amber-700">
|
||||
No Git
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center justify-end gap-2 @sm/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
keybindings={keybindings}
|
||||
preferredScriptId={preferredScriptId}
|
||||
onRunScript={onRunProjectScript}
|
||||
onAddScript={onAddProjectScript}
|
||||
onUpdateScript={onUpdateProjectScript}
|
||||
onDeleteScript={onDeleteProjectScript}
|
||||
/>
|
||||
)}
|
||||
{activeProjectName && (
|
||||
<OpenInPicker
|
||||
keybindings={keybindings}
|
||||
availableEditors={availableEditors}
|
||||
openInCwd={openInCwd}
|
||||
/>
|
||||
)}
|
||||
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={diffOpen}
|
||||
onPressedChange={onToggleDiff}
|
||||
aria-label="Toggle diff panel"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!isGitRepo}
|
||||
>
|
||||
<DiffIcon className="size-3" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{!isGitRepo
|
||||
? "Diff panel is unavailable because this project is not a git repository."
|
||||
: diffToggleShortcutLabel
|
||||
? `Toggle diff panel (${diffToggleShortcutLabel})`
|
||||
: "Toggle diff panel"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import "../../index.css";
|
||||
|
||||
import type { ProviderReasoningEffort } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { ProviderTraitsPicker } from "./CodexTraitsPicker";
|
||||
|
||||
async function mountPicker(props: {
|
||||
effort: ProviderReasoningEffort;
|
||||
supportsFastMode: boolean;
|
||||
fastModeEnabled: boolean;
|
||||
}) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onEffortChange = vi.fn();
|
||||
const onFastModeChange = vi.fn();
|
||||
const screen = await render(
|
||||
<ProviderTraitsPicker
|
||||
provider="claudeAgent"
|
||||
effort={props.effort}
|
||||
supportsFastMode={props.supportsFastMode}
|
||||
fastModeEnabled={props.fastModeEnabled}
|
||||
options={["low", "medium", "high", "max", "ultrathink"]}
|
||||
onEffortChange={onEffortChange}
|
||||
onFastModeChange={onFastModeChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
onEffortChange,
|
||||
onFastModeChange,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProviderTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("shows fast mode controls for claude", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
supportsFastMode: true,
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows Fast in the trigger label when claude fast mode is active", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
supportsFastMode: true,
|
||||
fastModeEnabled: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("High · Fast");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-opus claude models", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
supportsFastMode: false,
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { type ProviderKind, type ProviderReasoningEffort } from "@t3tools/contracts";
|
||||
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
function effortLabel(provider: ProviderKind, effort: ProviderReasoningEffort): string {
|
||||
if (provider === "codex") {
|
||||
const codexLabels: Record<string, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
return codexLabels[effort] ?? effort;
|
||||
}
|
||||
|
||||
const claudeLabels: Record<string, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
};
|
||||
return claudeLabels[effort] ?? effort;
|
||||
}
|
||||
|
||||
export const ProviderTraitsPicker = memo(function ProviderTraitsPicker(props: {
|
||||
provider: ProviderKind;
|
||||
effort: ProviderReasoningEffort;
|
||||
supportsFastMode?: boolean;
|
||||
fastModeEnabled?: boolean;
|
||||
options: ReadonlyArray<ProviderReasoningEffort>;
|
||||
onEffortChange: (effort: ProviderReasoningEffort) => void;
|
||||
onFastModeChange?: (enabled: boolean) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(props.provider);
|
||||
const triggerLabel = [
|
||||
effortLabel(props.provider, props.effort),
|
||||
...(props.supportsFastMode && props.fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
{props.provider === "codex" ? "Reasoning" : "Effort"}
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={props.effort}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextEffort = props.options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
props.onEffortChange(nextEffort);
|
||||
}}
|
||||
>
|
||||
{props.options.map((effort) => (
|
||||
<MenuRadioItem key={effort} value={effort}>
|
||||
{effortLabel(props.provider, effort)}
|
||||
{effort === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
{props.supportsFastMode && props.onFastModeChange ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={props.fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
props.onFastModeChange?.(value === "on");
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,75 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
|
||||
async function mountMenu(supportsFastMode = true) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={false}
|
||||
interactionMode="default"
|
||||
planSidebarOpen={false}
|
||||
runtimeMode="approval-required"
|
||||
selectedEffort="high"
|
||||
selectedProvider="claudeAgent"
|
||||
supportsFastMode={supportsFastMode}
|
||||
selectedFastModeEnabled={false}
|
||||
reasoningOptions={["low", "medium", "high", "max", "ultrathink"]}
|
||||
onEffortSelect={vi.fn()}
|
||||
onFastModeChange={vi.fn()}
|
||||
onToggleInteractionMode={vi.fn()}
|
||||
onTogglePlanSidebar={vi.fn()}
|
||||
onToggleRuntimeMode={vi.fn()}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CompactComposerControlsMenu", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("shows fast mode controls for claude", async () => {
|
||||
const mounted = await mountMenu();
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-opus claude models", async () => {
|
||||
const mounted = await mountMenu(false);
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import {
|
||||
type ProviderKind,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
type ProviderReasoningEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import { getDefaultReasoningEffort } from "@t3tools/shared/model";
|
||||
import { memo } from "react";
|
||||
import { EllipsisIcon, ListTodoIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
export const CompactComposerControlsMenu = memo(function CompactComposerControlsMenu(props: {
|
||||
activePlan: boolean;
|
||||
interactionMode: ProviderInteractionMode;
|
||||
planSidebarOpen: boolean;
|
||||
runtimeMode: RuntimeMode;
|
||||
selectedEffort: ProviderReasoningEffort | null;
|
||||
selectedProvider: ProviderKind;
|
||||
supportsFastMode: boolean;
|
||||
selectedFastModeEnabled: boolean;
|
||||
reasoningOptions: ReadonlyArray<ProviderReasoningEffort>;
|
||||
onEffortSelect: (effort: ProviderReasoningEffort) => void;
|
||||
onFastModeChange: (enabled: boolean) => void;
|
||||
onToggleInteractionMode: () => void;
|
||||
onTogglePlanSidebar: () => void;
|
||||
onToggleRuntimeMode: () => void;
|
||||
}) {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(props.selectedProvider);
|
||||
const reasoningLabelByOption: Record<ProviderReasoningEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
};
|
||||
|
||||
return (
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0 px-2 text-muted-foreground/70 hover:text-foreground/80"
|
||||
aria-label="More composer controls"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<EllipsisIcon aria-hidden="true" className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{props.selectedEffort != null ? (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
{props.selectedProvider === "codex" ? "Reasoning" : "Effort"}
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selectedEffort}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextEffort = props.reasoningOptions.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
props.onEffortSelect(nextEffort);
|
||||
}}
|
||||
>
|
||||
{props.reasoningOptions.map((effort) => (
|
||||
<MenuRadioItem key={effort} value={effort}>
|
||||
{reasoningLabelByOption[effort]}
|
||||
{effort === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
{props.supportsFastMode ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Fast Mode
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={props.selectedFastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
props.onFastModeChange(value === "on");
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
</>
|
||||
) : (
|
||||
<MenuDivider />
|
||||
)}
|
||||
</>
|
||||
) : null}
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={props.interactionMode}
|
||||
onValueChange={(value) => {
|
||||
if (!value || value === props.interactionMode) return;
|
||||
props.onToggleInteractionMode();
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="default">Chat</MenuRadioItem>
|
||||
<MenuRadioItem value="plan">Plan</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Access</div>
|
||||
<MenuRadioGroup
|
||||
value={props.runtimeMode}
|
||||
onValueChange={(value) => {
|
||||
if (!value || value === props.runtimeMode) return;
|
||||
props.onToggleRuntimeMode();
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="approval-required">Supervised</MenuRadioItem>
|
||||
<MenuRadioItem value="full-access">Full access</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
{props.activePlan ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuItem onClick={props.onTogglePlanSidebar}>
|
||||
<ListTodoIcon className="size-4 shrink-0" />
|
||||
{props.planSidebarOpen ? "Hide plan sidebar" : "Show plan sidebar"}
|
||||
</MenuItem>
|
||||
</>
|
||||
) : null}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
import { type ProjectEntry, type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { BotIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Command, CommandItem, CommandList } from "../ui/command";
|
||||
import { VscodeEntryIcon } from "./VscodeEntryIcon";
|
||||
|
||||
export type ComposerCommandItem =
|
||||
| {
|
||||
id: string;
|
||||
type: "path";
|
||||
path: string;
|
||||
pathKind: ProjectEntry["kind"];
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "slash-command";
|
||||
command: ComposerSlashCommand;
|
||||
label: string;
|
||||
description: string;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
type: "model";
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
items: ComposerCommandItem[];
|
||||
resolvedTheme: "light" | "dark";
|
||||
isLoading: boolean;
|
||||
triggerKind: ComposerTriggerKind | null;
|
||||
activeItemId: string | null;
|
||||
onHighlightedItemChange: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
return (
|
||||
<Command
|
||||
mode="none"
|
||||
onItemHighlighted={(highlightedValue) => {
|
||||
props.onHighlightedItemChange(
|
||||
typeof highlightedValue === "string" ? highlightedValue : null,
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
|
||||
<CommandList className="max-h-64">
|
||||
{props.items.map((item) => (
|
||||
<ComposerCommandMenuItem
|
||||
key={item.id}
|
||||
item={item}
|
||||
resolvedTheme={props.resolvedTheme}
|
||||
isActive={props.activeItemId === item.id}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
))}
|
||||
</CommandList>
|
||||
{props.items.length === 0 && (
|
||||
<p className="px-3 py-2 text-muted-foreground/70 text-xs">
|
||||
{props.isLoading
|
||||
? "Searching workspace files..."
|
||||
: props.triggerKind === "path"
|
||||
? "No matching files or folders."
|
||||
: "No matching command."}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</Command>
|
||||
);
|
||||
});
|
||||
|
||||
const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
item: ComposerCommandItem;
|
||||
resolvedTheme: "light" | "dark";
|
||||
isActive: boolean;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.id}
|
||||
className={cn(
|
||||
"cursor-pointer select-none gap-2",
|
||||
props.isActive && "bg-accent text-accent-foreground",
|
||||
)}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
onClick={() => {
|
||||
props.onSelect(props.item);
|
||||
}}
|
||||
>
|
||||
{props.item.type === "path" ? (
|
||||
<VscodeEntryIcon
|
||||
pathValue={props.item.path}
|
||||
kind={props.item.pathKind}
|
||||
theme={props.resolvedTheme}
|
||||
/>
|
||||
) : null}
|
||||
{props.item.type === "slash-command" ? (
|
||||
<BotIcon className="size-4 text-muted-foreground/80" />
|
||||
) : null}
|
||||
{props.item.type === "model" ? (
|
||||
<Badge variant="outline" className="px-1.5 py-0 text-[10px]">
|
||||
model
|
||||
</Badge>
|
||||
) : null}
|
||||
<span className="flex min-w-0 items-center gap-1.5 truncate">
|
||||
<span className="truncate">{props.item.label}</span>
|
||||
</span>
|
||||
<span className="truncate text-muted-foreground/70 text-xs">{props.item.description}</span>
|
||||
</CommandItem>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,55 @@
|
||||
import { type ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Button } from "../ui/button";
|
||||
|
||||
interface ComposerPendingApprovalActionsProps {
|
||||
requestId: ApprovalRequestId;
|
||||
isResponding: boolean;
|
||||
onRespondToApproval: (
|
||||
requestId: ApprovalRequestId,
|
||||
decision: ProviderApprovalDecision,
|
||||
) => Promise<void>;
|
||||
}
|
||||
|
||||
export const ComposerPendingApprovalActions = memo(function ComposerPendingApprovalActions({
|
||||
requestId,
|
||||
isResponding,
|
||||
onRespondToApproval,
|
||||
}: ComposerPendingApprovalActionsProps) {
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(requestId, "cancel")}
|
||||
>
|
||||
Cancel turn
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="destructive-outline"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(requestId, "decline")}
|
||||
>
|
||||
Decline
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(requestId, "acceptForSession")}
|
||||
>
|
||||
Always allow this session
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
disabled={isResponding}
|
||||
onClick={() => void onRespondToApproval(requestId, "accept")}
|
||||
>
|
||||
Approve once
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import { memo } from "react";
|
||||
import { type PendingApproval } from "../../session-logic";
|
||||
|
||||
interface ComposerPendingApprovalPanelProps {
|
||||
approval: PendingApproval;
|
||||
pendingCount: number;
|
||||
}
|
||||
|
||||
export const ComposerPendingApprovalPanel = memo(function ComposerPendingApprovalPanel({
|
||||
approval,
|
||||
pendingCount,
|
||||
}: ComposerPendingApprovalPanelProps) {
|
||||
const approvalSummary =
|
||||
approval.requestKind === "command"
|
||||
? "Command approval requested"
|
||||
: approval.requestKind === "file-read"
|
||||
? "File-read approval requested"
|
||||
: "File-change approval requested";
|
||||
|
||||
return (
|
||||
<div className="px-4 py-3.5 sm:px-5 sm:py-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="uppercase text-sm tracking-[0.2em]">PENDING APPROVAL</span>
|
||||
<span className="text-sm font-medium">{approvalSummary}</span>
|
||||
{pendingCount > 1 ? (
|
||||
<span className="text-xs text-muted-foreground">1/{pendingCount}</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { type ApprovalRequestId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useRef } from "react";
|
||||
import { type PendingUserInput } from "../../session-logic";
|
||||
import {
|
||||
derivePendingUserInputProgress,
|
||||
type PendingUserInputDraftAnswer,
|
||||
} from "../../pendingUserInput";
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface PendingUserInputPanelProps {
|
||||
pendingUserInputs: PendingUserInput[];
|
||||
respondingRequestIds: ApprovalRequestId[];
|
||||
answers: Record<string, PendingUserInputDraftAnswer>;
|
||||
questionIndex: number;
|
||||
onSelectOption: (questionId: string, optionLabel: string) => void;
|
||||
onAdvance: () => void;
|
||||
}
|
||||
|
||||
export const ComposerPendingUserInputPanel = memo(function ComposerPendingUserInputPanel({
|
||||
pendingUserInputs,
|
||||
respondingRequestIds,
|
||||
answers,
|
||||
questionIndex,
|
||||
onSelectOption,
|
||||
onAdvance,
|
||||
}: PendingUserInputPanelProps) {
|
||||
if (pendingUserInputs.length === 0) return null;
|
||||
const activePrompt = pendingUserInputs[0];
|
||||
if (!activePrompt) return null;
|
||||
|
||||
return (
|
||||
<ComposerPendingUserInputCard
|
||||
key={activePrompt.requestId}
|
||||
prompt={activePrompt}
|
||||
isResponding={respondingRequestIds.includes(activePrompt.requestId)}
|
||||
answers={answers}
|
||||
questionIndex={questionIndex}
|
||||
onSelectOption={onSelectOption}
|
||||
onAdvance={onAdvance}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const ComposerPendingUserInputCard = memo(function ComposerPendingUserInputCard({
|
||||
prompt,
|
||||
isResponding,
|
||||
answers,
|
||||
questionIndex,
|
||||
onSelectOption,
|
||||
onAdvance,
|
||||
}: {
|
||||
prompt: PendingUserInput;
|
||||
isResponding: boolean;
|
||||
answers: Record<string, PendingUserInputDraftAnswer>;
|
||||
questionIndex: number;
|
||||
onSelectOption: (questionId: string, optionLabel: string) => void;
|
||||
onAdvance: () => void;
|
||||
}) {
|
||||
const progress = derivePendingUserInputProgress(prompt.questions, answers, questionIndex);
|
||||
const activeQuestion = progress.activeQuestion;
|
||||
const autoAdvanceTimerRef = useRef<number | null>(null);
|
||||
|
||||
// Clear auto-advance timer on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (autoAdvanceTimerRef.current !== null) {
|
||||
window.clearTimeout(autoAdvanceTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const selectOptionAndAutoAdvance = useCallback(
|
||||
(questionId: string, optionLabel: string) => {
|
||||
onSelectOption(questionId, optionLabel);
|
||||
if (autoAdvanceTimerRef.current !== null) {
|
||||
window.clearTimeout(autoAdvanceTimerRef.current);
|
||||
}
|
||||
autoAdvanceTimerRef.current = window.setTimeout(() => {
|
||||
autoAdvanceTimerRef.current = null;
|
||||
onAdvance();
|
||||
}, 200);
|
||||
},
|
||||
[onSelectOption, onAdvance],
|
||||
);
|
||||
|
||||
// Keyboard shortcut: number keys 1-9 select corresponding option and auto-advance.
|
||||
// Works even when the Lexical composer (contenteditable) has focus — the composer
|
||||
// doubles as a custom-answer field during user input, and when it's empty the digit
|
||||
// keys should pick options instead of typing into the editor.
|
||||
useEffect(() => {
|
||||
if (!activeQuestion || isResponding) return;
|
||||
const handler = (event: globalThis.KeyboardEvent) => {
|
||||
if (event.metaKey || event.ctrlKey || event.altKey) return;
|
||||
const target = event.target;
|
||||
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
|
||||
return;
|
||||
}
|
||||
// If the user has started typing a custom answer in the contenteditable
|
||||
// composer, let digit keys pass through so they can type numbers.
|
||||
if (target instanceof HTMLElement && target.isContentEditable) {
|
||||
const hasCustomText = progress.customAnswer.length > 0;
|
||||
if (hasCustomText) return;
|
||||
}
|
||||
const digit = Number.parseInt(event.key, 10);
|
||||
if (Number.isNaN(digit) || digit < 1 || digit > 9) return;
|
||||
const optionIndex = digit - 1;
|
||||
if (optionIndex >= activeQuestion.options.length) return;
|
||||
const option = activeQuestion.options[optionIndex];
|
||||
if (!option) return;
|
||||
event.preventDefault();
|
||||
selectOptionAndAutoAdvance(activeQuestion.id, option.label);
|
||||
};
|
||||
document.addEventListener("keydown", handler);
|
||||
return () => document.removeEventListener("keydown", handler);
|
||||
}, [activeQuestion, isResponding, selectOptionAndAutoAdvance, progress.customAnswer.length]);
|
||||
|
||||
if (!activeQuestion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="px-4 py-3 sm:px-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex items-center gap-2">
|
||||
{prompt.questions.length > 1 ? (
|
||||
<span className="flex h-5 items-center rounded-md bg-muted/60 px-1.5 text-[10px] font-medium tabular-nums text-muted-foreground/60">
|
||||
{questionIndex + 1}/{prompt.questions.length}
|
||||
</span>
|
||||
) : null}
|
||||
<span className="text-[11px] font-semibold tracking-widest text-muted-foreground/50 uppercase">
|
||||
{activeQuestion.header}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<p className="mt-1.5 text-sm text-foreground/90">{activeQuestion.question}</p>
|
||||
<div className="mt-3 space-y-1">
|
||||
{activeQuestion.options.map((option, index) => {
|
||||
const isSelected = progress.selectedOptionLabel === option.label;
|
||||
const shortcutKey = index < 9 ? index + 1 : null;
|
||||
return (
|
||||
<button
|
||||
key={`${activeQuestion.id}:${option.label}`}
|
||||
type="button"
|
||||
disabled={isResponding}
|
||||
onClick={() => selectOptionAndAutoAdvance(activeQuestion.id, option.label)}
|
||||
className={cn(
|
||||
"group flex w-full items-center gap-3 rounded-lg border px-3 py-2 text-left transition-all duration-150",
|
||||
isSelected
|
||||
? "border-blue-500/40 bg-blue-500/8 text-foreground"
|
||||
: "border-transparent bg-muted/20 text-foreground/80 hover:bg-muted/40 hover:border-border/40",
|
||||
isResponding && "opacity-50 cursor-not-allowed",
|
||||
)}
|
||||
>
|
||||
{shortcutKey !== null ? (
|
||||
<kbd
|
||||
className={cn(
|
||||
"flex size-5 shrink-0 items-center justify-center rounded text-[11px] font-medium tabular-nums transition-colors duration-150",
|
||||
isSelected
|
||||
? "bg-blue-500/20 text-blue-400"
|
||||
: "bg-muted/40 text-muted-foreground/50 group-hover:bg-muted/60 group-hover:text-muted-foreground/70",
|
||||
)}
|
||||
>
|
||||
{shortcutKey}
|
||||
</kbd>
|
||||
) : null}
|
||||
<div className="min-w-0 flex-1">
|
||||
<span className="text-sm font-medium">{option.label}</span>
|
||||
{option.description && option.description !== option.label ? (
|
||||
<span className="ml-2 text-xs text-muted-foreground/50">
|
||||
{option.description}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
{isSelected ? <CheckIcon className="size-3.5 shrink-0 text-blue-400" /> : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { memo } from "react";
|
||||
|
||||
export const ComposerPlanFollowUpBanner = memo(function ComposerPlanFollowUpBanner({
|
||||
planTitle,
|
||||
}: {
|
||||
planTitle: string | null;
|
||||
}) {
|
||||
return (
|
||||
<div className="px-4 py-3.5 sm:px-5 sm:py-4">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<span className="uppercase text-sm tracking-[0.2em]">Plan ready</span>
|
||||
{planTitle ? (
|
||||
<span className="min-w-0 flex-1 truncate text-sm font-medium">{planTitle}</span>
|
||||
) : null}
|
||||
</div>
|
||||
{/* <div className="mt-2 text-xs text-muted-foreground">
|
||||
Review the plan
|
||||
</div> */}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import { memo } from "react";
|
||||
|
||||
export function hasNonZeroStat(stat: { additions: number; deletions: number }): boolean {
|
||||
return stat.additions > 0 || stat.deletions > 0;
|
||||
}
|
||||
|
||||
export const DiffStatLabel = memo(function DiffStatLabel(props: {
|
||||
additions: number;
|
||||
deletions: number;
|
||||
showParentheses?: boolean;
|
||||
}) {
|
||||
const { additions, deletions, showParentheses = false } = props;
|
||||
return (
|
||||
<>
|
||||
{showParentheses && <span className="text-muted-foreground/70">(</span>}
|
||||
<span className="text-success">+{additions}</span>
|
||||
<span className="mx-0.5 text-muted-foreground/70">/</span>
|
||||
<span className="text-destructive">-{deletions}</span>
|
||||
{showParentheses && <span className="text-muted-foreground/70">)</span>}
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
export interface ExpandedImageItem {
|
||||
src: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ExpandedImagePreview {
|
||||
images: ExpandedImageItem[];
|
||||
index: number;
|
||||
}
|
||||
|
||||
export function buildExpandedImagePreview(
|
||||
images: ReadonlyArray<{ id: string; name: string; previewUrl?: string }>,
|
||||
selectedImageId: string,
|
||||
): ExpandedImagePreview | null {
|
||||
const previewableImages = images.flatMap((image) =>
|
||||
image.previewUrl ? [{ id: image.id, src: image.previewUrl, name: image.name }] : [],
|
||||
);
|
||||
if (previewableImages.length === 0) {
|
||||
return null;
|
||||
}
|
||||
const selectedIndex = previewableImages.findIndex((image) => image.id === selectedImageId);
|
||||
if (selectedIndex < 0) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
images: previewableImages.map((image) => ({
|
||||
src: image.src,
|
||||
name: image.name,
|
||||
})),
|
||||
index: selectedIndex,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { memo } from "react";
|
||||
import { CopyIcon, CheckIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
|
||||
export const MessageCopyButton = memo(function MessageCopyButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
|
||||
return (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => copyToClipboard(text)}
|
||||
title="Copy message"
|
||||
>
|
||||
{isCopied ? <CheckIcon className="size-3 text-success" /> : <CopyIcon className="size-3" />}
|
||||
</Button>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
|
||||
|
||||
describe("computeMessageDurationStart", () => {
|
||||
it("returns message createdAt when there is no preceding user message", () => {
|
||||
const result = computeMessageDurationStart([
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:00:05Z",
|
||||
completedAt: "2026-01-01T00:00:10Z",
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual(new Map([["a1", "2026-01-01T00:00:05Z"]]));
|
||||
});
|
||||
|
||||
it("uses the user message createdAt for the first assistant response", () => {
|
||||
const result = computeMessageDurationStart([
|
||||
{ id: "u1", role: "user", createdAt: "2026-01-01T00:00:00Z" },
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:00:30Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
new Map([
|
||||
["u1", "2026-01-01T00:00:00Z"],
|
||||
["a1", "2026-01-01T00:00:00Z"],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("uses the previous assistant completedAt for subsequent assistant responses", () => {
|
||||
const result = computeMessageDurationStart([
|
||||
{ id: "u1", role: "user", createdAt: "2026-01-01T00:00:00Z" },
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:00:30Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
},
|
||||
{
|
||||
id: "a2",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:00:55Z",
|
||||
completedAt: "2026-01-01T00:00:55Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
new Map([
|
||||
["u1", "2026-01-01T00:00:00Z"],
|
||||
["a1", "2026-01-01T00:00:00Z"],
|
||||
["a2", "2026-01-01T00:00:30Z"],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not advance the boundary for a streaming message without completedAt", () => {
|
||||
const result = computeMessageDurationStart([
|
||||
{ id: "u1", role: "user", createdAt: "2026-01-01T00:00:00Z" },
|
||||
{ id: "a1", role: "assistant", createdAt: "2026-01-01T00:00:30Z" },
|
||||
{
|
||||
id: "a2",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:00:55Z",
|
||||
completedAt: "2026-01-01T00:00:55Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
new Map([
|
||||
["u1", "2026-01-01T00:00:00Z"],
|
||||
["a1", "2026-01-01T00:00:00Z"],
|
||||
["a2", "2026-01-01T00:00:00Z"],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("resets the boundary on a new user message", () => {
|
||||
const result = computeMessageDurationStart([
|
||||
{ id: "u1", role: "user", createdAt: "2026-01-01T00:00:00Z" },
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:00:30Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
},
|
||||
{ id: "u2", role: "user", createdAt: "2026-01-01T00:01:00Z" },
|
||||
{
|
||||
id: "a2",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:01:20Z",
|
||||
completedAt: "2026-01-01T00:01:20Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
new Map([
|
||||
["u1", "2026-01-01T00:00:00Z"],
|
||||
["a1", "2026-01-01T00:00:00Z"],
|
||||
["u2", "2026-01-01T00:01:00Z"],
|
||||
["a2", "2026-01-01T00:01:00Z"],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("handles system messages without affecting the boundary", () => {
|
||||
const result = computeMessageDurationStart([
|
||||
{ id: "u1", role: "user", createdAt: "2026-01-01T00:00:00Z" },
|
||||
{ id: "s1", role: "system", createdAt: "2026-01-01T00:00:01Z" },
|
||||
{
|
||||
id: "a1",
|
||||
role: "assistant",
|
||||
createdAt: "2026-01-01T00:00:30Z",
|
||||
completedAt: "2026-01-01T00:00:30Z",
|
||||
},
|
||||
]);
|
||||
|
||||
expect(result).toEqual(
|
||||
new Map([
|
||||
["u1", "2026-01-01T00:00:00Z"],
|
||||
["s1", "2026-01-01T00:00:00Z"],
|
||||
["a1", "2026-01-01T00:00:00Z"],
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("returns empty map for empty input", () => {
|
||||
expect(computeMessageDurationStart([])).toEqual(new Map());
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCompactToolLabel", () => {
|
||||
it("removes trailing completion wording from command labels", () => {
|
||||
expect(normalizeCompactToolLabel("Ran command complete")).toBe("Ran command");
|
||||
});
|
||||
|
||||
it("removes trailing completion wording from other labels", () => {
|
||||
expect(normalizeCompactToolLabel("Read file completed")).toBe("Read file");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
export interface TimelineDurationMessage {
|
||||
id: string;
|
||||
role: "user" | "assistant" | "system";
|
||||
createdAt: string;
|
||||
completedAt?: string | undefined;
|
||||
}
|
||||
|
||||
export function computeMessageDurationStart(
|
||||
messages: ReadonlyArray<TimelineDurationMessage>,
|
||||
): Map<string, string> {
|
||||
const result = new Map<string, string>();
|
||||
let lastBoundary: string | null = null;
|
||||
|
||||
for (const message of messages) {
|
||||
if (message.role === "user") {
|
||||
lastBoundary = message.createdAt;
|
||||
}
|
||||
result.set(message.id, lastBoundary ?? message.createdAt);
|
||||
if (message.role === "assistant" && message.completedAt) {
|
||||
lastBoundary = message.completedAt;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export function normalizeCompactToolLabel(value: string): string {
|
||||
return value.replace(/\s+(?:complete|completed)\s*$/i, "").trim();
|
||||
}
|
||||
@@ -0,0 +1,783 @@
|
||||
import { type MessageId, type TurnId } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
measureElement as measureVirtualElement,
|
||||
type VirtualItem,
|
||||
useVirtualizer,
|
||||
} from "@tanstack/react-virtual";
|
||||
import { deriveTimelineEntries, formatElapsed } from "../../session-logic";
|
||||
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX } from "../../chat-scroll";
|
||||
import { type TurnDiffSummary } from "../../types";
|
||||
import { summarizeTurnDiffStats } from "../../lib/turnDiffTree";
|
||||
import ChatMarkdown from "../ChatMarkdown";
|
||||
import {
|
||||
BotIcon,
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
EyeIcon,
|
||||
GlobeIcon,
|
||||
HammerIcon,
|
||||
type LucideIcon,
|
||||
SquarePenIcon,
|
||||
TerminalIcon,
|
||||
Undo2Icon,
|
||||
WrenchIcon,
|
||||
ZapIcon,
|
||||
} from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { clamp } from "effect/Number";
|
||||
import { estimateTimelineMessageHeight } from "../timelineHeight";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./ExpandedImagePreview";
|
||||
import { ProposedPlanCard } from "./ProposedPlanCard";
|
||||
import { ChangedFilesTree } from "./ChangedFilesTree";
|
||||
import { DiffStatLabel, hasNonZeroStat } from "./DiffStatLabel";
|
||||
import { MessageCopyButton } from "./MessageCopyButton";
|
||||
import { computeMessageDurationStart, normalizeCompactToolLabel } from "./MessagesTimeline.logic";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { type TimestampFormat } from "../../appSettings";
|
||||
import { formatTimestamp } from "../../timestampFormat";
|
||||
|
||||
const MAX_VISIBLE_WORK_LOG_ENTRIES = 6;
|
||||
const ALWAYS_UNVIRTUALIZED_TAIL_ROWS = 8;
|
||||
|
||||
interface MessagesTimelineProps {
|
||||
hasMessages: boolean;
|
||||
isWorking: boolean;
|
||||
activeTurnInProgress: boolean;
|
||||
activeTurnStartedAt: string | null;
|
||||
scrollContainer: HTMLDivElement | null;
|
||||
timelineEntries: ReturnType<typeof deriveTimelineEntries>;
|
||||
completionDividerBeforeEntryId: string | null;
|
||||
completionSummary: string | null;
|
||||
turnDiffSummaryByAssistantMessageId: Map<MessageId, TurnDiffSummary>;
|
||||
nowIso: string;
|
||||
expandedWorkGroups: Record<string, boolean>;
|
||||
onToggleWorkGroup: (groupId: string) => void;
|
||||
onOpenTurnDiff: (turnId: TurnId, filePath?: string) => void;
|
||||
revertTurnCountByUserMessageId: Map<MessageId, number>;
|
||||
onRevertUserMessage: (messageId: MessageId) => void;
|
||||
isRevertingCheckpoint: boolean;
|
||||
onImageExpand: (preview: ExpandedImagePreview) => void;
|
||||
markdownCwd: string | undefined;
|
||||
resolvedTheme: "light" | "dark";
|
||||
timestampFormat: TimestampFormat;
|
||||
workspaceRoot: string | undefined;
|
||||
}
|
||||
|
||||
export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
hasMessages,
|
||||
isWorking,
|
||||
activeTurnInProgress,
|
||||
activeTurnStartedAt,
|
||||
scrollContainer,
|
||||
timelineEntries,
|
||||
completionDividerBeforeEntryId,
|
||||
completionSummary,
|
||||
turnDiffSummaryByAssistantMessageId,
|
||||
nowIso,
|
||||
expandedWorkGroups,
|
||||
onToggleWorkGroup,
|
||||
onOpenTurnDiff,
|
||||
revertTurnCountByUserMessageId,
|
||||
onRevertUserMessage,
|
||||
isRevertingCheckpoint,
|
||||
onImageExpand,
|
||||
markdownCwd,
|
||||
resolvedTheme,
|
||||
timestampFormat,
|
||||
workspaceRoot,
|
||||
}: MessagesTimelineProps) {
|
||||
const timelineRootRef = useRef<HTMLDivElement | null>(null);
|
||||
const [timelineWidthPx, setTimelineWidthPx] = useState<number | null>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const timelineRoot = timelineRootRef.current;
|
||||
if (!timelineRoot) return;
|
||||
|
||||
const updateWidth = (nextWidth: number) => {
|
||||
setTimelineWidthPx((previousWidth) => {
|
||||
if (previousWidth !== null && Math.abs(previousWidth - nextWidth) < 0.5) {
|
||||
return previousWidth;
|
||||
}
|
||||
return nextWidth;
|
||||
});
|
||||
};
|
||||
|
||||
updateWidth(timelineRoot.getBoundingClientRect().width);
|
||||
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const observer = new ResizeObserver(() => {
|
||||
updateWidth(timelineRoot.getBoundingClientRect().width);
|
||||
});
|
||||
observer.observe(timelineRoot);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, [hasMessages, isWorking]);
|
||||
|
||||
const rows = useMemo<TimelineRow[]>(() => {
|
||||
const nextRows: TimelineRow[] = [];
|
||||
const durationStartByMessageId = computeMessageDurationStart(
|
||||
timelineEntries.flatMap((entry) => (entry.kind === "message" ? [entry.message] : [])),
|
||||
);
|
||||
|
||||
for (let index = 0; index < timelineEntries.length; index += 1) {
|
||||
const timelineEntry = timelineEntries[index];
|
||||
if (!timelineEntry) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "work") {
|
||||
const groupedEntries = [timelineEntry.entry];
|
||||
let cursor = index + 1;
|
||||
while (cursor < timelineEntries.length) {
|
||||
const nextEntry = timelineEntries[cursor];
|
||||
if (!nextEntry || nextEntry.kind !== "work") break;
|
||||
groupedEntries.push(nextEntry.entry);
|
||||
cursor += 1;
|
||||
}
|
||||
nextRows.push({
|
||||
kind: "work",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
groupedEntries,
|
||||
});
|
||||
index = cursor - 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (timelineEntry.kind === "proposed-plan") {
|
||||
nextRows.push({
|
||||
kind: "proposed-plan",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
proposedPlan: timelineEntry.proposedPlan,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
nextRows.push({
|
||||
kind: "message",
|
||||
id: timelineEntry.id,
|
||||
createdAt: timelineEntry.createdAt,
|
||||
message: timelineEntry.message,
|
||||
durationStart:
|
||||
durationStartByMessageId.get(timelineEntry.message.id) ?? timelineEntry.message.createdAt,
|
||||
showCompletionDivider:
|
||||
timelineEntry.message.role === "assistant" &&
|
||||
completionDividerBeforeEntryId === timelineEntry.id,
|
||||
});
|
||||
}
|
||||
|
||||
if (isWorking) {
|
||||
nextRows.push({
|
||||
kind: "working",
|
||||
id: "working-indicator-row",
|
||||
createdAt: activeTurnStartedAt,
|
||||
});
|
||||
}
|
||||
|
||||
return nextRows;
|
||||
}, [timelineEntries, completionDividerBeforeEntryId, isWorking, activeTurnStartedAt]);
|
||||
|
||||
const firstUnvirtualizedRowIndex = useMemo(() => {
|
||||
const firstTailRowIndex = Math.max(rows.length - ALWAYS_UNVIRTUALIZED_TAIL_ROWS, 0);
|
||||
if (!activeTurnInProgress) return firstTailRowIndex;
|
||||
|
||||
const turnStartedAtMs =
|
||||
typeof activeTurnStartedAt === "string" ? Date.parse(activeTurnStartedAt) : Number.NaN;
|
||||
let firstCurrentTurnRowIndex = -1;
|
||||
if (!Number.isNaN(turnStartedAtMs)) {
|
||||
firstCurrentTurnRowIndex = rows.findIndex((row) => {
|
||||
if (row.kind === "working") return true;
|
||||
if (!row.createdAt) return false;
|
||||
const rowCreatedAtMs = Date.parse(row.createdAt);
|
||||
return !Number.isNaN(rowCreatedAtMs) && rowCreatedAtMs >= turnStartedAtMs;
|
||||
});
|
||||
}
|
||||
|
||||
if (firstCurrentTurnRowIndex < 0) {
|
||||
firstCurrentTurnRowIndex = rows.findIndex(
|
||||
(row) => row.kind === "message" && row.message.streaming,
|
||||
);
|
||||
}
|
||||
|
||||
if (firstCurrentTurnRowIndex < 0) return firstTailRowIndex;
|
||||
|
||||
for (let index = firstCurrentTurnRowIndex - 1; index >= 0; index -= 1) {
|
||||
const previousRow = rows[index];
|
||||
if (!previousRow || previousRow.kind !== "message") continue;
|
||||
if (previousRow.message.role === "user") {
|
||||
return Math.min(index, firstTailRowIndex);
|
||||
}
|
||||
if (previousRow.message.role === "assistant" && !previousRow.message.streaming) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return Math.min(firstCurrentTurnRowIndex, firstTailRowIndex);
|
||||
}, [activeTurnInProgress, activeTurnStartedAt, rows]);
|
||||
|
||||
const virtualizedRowCount = clamp(firstUnvirtualizedRowIndex, {
|
||||
minimum: 0,
|
||||
maximum: rows.length,
|
||||
});
|
||||
|
||||
const rowVirtualizer = useVirtualizer({
|
||||
count: virtualizedRowCount,
|
||||
getScrollElement: () => scrollContainer,
|
||||
// Use stable row ids so virtual measurements do not leak across thread switches.
|
||||
getItemKey: (index: number) => rows[index]?.id ?? index,
|
||||
estimateSize: (index: number) => {
|
||||
const row = rows[index];
|
||||
if (!row) return 96;
|
||||
if (row.kind === "work") return 112;
|
||||
if (row.kind === "proposed-plan") return estimateTimelineProposedPlanHeight(row.proposedPlan);
|
||||
if (row.kind === "working") return 40;
|
||||
return estimateTimelineMessageHeight(row.message, { timelineWidthPx });
|
||||
},
|
||||
measureElement: measureVirtualElement,
|
||||
useAnimationFrameWithResizeObserver: true,
|
||||
overscan: 8,
|
||||
});
|
||||
useEffect(() => {
|
||||
if (timelineWidthPx === null) return;
|
||||
rowVirtualizer.measure();
|
||||
}, [rowVirtualizer, timelineWidthPx]);
|
||||
useEffect(() => {
|
||||
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
|
||||
const viewportHeight = instance.scrollRect?.height ?? 0;
|
||||
const scrollOffset = instance.scrollOffset ?? 0;
|
||||
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
|
||||
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
|
||||
};
|
||||
return () => {
|
||||
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = undefined;
|
||||
};
|
||||
}, [rowVirtualizer]);
|
||||
const pendingMeasureFrameRef = useRef<number | null>(null);
|
||||
const onTimelineImageLoad = useCallback(() => {
|
||||
if (pendingMeasureFrameRef.current !== null) return;
|
||||
pendingMeasureFrameRef.current = window.requestAnimationFrame(() => {
|
||||
pendingMeasureFrameRef.current = null;
|
||||
rowVirtualizer.measure();
|
||||
});
|
||||
}, [rowVirtualizer]);
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
const frame = pendingMeasureFrameRef.current;
|
||||
if (frame !== null) {
|
||||
window.cancelAnimationFrame(frame);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const virtualRows = rowVirtualizer.getVirtualItems();
|
||||
const nonVirtualizedRows = rows.slice(virtualizedRowCount);
|
||||
const [allDirectoriesExpandedByTurnId, setAllDirectoriesExpandedByTurnId] = useState<
|
||||
Record<string, boolean>
|
||||
>({});
|
||||
const onToggleAllDirectories = useCallback((turnId: TurnId) => {
|
||||
setAllDirectoriesExpandedByTurnId((current) => ({
|
||||
...current,
|
||||
[turnId]: !(current[turnId] ?? true),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
const renderRowContent = (row: TimelineRow) => (
|
||||
<div
|
||||
className="pb-4"
|
||||
data-timeline-row-kind={row.kind}
|
||||
data-message-id={row.kind === "message" ? row.message.id : undefined}
|
||||
data-message-role={row.kind === "message" ? row.message.role : undefined}
|
||||
>
|
||||
{row.kind === "work" &&
|
||||
(() => {
|
||||
const groupId = row.id;
|
||||
const groupedEntries = row.groupedEntries;
|
||||
const isExpanded = expandedWorkGroups[groupId] ?? false;
|
||||
const hasOverflow = groupedEntries.length > MAX_VISIBLE_WORK_LOG_ENTRIES;
|
||||
const visibleEntries =
|
||||
hasOverflow && !isExpanded
|
||||
? groupedEntries.slice(-MAX_VISIBLE_WORK_LOG_ENTRIES)
|
||||
: groupedEntries;
|
||||
const hiddenCount = groupedEntries.length - visibleEntries.length;
|
||||
const onlyToolEntries = groupedEntries.every((entry) => entry.tone === "tool");
|
||||
const showHeader = hasOverflow || !onlyToolEntries;
|
||||
const groupLabel = onlyToolEntries ? "Tool calls" : "Work log";
|
||||
|
||||
return (
|
||||
<div className="rounded-xl border border-border/45 bg-card/25 px-2 py-1.5">
|
||||
{showHeader && (
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2 px-0.5">
|
||||
<p className="text-[9px] uppercase tracking-[0.16em] text-muted-foreground/55">
|
||||
{groupLabel} ({groupedEntries.length})
|
||||
</p>
|
||||
{hasOverflow && (
|
||||
<button
|
||||
type="button"
|
||||
className="text-[9px] uppercase tracking-[0.12em] text-muted-foreground/55 transition-colors duration-150 hover:text-foreground/75"
|
||||
onClick={() => onToggleWorkGroup(groupId)}
|
||||
>
|
||||
{isExpanded ? "Show less" : `Show ${hiddenCount} more`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="space-y-0.5">
|
||||
{visibleEntries.map((workEntry) => (
|
||||
<SimpleWorkEntryRow key={`work-row:${workEntry.id}`} workEntry={workEntry} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "message" &&
|
||||
row.message.role === "user" &&
|
||||
(() => {
|
||||
const userImages = row.message.attachments ?? [];
|
||||
const canRevertAgentWork = revertTurnCountByUserMessageId.has(row.message.id);
|
||||
return (
|
||||
<div className="flex justify-end">
|
||||
<div className="group relative max-w-[80%] rounded-2xl rounded-br-sm border border-border bg-secondary px-4 py-3">
|
||||
{userImages.length > 0 && (
|
||||
<div className="mb-2 grid max-w-[420px] grid-cols-2 gap-2">
|
||||
{userImages.map(
|
||||
(image: NonNullable<TimelineMessage["attachments"]>[number]) => (
|
||||
<div
|
||||
key={image.id}
|
||||
className="overflow-hidden rounded-lg border border-border/80 bg-background/70"
|
||||
>
|
||||
{image.previewUrl ? (
|
||||
<button
|
||||
type="button"
|
||||
className="h-full w-full cursor-zoom-in"
|
||||
aria-label={`Preview ${image.name}`}
|
||||
onClick={() => {
|
||||
const preview = buildExpandedImagePreview(userImages, image.id);
|
||||
if (!preview) return;
|
||||
onImageExpand(preview);
|
||||
}}
|
||||
>
|
||||
<img
|
||||
src={image.previewUrl}
|
||||
alt={image.name}
|
||||
className="h-full max-h-[220px] w-full object-cover"
|
||||
onLoad={onTimelineImageLoad}
|
||||
onError={onTimelineImageLoad}
|
||||
/>
|
||||
</button>
|
||||
) : (
|
||||
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
|
||||
{image.name}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{row.message.text && (
|
||||
<pre className="whitespace-pre-wrap wrap-break-word font-mono text-sm leading-relaxed text-foreground">
|
||||
{row.message.text}
|
||||
</pre>
|
||||
)}
|
||||
<div className="mt-1.5 flex items-center justify-end gap-2">
|
||||
<div className="flex items-center gap-1.5 opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover:opacity-100">
|
||||
{row.message.text && <MessageCopyButton text={row.message.text} />}
|
||||
{canRevertAgentWork && (
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={isRevertingCheckpoint || isWorking}
|
||||
onClick={() => onRevertUserMessage(row.message.id)}
|
||||
title="Revert to this message"
|
||||
>
|
||||
<Undo2Icon className="size-3" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-right text-[10px] text-muted-foreground/30">
|
||||
{formatTimestamp(row.message.createdAt, timestampFormat)}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "message" &&
|
||||
row.message.role === "assistant" &&
|
||||
(() => {
|
||||
const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");
|
||||
return (
|
||||
<>
|
||||
{row.showCompletionDivider && (
|
||||
<div className="my-3 flex items-center gap-3">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="rounded-full border border-border bg-background px-2.5 py-1 text-[10px] uppercase tracking-[0.14em] text-muted-foreground/80">
|
||||
{completionSummary ? `Response • ${completionSummary}` : "Response"}
|
||||
</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ChatMarkdown
|
||||
text={messageText}
|
||||
cwd={markdownCwd}
|
||||
isStreaming={Boolean(row.message.streaming)}
|
||||
/>
|
||||
{(() => {
|
||||
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
|
||||
if (!turnSummary) return null;
|
||||
const checkpointFiles = turnSummary.files;
|
||||
if (checkpointFiles.length === 0) return null;
|
||||
const summaryStat = summarizeTurnDiffStats(checkpointFiles);
|
||||
const changedFileCountLabel = String(checkpointFiles.length);
|
||||
const allDirectoriesExpanded =
|
||||
allDirectoriesExpandedByTurnId[turnSummary.turnId] ?? true;
|
||||
return (
|
||||
<div className="mt-2 rounded-lg border border-border/80 bg-card/45 p-2.5">
|
||||
<div className="mb-1.5 flex items-center justify-between gap-2">
|
||||
<p className="text-[10px] uppercase tracking-[0.12em] text-muted-foreground/65">
|
||||
<span>Changed files ({changedFileCountLabel})</span>
|
||||
{hasNonZeroStat(summaryStat) && (
|
||||
<>
|
||||
<span className="mx-1">•</span>
|
||||
<DiffStatLabel
|
||||
additions={summaryStat.additions}
|
||||
deletions={summaryStat.deletions}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
onClick={() =>
|
||||
onOpenTurnDiff(turnSummary.turnId, checkpointFiles[0]?.path)
|
||||
}
|
||||
>
|
||||
View diff
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<ChangedFilesTree
|
||||
key={`changed-files-tree:${turnSummary.turnId}`}
|
||||
turnId={turnSummary.turnId}
|
||||
files={checkpointFiles}
|
||||
allDirectoriesExpanded={allDirectoriesExpanded}
|
||||
resolvedTheme={resolvedTheme}
|
||||
onOpenTurnDiff={onOpenTurnDiff}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})()}
|
||||
<p className="mt-1.5 text-[10px] text-muted-foreground/30">
|
||||
{formatMessageMeta(
|
||||
row.message.createdAt,
|
||||
row.message.streaming
|
||||
? formatElapsed(row.durationStart, nowIso)
|
||||
: formatElapsed(row.durationStart, row.message.completedAt),
|
||||
timestampFormat,
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
})()}
|
||||
|
||||
{row.kind === "proposed-plan" && (
|
||||
<div className="min-w-0 px-1 py-0.5">
|
||||
<ProposedPlanCard
|
||||
planMarkdown={row.proposedPlan.planMarkdown}
|
||||
cwd={markdownCwd}
|
||||
workspaceRoot={workspaceRoot}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{row.kind === "working" && (
|
||||
<div className="py-0.5 pl-1.5">
|
||||
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70">
|
||||
<span className="inline-flex items-center gap-[3px]">
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:200ms]" />
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
<span>
|
||||
{row.createdAt
|
||||
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
|
||||
: "Working..."}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
if (!hasMessages && !isWorking) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground/30">
|
||||
Send a message to start the conversation.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={timelineRootRef}
|
||||
data-timeline-root="true"
|
||||
className="mx-auto w-full min-w-0 max-w-3xl overflow-x-hidden"
|
||||
>
|
||||
{virtualizedRowCount > 0 && (
|
||||
<div className="relative" style={{ height: `${rowVirtualizer.getTotalSize()}px` }}>
|
||||
{virtualRows.map((virtualRow: VirtualItem) => {
|
||||
const row = rows[virtualRow.index];
|
||||
if (!row) return null;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`virtual-row:${row.id}`}
|
||||
data-index={virtualRow.index}
|
||||
ref={rowVirtualizer.measureElement}
|
||||
className="absolute left-0 top-0 w-full"
|
||||
style={{ transform: `translateY(${virtualRow.start}px)` }}
|
||||
>
|
||||
{renderRowContent(row)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nonVirtualizedRows.map((row) => (
|
||||
<div key={`non-virtual-row:${row.id}`}>{renderRowContent(row)}</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
type TimelineEntry = ReturnType<typeof deriveTimelineEntries>[number];
|
||||
type TimelineMessage = Extract<TimelineEntry, { kind: "message" }>["message"];
|
||||
type TimelineProposedPlan = Extract<TimelineEntry, { kind: "proposed-plan" }>["proposedPlan"];
|
||||
type TimelineWorkEntry = Extract<TimelineEntry, { kind: "work" }>["entry"];
|
||||
type TimelineRow =
|
||||
| {
|
||||
kind: "work";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
groupedEntries: TimelineWorkEntry[];
|
||||
}
|
||||
| {
|
||||
kind: "message";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
message: TimelineMessage;
|
||||
durationStart: string;
|
||||
showCompletionDivider: boolean;
|
||||
}
|
||||
| {
|
||||
kind: "proposed-plan";
|
||||
id: string;
|
||||
createdAt: string;
|
||||
proposedPlan: TimelineProposedPlan;
|
||||
}
|
||||
| { kind: "working"; id: string; createdAt: string | null };
|
||||
|
||||
function estimateTimelineProposedPlanHeight(proposedPlan: TimelineProposedPlan): number {
|
||||
const estimatedLines = Math.max(1, Math.ceil(proposedPlan.planMarkdown.length / 72));
|
||||
return 120 + Math.min(estimatedLines * 22, 880);
|
||||
}
|
||||
|
||||
function formatWorkingTimer(startIso: string, endIso: string): string | null {
|
||||
const startedAtMs = Date.parse(startIso);
|
||||
const endedAtMs = Date.parse(endIso);
|
||||
if (!Number.isFinite(startedAtMs) || !Number.isFinite(endedAtMs)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
|
||||
if (elapsedSeconds < 60) {
|
||||
return `${elapsedSeconds}s`;
|
||||
}
|
||||
|
||||
const hours = Math.floor(elapsedSeconds / 3600);
|
||||
const minutes = Math.floor((elapsedSeconds % 3600) / 60);
|
||||
const seconds = elapsedSeconds % 60;
|
||||
|
||||
if (hours > 0) {
|
||||
return minutes > 0 ? `${hours}h ${minutes}m` : `${hours}h`;
|
||||
}
|
||||
|
||||
return seconds > 0 ? `${minutes}m ${seconds}s` : `${minutes}m`;
|
||||
}
|
||||
|
||||
function formatMessageMeta(
|
||||
createdAt: string,
|
||||
duration: string | null,
|
||||
timestampFormat: TimestampFormat,
|
||||
): string {
|
||||
if (!duration) return formatTimestamp(createdAt, timestampFormat);
|
||||
return `${formatTimestamp(createdAt, timestampFormat)} • ${duration}`;
|
||||
}
|
||||
|
||||
function workToneIcon(tone: TimelineWorkEntry["tone"]): {
|
||||
icon: LucideIcon;
|
||||
className: string;
|
||||
} {
|
||||
if (tone === "error") {
|
||||
return {
|
||||
icon: CircleAlertIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
if (tone === "thinking") {
|
||||
return {
|
||||
icon: BotIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
if (tone === "info") {
|
||||
return {
|
||||
icon: CheckIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
return {
|
||||
icon: ZapIcon,
|
||||
className: "text-foreground/92",
|
||||
};
|
||||
}
|
||||
|
||||
function workToneClass(tone: "thinking" | "tool" | "info" | "error"): string {
|
||||
if (tone === "error") return "text-rose-300/50 dark:text-rose-300/50";
|
||||
if (tone === "tool") return "text-muted-foreground/70";
|
||||
if (tone === "thinking") return "text-muted-foreground/50";
|
||||
return "text-muted-foreground/40";
|
||||
}
|
||||
|
||||
function workEntryPreview(
|
||||
workEntry: Pick<TimelineWorkEntry, "detail" | "command" | "changedFiles">,
|
||||
) {
|
||||
if (workEntry.command) return workEntry.command;
|
||||
if (workEntry.detail) return workEntry.detail;
|
||||
if ((workEntry.changedFiles?.length ?? 0) === 0) return null;
|
||||
const [firstPath] = workEntry.changedFiles ?? [];
|
||||
if (!firstPath) return null;
|
||||
return workEntry.changedFiles!.length === 1
|
||||
? firstPath
|
||||
: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
|
||||
}
|
||||
|
||||
function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
|
||||
if (workEntry.requestKind === "command") return TerminalIcon;
|
||||
if (workEntry.requestKind === "file-read") return EyeIcon;
|
||||
if (workEntry.requestKind === "file-change") return SquarePenIcon;
|
||||
|
||||
if (workEntry.itemType === "command_execution" || workEntry.command) {
|
||||
return TerminalIcon;
|
||||
}
|
||||
if (workEntry.itemType === "file_change" || (workEntry.changedFiles?.length ?? 0) > 0) {
|
||||
return SquarePenIcon;
|
||||
}
|
||||
if (workEntry.itemType === "web_search") return GlobeIcon;
|
||||
if (workEntry.itemType === "image_view") return EyeIcon;
|
||||
|
||||
switch (workEntry.itemType) {
|
||||
case "mcp_tool_call":
|
||||
return WrenchIcon;
|
||||
case "dynamic_tool_call":
|
||||
case "collab_agent_tool_call":
|
||||
return HammerIcon;
|
||||
}
|
||||
|
||||
return workToneIcon(workEntry.tone).icon;
|
||||
}
|
||||
|
||||
function capitalizePhrase(value: string): string {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) {
|
||||
return value;
|
||||
}
|
||||
return `${trimmed.charAt(0).toUpperCase()}${trimmed.slice(1)}`;
|
||||
}
|
||||
|
||||
function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
|
||||
if (!workEntry.toolTitle) {
|
||||
return capitalizePhrase(normalizeCompactToolLabel(workEntry.label));
|
||||
}
|
||||
return capitalizePhrase(normalizeCompactToolLabel(workEntry.toolTitle));
|
||||
}
|
||||
|
||||
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
|
||||
workEntry: TimelineWorkEntry;
|
||||
}) {
|
||||
const { workEntry } = props;
|
||||
const iconConfig = workToneIcon(workEntry.tone);
|
||||
const EntryIcon = workEntryIcon(workEntry);
|
||||
const heading = toolWorkEntryHeading(workEntry);
|
||||
const preview = workEntryPreview(workEntry);
|
||||
const displayText = preview ? `${heading} - ${preview}` : heading;
|
||||
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
|
||||
const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg px-1 py-1">
|
||||
<div className="flex items-center gap-2 transition-[opacity,translate] duration-200">
|
||||
<span
|
||||
className={cn("flex size-5 shrink-0 items-center justify-center", iconConfig.className)}
|
||||
>
|
||||
<EntryIcon className="size-3" />
|
||||
</span>
|
||||
<div className="min-w-0 flex-1 overflow-hidden">
|
||||
<p
|
||||
className={cn(
|
||||
"truncate text-[11px] leading-5",
|
||||
workToneClass(workEntry.tone),
|
||||
preview ? "text-muted-foreground/70" : "",
|
||||
)}
|
||||
title={displayText}
|
||||
>
|
||||
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
|
||||
{heading}
|
||||
</span>
|
||||
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
{hasChangedFiles && !previewIsChangedFiles && (
|
||||
<div className="mt-1 flex flex-wrap gap-1 pl-6">
|
||||
{workEntry.changedFiles?.slice(0, 4).map((filePath) => (
|
||||
<span
|
||||
key={`${workEntry.id}:${filePath}`}
|
||||
className="rounded-md border border-border/55 bg-background/75 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground/75"
|
||||
title={filePath}
|
||||
>
|
||||
{filePath}
|
||||
</span>
|
||||
))}
|
||||
{(workEntry.changedFiles?.length ?? 0) > 4 && (
|
||||
<span className="px-1 text-[10px] text-muted-foreground/55">
|
||||
+{(workEntry.changedFiles?.length ?? 0) - 4}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { EditorId, type ResolvedKeybindingsConfig } from "@t3tools/contracts";
|
||||
import { memo, useCallback, useEffect, useMemo } from "react";
|
||||
import { isOpenFavoriteEditorShortcut, shortcutLabelForCommand } from "../../keybindings";
|
||||
import { usePreferredEditor } from "../../editorPreferences";
|
||||
import { ChevronDownIcon, FolderClosedIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Group, GroupSeparator } from "../ui/group";
|
||||
import { Menu, MenuItem, MenuPopup, MenuShortcut, MenuTrigger } from "../ui/menu";
|
||||
import { AntigravityIcon, CursorIcon, Icon, VisualStudioCode, Zed } from "../Icons";
|
||||
import { isMacPlatform, isWindowsPlatform } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
const resolveOptions = (platform: string, availableEditors: ReadonlyArray<EditorId>) => {
|
||||
const baseOptions: ReadonlyArray<{ label: string; Icon: Icon; value: EditorId }> = [
|
||||
{
|
||||
label: "Cursor",
|
||||
Icon: CursorIcon,
|
||||
value: "cursor",
|
||||
},
|
||||
{
|
||||
label: "VS Code",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode",
|
||||
},
|
||||
{
|
||||
label: "Zed",
|
||||
Icon: Zed,
|
||||
value: "zed",
|
||||
},
|
||||
{
|
||||
label: "Antigravity",
|
||||
Icon: AntigravityIcon,
|
||||
value: "antigravity",
|
||||
},
|
||||
{
|
||||
label: isMacPlatform(platform)
|
||||
? "Finder"
|
||||
: isWindowsPlatform(platform)
|
||||
? "Explorer"
|
||||
: "Files",
|
||||
Icon: FolderClosedIcon,
|
||||
value: "file-manager",
|
||||
},
|
||||
];
|
||||
return baseOptions.filter((option) => availableEditors.includes(option.value));
|
||||
};
|
||||
|
||||
export const OpenInPicker = memo(function OpenInPicker({
|
||||
keybindings,
|
||||
availableEditors,
|
||||
openInCwd,
|
||||
}: {
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
availableEditors: ReadonlyArray<EditorId>;
|
||||
openInCwd: string | null;
|
||||
}) {
|
||||
const [preferredEditor, setPreferredEditor] = usePreferredEditor(availableEditors);
|
||||
const options = useMemo(
|
||||
() => resolveOptions(navigator.platform, availableEditors),
|
||||
[availableEditors],
|
||||
);
|
||||
const primaryOption = options.find(({ value }) => value === preferredEditor) ?? null;
|
||||
|
||||
const openInEditor = useCallback(
|
||||
(editorId: EditorId | null) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !openInCwd) return;
|
||||
const editor = editorId ?? preferredEditor;
|
||||
if (!editor) return;
|
||||
void api.shell.openInEditor(openInCwd, editor);
|
||||
setPreferredEditor(editor);
|
||||
},
|
||||
[preferredEditor, openInCwd, setPreferredEditor],
|
||||
);
|
||||
|
||||
const openFavoriteEditorShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "editor.openFavorite"),
|
||||
[keybindings],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: globalThis.KeyboardEvent) => {
|
||||
const api = readNativeApi();
|
||||
if (!isOpenFavoriteEditorShortcut(e, keybindings)) return;
|
||||
if (!api || !openInCwd) return;
|
||||
if (!preferredEditor) return;
|
||||
|
||||
e.preventDefault();
|
||||
void api.shell.openInEditor(openInCwd, preferredEditor);
|
||||
};
|
||||
window.addEventListener("keydown", handler);
|
||||
return () => window.removeEventListener("keydown", handler);
|
||||
}, [preferredEditor, keybindings, openInCwd]);
|
||||
|
||||
return (
|
||||
<Group aria-label="Subscription actions">
|
||||
<Button
|
||||
size="xs"
|
||||
variant="outline"
|
||||
disabled={!preferredEditor || !openInCwd}
|
||||
onClick={() => openInEditor(preferredEditor)}
|
||||
>
|
||||
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
Open
|
||||
</span>
|
||||
</Button>
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<Menu>
|
||||
<MenuTrigger render={<Button aria-label="Copy options" size="icon-xs" variant="outline" />}>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
{options.length === 0 && <MenuItem disabled>No installed editors found</MenuItem>}
|
||||
{options.map(({ label, Icon, value }) => (
|
||||
<MenuItem key={value} onClick={() => openInEditor(value)}>
|
||||
<Icon aria-hidden="true" className="text-muted-foreground" />
|
||||
{label}
|
||||
{value === preferredEditor && openFavoriteEditorShortcutLabel && (
|
||||
<MenuShortcut>{openFavoriteEditorShortcutLabel}</MenuShortcut>
|
||||
)}
|
||||
</MenuItem>
|
||||
))}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</Group>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import { memo, useState, useId } from "react";
|
||||
import {
|
||||
buildCollapsedProposedPlanPreviewMarkdown,
|
||||
buildProposedPlanMarkdownFilename,
|
||||
downloadPlanAsTextFile,
|
||||
normalizePlanMarkdownForExport,
|
||||
proposedPlanTitle,
|
||||
stripDisplayedPlanMarkdown,
|
||||
} from "../../proposedPlan";
|
||||
import ChatMarkdown from "../ChatMarkdown";
|
||||
import { EllipsisIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Input } from "../ui/input";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Badge } from "../ui/badge";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogPanel,
|
||||
DialogPopup,
|
||||
DialogTitle,
|
||||
} from "../ui/dialog";
|
||||
import { toastManager } from "../ui/toast";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
export const ProposedPlanCard = memo(function ProposedPlanCard({
|
||||
planMarkdown,
|
||||
cwd,
|
||||
workspaceRoot,
|
||||
}: {
|
||||
planMarkdown: string;
|
||||
cwd: string | undefined;
|
||||
workspaceRoot: string | undefined;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const [isSaveDialogOpen, setIsSaveDialogOpen] = useState(false);
|
||||
const [savePath, setSavePath] = useState("");
|
||||
const [isSavingToWorkspace, setIsSavingToWorkspace] = useState(false);
|
||||
const savePathInputId = useId();
|
||||
const title = proposedPlanTitle(planMarkdown) ?? "Proposed plan";
|
||||
const lineCount = planMarkdown.split("\n").length;
|
||||
const canCollapse = planMarkdown.length > 900 || lineCount > 20;
|
||||
const displayedPlanMarkdown = stripDisplayedPlanMarkdown(planMarkdown);
|
||||
const collapsedPreview = canCollapse
|
||||
? buildCollapsedProposedPlanPreviewMarkdown(planMarkdown, { maxLines: 10 })
|
||||
: null;
|
||||
const downloadFilename = buildProposedPlanMarkdownFilename(planMarkdown);
|
||||
const saveContents = normalizePlanMarkdownForExport(planMarkdown);
|
||||
|
||||
const handleDownload = () => {
|
||||
downloadPlanAsTextFile(downloadFilename, saveContents);
|
||||
};
|
||||
|
||||
const openSaveDialog = () => {
|
||||
if (!workspaceRoot) {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Workspace path is unavailable",
|
||||
description: "This thread does not have a workspace path to save into.",
|
||||
});
|
||||
return;
|
||||
}
|
||||
setSavePath((existing) => (existing.length > 0 ? existing : downloadFilename));
|
||||
setIsSaveDialogOpen(true);
|
||||
};
|
||||
|
||||
const handleSaveToWorkspace = () => {
|
||||
const api = readNativeApi();
|
||||
const relativePath = savePath.trim();
|
||||
if (!api || !workspaceRoot) {
|
||||
return;
|
||||
}
|
||||
if (!relativePath) {
|
||||
toastManager.add({
|
||||
type: "warning",
|
||||
title: "Enter a workspace path",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSavingToWorkspace(true);
|
||||
void api.projects
|
||||
.writeFile({
|
||||
cwd: workspaceRoot,
|
||||
relativePath,
|
||||
contents: saveContents,
|
||||
})
|
||||
.then((result) => {
|
||||
setIsSaveDialogOpen(false);
|
||||
toastManager.add({
|
||||
type: "success",
|
||||
title: "Plan saved to workspace",
|
||||
description: result.relativePath,
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not save plan",
|
||||
description: error instanceof Error ? error.message : "An error occurred while saving.",
|
||||
});
|
||||
})
|
||||
.then(
|
||||
() => {
|
||||
setIsSavingToWorkspace(false);
|
||||
},
|
||||
() => {
|
||||
setIsSavingToWorkspace(false);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="rounded-[24px] border border-border/80 bg-card/70 p-4 sm:p-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<Badge variant="secondary">Plan</Badge>
|
||||
<p className="truncate text-sm font-medium text-foreground">{title}</p>
|
||||
</div>
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
render={<Button aria-label="Plan actions" size="icon-xs" variant="outline" />}
|
||||
>
|
||||
<EllipsisIcon aria-hidden="true" className="size-4" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end">
|
||||
<MenuItem onClick={handleDownload}>Download as markdown</MenuItem>
|
||||
<MenuItem onClick={openSaveDialog} disabled={!workspaceRoot || isSavingToWorkspace}>
|
||||
Save to workspace
|
||||
</MenuItem>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
</div>
|
||||
<div className="mt-4">
|
||||
<div className={cn("relative", canCollapse && !expanded && "max-h-104 overflow-hidden")}>
|
||||
{canCollapse && !expanded ? (
|
||||
<ChatMarkdown text={collapsedPreview ?? ""} cwd={cwd} isStreaming={false} />
|
||||
) : (
|
||||
<ChatMarkdown text={displayedPlanMarkdown} cwd={cwd} isStreaming={false} />
|
||||
)}
|
||||
{canCollapse && !expanded ? (
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-0 h-24 bg-linear-to-t from-card/95 via-card/80 to-transparent" />
|
||||
) : null}
|
||||
</div>
|
||||
{canCollapse ? (
|
||||
<div className="mt-4 flex justify-center">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => setExpanded((value) => !value)}
|
||||
>
|
||||
{expanded ? "Collapse plan" : "Expand plan"}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<Dialog
|
||||
open={isSaveDialogOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!isSavingToWorkspace) {
|
||||
setIsSaveDialogOpen(open);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogPopup className="max-w-xl">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Save plan to workspace</DialogTitle>
|
||||
<DialogDescription>
|
||||
Enter a path relative to <code>{workspaceRoot ?? "the workspace"}</code>.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogPanel className="space-y-3">
|
||||
<label htmlFor={savePathInputId} className="grid gap-1.5">
|
||||
<span className="text-xs font-medium text-foreground">Workspace path</span>
|
||||
<Input
|
||||
id={savePathInputId}
|
||||
value={savePath}
|
||||
onChange={(event) => setSavePath(event.target.value)}
|
||||
placeholder={downloadFilename}
|
||||
spellCheck={false}
|
||||
disabled={isSavingToWorkspace}
|
||||
/>
|
||||
</label>
|
||||
</DialogPanel>
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setIsSaveDialogOpen(false)}
|
||||
disabled={isSavingToWorkspace}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => void handleSaveToWorkspace()}
|
||||
disabled={isSavingToWorkspace}
|
||||
>
|
||||
{isSavingToWorkspace ? "Saving..." : "Save"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogPopup>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { type ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
|
||||
import { CircleAlertIcon } from "lucide-react";
|
||||
|
||||
export const ProviderHealthBanner = memo(function ProviderHealthBanner({
|
||||
status,
|
||||
}: {
|
||||
status: ServerProviderStatus | null;
|
||||
}) {
|
||||
if (!status || status.status === "ready") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const providerLabel =
|
||||
status.provider === "codex"
|
||||
? "Codex"
|
||||
: status.provider === "claudeAgent"
|
||||
? "Claude"
|
||||
: status.provider;
|
||||
const defaultMessage =
|
||||
status.status === "error"
|
||||
? `${providerLabel} provider is unavailable.`
|
||||
: `${providerLabel} provider has limited availability.`;
|
||||
const title = providerLabel === "Codex" ? "Codex provider status" : `${providerLabel} status`;
|
||||
|
||||
return (
|
||||
<div className="pt-3 mx-auto max-w-3xl">
|
||||
<Alert variant={status.status === "error" ? "error" : "warning"}>
|
||||
<CircleAlertIcon />
|
||||
<AlertTitle>{title}</AlertTitle>
|
||||
<AlertDescription className="line-clamp-3" title={status.message ?? defaultMessage}>
|
||||
{status.message ?? defaultMessage}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { ProviderModelPicker } from "./ProviderModelPicker";
|
||||
|
||||
const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
claudeAgent: [
|
||||
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
{ slug: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
|
||||
],
|
||||
codex: [
|
||||
{ slug: "gpt-5-codex", name: "GPT-5 Codex" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
],
|
||||
} as const satisfies Record<ProviderKind, ReadonlyArray<{ slug: ModelSlug; name: string }>>;
|
||||
|
||||
async function mountPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
lockedProvider: ProviderKind | null;
|
||||
}) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onProviderModelChange = vi.fn();
|
||||
const screen = await render(
|
||||
<ProviderModelPicker
|
||||
provider={props.provider}
|
||||
model={props.model}
|
||||
lockedProvider={props.lockedProvider}
|
||||
modelOptionsByProvider={MODEL_OPTIONS_BY_PROVIDER}
|
||||
onProviderModelChange={onProviderModelChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
onProviderModelChange,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("ProviderModelPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("shows provider submenus when provider switching is allowed", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: null,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Codex");
|
||||
expect(text).toContain("Claude");
|
||||
expect(text).not.toContain("Claude Sonnet 4.6");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows models directly when the provider is locked mid-thread", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: "claudeAgent",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Claude Sonnet 4.6");
|
||||
expect(text).toContain("Claude Haiku 4.5");
|
||||
expect(text).not.toContain("Codex");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,233 @@
|
||||
import { type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { type ProviderPickerKind, PROVIDER_OPTIONS } from "../../session-logic";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuItem,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuSub,
|
||||
MenuSubPopup,
|
||||
MenuSubTrigger,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { ClaudeAI, CursorIcon, Gemini, Icon, OpenAI, OpenCodeIcon } from "../Icons";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
|
||||
value: ProviderKind;
|
||||
label: string;
|
||||
available: true;
|
||||
} {
|
||||
return option.available;
|
||||
}
|
||||
|
||||
function resolveModelForProviderPicker(
|
||||
provider: ProviderKind,
|
||||
value: string,
|
||||
options: ReadonlyArray<{ slug: string; name: string }>,
|
||||
): ModelSlug | null {
|
||||
const trimmedValue = value.trim();
|
||||
if (!trimmedValue) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const direct = options.find((option) => option.slug === trimmedValue);
|
||||
if (direct) {
|
||||
return direct.slug;
|
||||
}
|
||||
|
||||
const byName = options.find((option) => option.name.toLowerCase() === trimmedValue.toLowerCase());
|
||||
if (byName) {
|
||||
return byName.slug;
|
||||
}
|
||||
|
||||
const normalized = normalizeModelSlug(trimmedValue, provider);
|
||||
if (!normalized) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolved = options.find((option) => option.slug === normalized);
|
||||
if (resolved) {
|
||||
return resolved.slug;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
const PROVIDER_ICON_BY_PROVIDER: Record<ProviderPickerKind, Icon> = {
|
||||
codex: OpenAI,
|
||||
claudeAgent: ClaudeAI,
|
||||
cursor: CursorIcon,
|
||||
};
|
||||
|
||||
export const AVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter(isAvailableProviderOption);
|
||||
const UNAVAILABLE_PROVIDER_OPTIONS = PROVIDER_OPTIONS.filter((option) => !option.available);
|
||||
const COMING_SOON_PROVIDER_OPTIONS = [
|
||||
{ id: "opencode", label: "OpenCode", icon: OpenCodeIcon },
|
||||
{ id: "gemini", label: "Gemini", icon: Gemini },
|
||||
] as const;
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
lockedProvider: ProviderKind | null;
|
||||
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
|
||||
ultrathinkActive?: boolean;
|
||||
compact?: boolean;
|
||||
disabled?: boolean;
|
||||
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const activeProvider = props.lockedProvider ?? props.provider;
|
||||
const selectedProviderOptions = props.modelOptionsByProvider[activeProvider];
|
||||
const selectedModelLabel =
|
||||
selectedProviderOptions.find((option) => option.slug === props.model)?.name ?? props.model;
|
||||
const ProviderIcon = PROVIDER_ICON_BY_PROVIDER[activeProvider];
|
||||
const handleModelChange = (provider: ProviderKind, value: string) => {
|
||||
if (props.disabled) return;
|
||||
if (!value) return;
|
||||
const resolvedModel = resolveModelForProviderPicker(
|
||||
provider,
|
||||
value,
|
||||
props.modelOptionsByProvider[provider],
|
||||
);
|
||||
if (!resolvedModel) return;
|
||||
props.onProviderModelChange(provider, resolvedModel);
|
||||
setIsMenuOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (props.disabled) {
|
||||
setIsMenuOpen(false);
|
||||
return;
|
||||
}
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80",
|
||||
props.compact ? "max-w-42" : "sm:px-3",
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span
|
||||
className={cn("flex min-w-0 items-center gap-2", props.compact ? "max-w-36" : undefined)}
|
||||
>
|
||||
<ProviderIcon
|
||||
aria-hidden="true"
|
||||
className={cn(
|
||||
"size-4 shrink-0",
|
||||
props.provider === "claudeAgent" ? "text-[#d97757]" : "text-muted-foreground/70",
|
||||
props.provider === "claudeAgent" && props.ultrathinkActive
|
||||
? "ultrathink-chroma"
|
||||
: undefined,
|
||||
)}
|
||||
/>
|
||||
<span className="truncate">{selectedModelLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
{props.lockedProvider !== null ? (
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.model}
|
||||
onValueChange={(value) => handleModelChange(props.lockedProvider!, value)}
|
||||
>
|
||||
{props.modelOptionsByProvider[props.lockedProvider].map((modelOption) => (
|
||||
<MenuRadioItem
|
||||
key={`${props.lockedProvider}:${modelOption.slug}`}
|
||||
value={modelOption.slug}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
{modelOption.name}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : (
|
||||
<>
|
||||
{AVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
|
||||
return (
|
||||
<MenuSub key={option.value}>
|
||||
<MenuSubTrigger>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/85"
|
||||
/>
|
||||
{option.label}
|
||||
</MenuSubTrigger>
|
||||
<MenuSubPopup className="[--available-height:min(24rem,70vh)]">
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.provider === option.value ? props.model : ""}
|
||||
onValueChange={(value) => handleModelChange(option.value, value)}
|
||||
>
|
||||
{props.modelOptionsByProvider[option.value].map((modelOption) => (
|
||||
<MenuRadioItem
|
||||
key={`${option.value}:${modelOption.slug}`}
|
||||
value={modelOption.slug}
|
||||
onClick={() => setIsMenuOpen(false)}
|
||||
>
|
||||
{modelOption.name}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</MenuSubPopup>
|
||||
</MenuSub>
|
||||
);
|
||||
})}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.length > 0 && <MenuDivider />}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
|
||||
return (
|
||||
<MenuItem key={option.value} disabled>
|
||||
<OptionIcon
|
||||
aria-hidden="true"
|
||||
className="size-4 shrink-0 text-muted-foreground/85 opacity-80"
|
||||
/>
|
||||
<span>{option.label}</span>
|
||||
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
|
||||
Coming soon
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
{UNAVAILABLE_PROVIDER_OPTIONS.length === 0 && <MenuDivider />}
|
||||
{COMING_SOON_PROVIDER_OPTIONS.map((option) => {
|
||||
const OptionIcon = option.icon;
|
||||
return (
|
||||
<MenuItem key={option.id} disabled>
|
||||
<OptionIcon aria-hidden="true" className="size-4 shrink-0 opacity-80" />
|
||||
<span>{option.label}</span>
|
||||
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
|
||||
Coming soon
|
||||
</span>
|
||||
</MenuItem>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { memo } from "react";
|
||||
import { Alert, AlertAction, AlertDescription } from "../ui/alert";
|
||||
import { CircleAlertIcon, XIcon } from "lucide-react";
|
||||
|
||||
export const ThreadErrorBanner = memo(function ThreadErrorBanner({
|
||||
error,
|
||||
onDismiss,
|
||||
}: {
|
||||
error: string | null;
|
||||
onDismiss?: () => void;
|
||||
}) {
|
||||
if (!error) return null;
|
||||
return (
|
||||
<div className="pt-3 mx-auto max-w-3xl">
|
||||
<Alert variant="error">
|
||||
<CircleAlertIcon />
|
||||
<AlertDescription className="line-clamp-3" title={error}>
|
||||
{error}
|
||||
</AlertDescription>
|
||||
{onDismiss && (
|
||||
<AlertAction>
|
||||
<button
|
||||
type="button"
|
||||
aria-label="Dismiss error"
|
||||
className="inline-flex size-6 items-center justify-center rounded-md text-destructive/60 transition-colors hover:text-destructive"
|
||||
onClick={onDismiss}
|
||||
>
|
||||
<XIcon className="size-3.5" />
|
||||
</button>
|
||||
</AlertAction>
|
||||
)}
|
||||
</Alert>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { memo, useMemo, useState } from "react";
|
||||
import { getVscodeIconUrlForEntry } from "../../vscode-icons";
|
||||
import { FileIcon, FolderIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export const VscodeEntryIcon = memo(function VscodeEntryIcon(props: {
|
||||
pathValue: string;
|
||||
kind: "file" | "directory";
|
||||
theme: "light" | "dark";
|
||||
className?: string;
|
||||
}) {
|
||||
const [failedIconUrl, setFailedIconUrl] = useState<string | null>(null);
|
||||
const iconUrl = useMemo(
|
||||
() => getVscodeIconUrlForEntry(props.pathValue, props.kind, props.theme),
|
||||
[props.kind, props.pathValue, props.theme],
|
||||
);
|
||||
const failed = failedIconUrl === iconUrl;
|
||||
|
||||
if (failed) {
|
||||
return props.kind === "directory" ? (
|
||||
<FolderIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
) : (
|
||||
<FileIcon className={cn("size-4 text-muted-foreground/80", props.className)} />
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
src={iconUrl}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
className={cn("size-4 shrink-0", props.className)}
|
||||
loading="lazy"
|
||||
onError={() => setFailedIconUrl(iconUrl)}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -29,6 +29,7 @@ const selectTriggerVariants = cva(
|
||||
default: "min-h-9 px-[calc(--spacing(3)-1px)] sm:min-h-8",
|
||||
lg: "min-h-10 px-[calc(--spacing(3)-1px)] sm:min-h-9",
|
||||
sm: "min-h-8 gap-1.5 px-[calc(--spacing(2.5)-1px)] sm:min-h-7",
|
||||
xs: "h-7 gap-1 rounded-md px-[calc(--spacing(2)-1px)] text-sm before:rounded-[calc(var(--radius-md)-1px)] sm:h-6 sm:text-xs [&_svg:not([class*='size-'])]:size-4 sm:[&_svg:not([class*='size-'])]:size-3.5",
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Loaded 100 of 150 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user