Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge cda0e97dae Fix Claude tests to create threads with Claude model
The two Claude tests ('forwards claude effort options' and 'restarts claude
sessions when claude effort changes') dispatched turns with provider
'claudeAgent' on thread-1, which was created by createHarness with model
'gpt-5-codex'. The provider validation infers 'codex' for that model,
rejecting the 'claudeAgent' provider mismatch.

Fix by having each Claude test create a dedicated thread with model
'claude-sonnet-4-6' so inferProviderForModel returns 'claudeAgent' and
the validation passes.

Co-authored-by: Julius Marminge <[email protected]>
2026-03-17 20:36:33 +00:00
JustYanniccandClaude Opus 4.6 e6254a8451 feat: claude effort controls, ultrathink UI, and adapter robustness (#1146)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-17 13:23:07 -07:00
Julius Marminge b04132d8c8 Use provider default model in orchestration integration seed
- derive `defaultModel` from `DEFAULT_MODEL_BY_PROVIDER` using harness provider
- replace hardcoded `gpt-5-codex` in seeded project and thread setup
2026-03-16 17:36:56 -07:00
Julius Marminge b577cb5326 Fix locked-thread model selection and provider fallback
- Use thread provider as the preferred provider during command handling
- Update `ProviderModelPicker` to show direct model choices when provider is locked
- Add browser tests for locked/unlocked picker behavior and widen browser test glob
2026-03-16 17:26:50 -07:00
Julius Marminge fc9660f238 Enforce provider-model consistency for thread turn starts
- Reject turn starts that request a provider switch from the thread-bound provider
- Reject models that do not belong to the thread provider and log start failures
- Add shared `inferProviderForModel` helper and tests; reuse it in web store inference
2026-03-16 17:09:38 -07:00
Julius Marminge b403ca3183 dont provide generated orchestration ids to native providerRefs 2026-03-16 16:09:50 -07:00
Julius Marminge f34dd0a91f Schema.is 2026-03-16 15:48:28 -07:00
Julius Marminge 33791cdfe5 align branding guide lines 2026-03-16 15:41:12 -07:00
Julius Marminge fdcb05d3f6 replace ad-hoc union for contract type 2026-03-16 12:16:24 -07:00
Julius Marmingeandcodex 2121682546 Improve Claude adapter tool streaming and health checks
- Map Claude reasoning deltas, streamed tool input JSON, and tool results into runtime item/content events
- Classify Agent/read-only Claude tools for correct approval request types
- Add Claude CLI provider health checks and auth-status parsing coverage

Co-authored-by: codex <[email protected]>
2026-03-16 12:14:27 -07:00
Julius Marminge d2b00e6550 Show Claude Code in provider picker and add Cursor placeholder
- Include Claude Code in available provider options in the picker
- Add Cursor as a disabled placeholder provider with icon mapping
- Update session-logic tests to assert provider availability and ordering
2026-03-16 11:11:57 -07:00
Julius Marminge e0facb03bd fix circular import 2026-03-16 11:06:26 -07:00
Julius Marminge 73152abe81 fmt 2026-03-16 11:03:31 -07:00
Julius Marminge c5bfff1583 unify start option union 2026-03-16 10:41:05 -07:00
Julius Marminge 040011dbc7 Remove Cursor provider support across server and web
- drop `cursor` from provider/model contracts and runtime validation
- remove Cursor-specific UI options, settings, and model normalization paths
- update server/web tests and fixtures to cover Codex + Claude Code only
2026-03-16 10:35:53 -07:00
Julius Marminge 858116d836 fmt 2026-03-16 10:28:36 -07:00
Julius Marminge ff34d2c708 lock 2026-03-16 10:28:24 -07:00
Julius Marmingeandcodex 99cd1c560e Fix post-rebase provider integration
Co-authored-by: codex <[email protected]>
2026-03-16 10:24:55 -07:00
Julius Marmingeandcodex 01f01c5e6b build: sync Claude SDK lockfile on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:18:03 -07:00
Julius Marmingeandcodex de7cfba261 split: restore Claude SDK manifest and plan doc
Co-authored-by: codex <[email protected]>
2026-03-16 10:17:45 -07:00
Julius Marmingeandcodex 1da30f776e split: restore Claude provider surface on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:17:45 -07:00
Julius Marmingeandcodex 11aca1fcc6 model: restore Claude catalogs on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:12:33 -07:00
Julius Marmingeandcodex 95c50053bc contracts: restore Claude schemas on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:09:06 -07:00
Julius Marmingeandcodex da9cbcc98c test: restore Claude coverage on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:08:09 -07:00
Julius Marmingeandcodex b9ea1487b3 Restore Claude adapter on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:07:39 -07:00
Daniel StickerandJulius Marminge 765c1dc9e4 fix(desktop): backfill SSH_AUTH_SOCK from login shell on macOS (#972)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-16 09:05:37 -07:00
Utkarsh Patil e6d9a271fc fix(github): fix bug report issue template for screenshots (#1109) 2026-03-15 22:31:36 -07:00
Ivor 4b811dae61 Fixed Typos in Agents.md (#1120) 2026-03-15 16:34:09 +00:00
Etan HeymanandJulius Marminge 6d76865e74 fix: tighten node engine range for node:sqlite compat (#206) (#1096)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-14 19:22:56 -07:00
Sai Shankar 2bb71f41c3 feat(web): add scroll to bottom pill in chat view (#619) 2026-03-14 10:44:55 -07:00
Stefan Wintergerst cc2ab00074 chore: add .idea/ to .gitignore (#1077) 2026-03-14 16:03:35 +00:00
XanacasandClaude Opus 4.6 8b8e8b38e5 fix(web): unify focus ring styles across sidebar and app (#1079)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-14 15:51:37 +00:00
Vitor Buzinaro 46ea594f02 Actions dialog: autofocus script-name field (#912) 2026-03-14 01:05:12 +00:00
0x1f99d 790fda1a97 feat(github): add issue templates for automatic triage (#896) 2026-03-13 11:29:22 -07:00
Julius Marminge 89ffcf42eb Upgrade oxfmt and oxlint tooling versions (#1010) 2026-03-12 23:24:42 -07:00
876bbd715a Extract reusable clipboard hook and standardize media queries (#1006)
Co-authored-by: macroscopeapp[bot] <170038800+macroscopeapp[bot]@users.noreply.github.com>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-03-12 21:03:21 -07:00
0x1f99dandJulius Marminge ac0d1f52a0 fix(web): defer diff worker startup until diff opens (#934)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 20:47:29 -07:00
0x1f99dandJulius Marminge d0ae0adc99 fix(web): add default thread env mode setting (#892)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 20:18:20 -07:00
Jono Kemball 995a26660e chore: Upgrade marketing app to Astro 6 (#1005) 2026-03-12 20:18:03 -07:00
dpav02andClaude Opus 4.6 dfd62cfb86 fix(desktop): show dialog after "Check for Updates" menu action (#955)
Co-authored-by: Claude Opus 4.6 <[email protected]>
2026-03-12 19:43:07 -07:00
ZortosandJulius Marminge 64dc07a8e5 Add compact Codex tool-call icons and details to the chat timeline (#988)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 19:42:59 -07:00
Jono Kemball ae4ae9973c chore: update @vitejs/plugin-react to 6.0.0 (#1002) 2026-03-12 19:30:47 -07:00
ZortosandJulius Marminge 36473f7de6 feat: replace worktree toggle with discoverable Select dropdown (#1001)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 19:26:14 -07:00
(CJ) Chukwudi Nwobodo a14debc83e fix: block image uploads during plan mode questions (#621) 2026-03-12 17:24:53 -07:00
(CJ) Chukwudi Nwobodo 71a7473a81 fix: composer @file autocomplete cursor and spacing bugs (#936) 2026-03-12 16:33:37 -07:00
WilgotMandJulius Marminge 5c03fb62c4 Add Antigravity to supported editors in Open menu (macOS, Windows, and Linux) (#841)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 23:28:32 +00:00
Hugo Blom 727c0cfcbf feat: Allow Overriding Timestamp Format in Settings (#855) 2026-03-12 15:58:51 -07:00
Noah GregoryandJulius Marminge dcd2e5c34f fix: don't restart the app on normal exists in dev runner (#986)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 13:03:55 -07:00
KiyotakaandJulius Marminge 1e276573c2 feat: add fuzzy workspace entry search (#256)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 13:00:08 -07:00
Julius Marminge db17ff3323 fix syntax errors from bad merge 2026-03-12 12:40:08 -07:00
Qiaochu Hu b496ae8395 fix: add error logging for code highlighting failures (#951) 2026-03-12 12:35:21 -07:00
Qiaochu Huandhobostay 724f54c2c1 fix: clean up timeout in PlanSidebar to prevent memory leaks (#949)
Co-authored-by: hobostay <[email protected]>
2026-03-12 12:32:00 -07:00
Qiaochu Huandhobostay b6eba3347d fix: add logging for WebSocket errors (#948)
Co-authored-by: hobostay <[email protected]>
2026-03-12 12:31:19 -07:00
Adam NajiandJulius Marminge 74c22628b3 chore: update actions/checkout and actions/github-script (#956)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 12:29:07 -07:00
0x1f99dandJulius Marminge 224acebb57 fix(web): add pointer cursor to running stop-generation button (#900)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 12:15:01 -07:00
Alex Schwartz 85c174a6ca fix: Linux icon now shows up (#807) 2026-03-12 12:09:41 -07:00
Julius Marminge 581d242925 remove triggers 2026-03-12 12:01:55 -07:00
Julius Marminge d9d0216e98 fix pr size workflow 2026-03-12 12:01:27 -07:00
Julius Marminge c52ad29b31 Fix mod+N new thread flow and terminal split limits
- ensure `chat.new` creates a fresh draft after a promoted draft thread
- enforce terminal cap per split group (4) while allowing additional terminal groups
- refine sidebar row selected/active styling via shared class-name logic and tests
2026-03-12 11:50:35 -07:00
Julius Marminge fcbf3f3c22 Fix new-thread shortcuts when terminal is focused
- move chat-wide key handling into `_chat` route-level shortcut handler
- extract reusable `useHandleNewThread` hook and `isTerminalFocused` helper
- update browser WS fixture to support `terminalOpen` RPC shape
2026-03-12 11:50:35 -07:00
Donald Silveira ab0002f99d update project removal copy (#981) 2026-03-12 11:48:23 -07:00
Noah GregoryandJulius Marminge f63cda22fa fix: improve business logic in prompt editor and fix cursor bugs in Plan mode (#867)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 11:24:10 -07:00
Noah Gregory b60a34eba4 fix: fix logo aligment regression on macOS (#960) 2026-03-12 11:13:37 -07:00
Jono Kemball ed4be2c849 fix: Fix response duration for agent to no longer always be 1ms (#866) 2026-03-12 11:12:18 -07:00
Noah Gregory 5e23e9c7c7 add Ymit24 to vouched list (#959) 2026-03-12 11:10:58 -07:00
Guilherme VieiraandJulius Marminge c3bfcc36b8 feat: add selective file staging to commit dialog (#872)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 10:50:49 -07:00
eggfriedrice a33cc8c758 fix: diff panel unclosable after retainSearchParams middleware (#937) 2026-03-12 10:44:16 -07:00
Magnus BuvarpandJulius Marminge a01d712751 fix(web): resolve preferred editor from available editors & introduce useLocalStorage helper (#662)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-12 10:42:17 -07:00
0x1f99d 774cff9a74 ci(github): add pull request size labels (#901) 2026-03-12 09:10:07 -07:00
Ymit24andChristian Smith e3d46b687c feat: split out components from ChatView.tsx (#860)
Co-authored-by: Christian Smith <[email protected]>
2026-03-11 19:21:22 -07:00
Theo Browne 8636ea0ec4 Add maria-rcks to the list of contributors 2026-03-11 17:16:51 -07:00
David Balderston ff6a66dcab Use live thread activities for sidebar status pills (#919) 2026-03-11 14:05:17 -07:00
maria 2ac735657e chore(release): align package versions before building artifacts (#933) 2026-03-11 14:03:49 -07:00
github-actions[bot] bbab1fc891 chore(release): prepare v0.0.10 2026-03-11 17:27:36 +00:00
167 changed files with 14700 additions and 5997 deletions

No files matched your search

+117
View File
@@ -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.
+101
View File
@@ -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.
+2
View File
@@ -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
+6 -6
View File
@@ -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
+75
View File
@@ -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,
});
}
}
+202
View File
@@ -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}`);
+43 -19
View File
@@ -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}`);
+18 -12
View File
@@ -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
+1
View File
@@ -13,6 +13,7 @@ build/
.logs/
release/
.t3
.idea/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
+441
View File
@@ -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`.
-27
View File
@@ -1,27 +0,0 @@
{
"name": "@effect-http-ws-cli/server",
"version": "0.1.0",
"private": true,
"type": "module",
"exports": {
"./client": "./src/client.ts",
"./contracts": "./src/contracts.ts"
},
"scripts": {
"dev": "node src/bin.ts",
"start": "node src/bin.ts",
"test": "vitest run",
"lint": "tsc --noEmit"
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-node": "catalog:",
"effect": "catalog:"
},
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "^24.10.0",
"typescript": "catalog:",
"vitest": "catalog:"
}
}
@@ -1,32 +0,0 @@
import * as Effect from "effect/Effect"
import * as SqlClient from "effect/unstable/sql/SqlClient"
export default Effect.gen(function*() {
const sql = yield* SqlClient.SqlClient
yield* sql`
CREATE TABLE IF NOT EXISTS todos (
id TEXT PRIMARY KEY NOT NULL,
title TEXT NOT NULL,
completed INTEGER NOT NULL,
archived INTEGER NOT NULL,
revision INTEGER NOT NULL,
updated_at TEXT NOT NULL
)
`
yield* sql`
CREATE TABLE IF NOT EXISTS todo_events (
event_offset INTEGER PRIMARY KEY AUTOINCREMENT,
at TEXT NOT NULL,
todo_json TEXT NOT NULL,
change_json TEXT NOT NULL,
archived INTEGER NOT NULL
)
`
yield* sql`
CREATE INDEX IF NOT EXISTS idx_todo_events_archived_offset
ON todo_events (archived, event_offset)
`
})
-11
View File
@@ -1,11 +0,0 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime"
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as Effect from "effect/Effect"
import { cli } from "./cli.ts"
import { Command } from "effect/unstable/cli"
Command.run(cli, { version: "0.1.0" }).pipe(
Effect.provide(NodeServices.layer),
NodeRuntime.runMain
)
-125
View File
@@ -1,125 +0,0 @@
import * as SqliteNode from "@effect/sql-sqlite-node"
import { Command, Flag } from "effect/unstable/cli"
import * as Config from "effect/Config"
import * as Effect from "effect/Effect"
import * as FileSystem from "effect/FileSystem"
import * as Option from "effect/Option"
import * as Path from "effect/Path"
import { fileURLToPath } from "node:url"
import { ServerConfig } from "./config.ts"
import { runMigrations } from "./migrations.ts"
import { runServer } from "./server.ts"
import type { ServerConfigData } from "./config.ts"
const defaultAssetsDir = fileURLToPath(new URL("../../public", import.meta.url))
const defaultDbFilename = fileURLToPath(new URL("../../todo.sqlite", import.meta.url))
const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host interface to bind"),
Flag.optional
)
const portFlag = Flag.integer("port").pipe(
Flag.withDescription("Port to listen on"),
Flag.optional
)
const assetsFlag = Flag.directory("assets").pipe(
Flag.withDescription("Directory of static assets"),
Flag.optional
)
const dbFlag = Flag.string("db").pipe(
Flag.withDescription("SQLite database filename"),
Flag.optional
)
const requestLoggingFlag = Flag.boolean("request-logging").pipe(
Flag.withDescription("Enable request logging"),
Flag.optional
)
const frontendDevOriginFlag = Flag.string("frontend-dev-origin").pipe(
Flag.withDescription("Redirect frontend GET requests to a Vite dev server origin"),
Flag.optional
)
const EnvServerConfig = Config.unwrap({
host: Config.string("HOST").pipe(Config.withDefault("127.0.0.1")),
port: Config.port("PORT").pipe(Config.withDefault(8787)),
assetsDir: Config.string("ASSETS_DIR").pipe(Config.withDefault(defaultAssetsDir)),
dbFilename: Config.string("DB_FILENAME").pipe(Config.withDefault(defaultDbFilename)),
requestLogging: Config.boolean("REQUEST_LOGGING").pipe(Config.withDefault(true)),
frontendDevOrigin: Config.string("FRONTEND_DEV_ORIGIN").pipe(
Config.option,
Config.map(Option.getOrUndefined)
)
})
export interface CliServerFlags {
readonly host: Option.Option<string>
readonly port: Option.Option<number>
readonly assets: Option.Option<string>
readonly db: Option.Option<string>
readonly requestLogging: Option.Option<boolean>
readonly frontendDevOrigin: Option.Option<string>
}
export const resolveServerConfig = (
flags: CliServerFlags
): Effect.Effect<ServerConfigData, Config.ConfigError> =>
Effect.gen(function*() {
const env = yield* EnvServerConfig
return {
host: Option.getOrElse(flags.host, () => env.host),
port: Option.getOrElse(flags.port, () => env.port),
assetsDir: Option.getOrElse(flags.assets, () => env.assetsDir),
dbFilename: Option.getOrElse(flags.db, () => env.dbFilename),
requestLogging: Option.getOrElse(flags.requestLogging, () => env.requestLogging),
frontendDevOrigin: Option.getOrElse(flags.frontendDevOrigin, () => env.frontendDevOrigin)
}
})
export const resetDatabase = (dbFilename: string) =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
if (dbFilename !== ":memory:") {
yield* fs.remove(path.resolve(dbFilename), { force: true })
}
const sqliteLayer = SqliteNode.SqliteClient.layer({
filename: dbFilename
})
yield* runMigrations.pipe(Effect.provide(sqliteLayer))
})
const commandFlags = {
host: hostFlag,
port: portFlag,
assets: assetsFlag,
db: dbFlag,
requestLogging: requestLoggingFlag,
frontendDevOrigin: frontendDevOriginFlag
} as const
const rootCommand = Command.make("effect-http-ws-cli", commandFlags).pipe(
Command.withDescription("Run a unified Effect HTTP + WebSocket server"),
Command.withHandler((flags) =>
Effect.flatMap(resolveServerConfig(flags), (config) =>
runServer.pipe(Effect.provideService(ServerConfig, config)))),
)
const resetCommand = Command.make("reset", commandFlags).pipe(
Command.withDescription("Delete the SQLite database file and rerun migrations"),
Command.withHandler((flags) =>
Effect.flatMap(resolveServerConfig(flags), (config) => resetDatabase(config.dbFilename))
)
)
export const cli = rootCommand.pipe(
Command.withSubcommands([resetCommand])
)
-58
View File
@@ -1,58 +0,0 @@
import { NodeSocket } from "@effect/platform-node"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as RpcClient from "effect/unstable/rpc/RpcClient"
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"
import * as Stream from "effect/Stream"
import { WsRpcGroup } from "./contracts.ts"
export const wsRpcProtocolLayer = (wsUrl: string) =>
RpcClient.layerProtocolSocket().pipe(
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
Layer.provide(RpcSerialization.layerJson)
)
export const makeWsRpcClient = RpcClient.make(WsRpcGroup)
type WsRpcClient = typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never
export const withWsRpcClient = <A, E, R>(
wsUrl: string,
f: (client: WsRpcClient) => Effect.Effect<A, E, R>
) =>
makeWsRpcClient.pipe(
Effect.flatMap(f),
Effect.provide(wsRpcProtocolLayer(wsUrl))
)
export const runClientExample = (wsUrl: string) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const echoed = yield* client.echo({ text: "hello from client" })
const summed = yield* client.sum({ left: 20, right: 22 })
const time = yield* client.time(undefined)
return { echoed, summed, time }
})
)
)
export const runSubscriptionExample = (wsUrl: string, modelId: string) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const todo = snapshot.todos[0]
if (!todo) {
return []
}
yield* client.renameTodo({ id: todo.id, title: `${modelId}: first` })
yield* client.completeTodo({ id: todo.id, completed: true })
return yield* client.subscribeTodos({ fromOffset: snapshot.offset, includeArchived: true }).pipe(
Stream.take(2),
Stream.runCollect
)
})
)
)
-14
View File
@@ -1,14 +0,0 @@
import * as ServiceMap from "effect/ServiceMap"
export interface ServerConfigData {
readonly host: string
readonly port: number
readonly assetsDir: string
readonly dbFilename: string
readonly requestLogging: boolean
readonly frontendDevOrigin: string | undefined
}
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigData>()(
"effect-http-ws-cli/ServerConfig"
) {}
-132
View File
@@ -1,132 +0,0 @@
import * as Schema from "effect/Schema"
import * as Rpc from "effect/unstable/rpc/Rpc"
import * as RpcGroup from "effect/unstable/rpc/RpcGroup"
export const EchoPayload = Schema.Struct({
text: Schema.String
})
export const EchoResult = Schema.Struct({
text: Schema.String
})
export const SumPayload = Schema.Struct({
left: Schema.Number,
right: Schema.Number
})
export const SumResult = Schema.Struct({
total: Schema.Number
})
export const TimeResult = Schema.Struct({
iso: Schema.String
})
export const Todo = Schema.Struct({
id: Schema.String,
title: Schema.String,
completed: Schema.Boolean,
archived: Schema.Boolean,
revision: Schema.Number,
updatedAt: Schema.String
})
export type Todo = Schema.Schema.Type<typeof Todo>
export const TodoChange = Schema.Union([
Schema.Struct({
_tag: Schema.Literal("TodoCreated")
}),
Schema.Struct({
_tag: Schema.Literal("TodoRenamed"),
title: Schema.String
}),
Schema.Struct({
_tag: Schema.Literal("TodoCompleted"),
completed: Schema.Boolean
}),
Schema.Struct({
_tag: Schema.Literal("TodoArchived"),
archived: Schema.Boolean
})
])
export type TodoChange = Schema.Schema.Type<typeof TodoChange>
export const TodoEvent = Schema.Struct({
offset: Schema.Number,
at: Schema.String,
todo: Todo,
change: TodoChange
})
export type TodoEvent = Schema.Schema.Type<typeof TodoEvent>
export const TodoSnapshot = Schema.Struct({
offset: Schema.Number,
todos: Schema.Array(Todo)
})
export type TodoSnapshot = Schema.Schema.Type<typeof TodoSnapshot>
export const EchoRpc = Rpc.make("echo", {
payload: EchoPayload,
success: EchoResult
})
export const SumRpc = Rpc.make("sum", {
payload: SumPayload,
success: SumResult
})
export const TimeRpc = Rpc.make("time", {
success: TimeResult
})
export const ListTodosRpc = Rpc.make("listTodos", {
payload: Schema.Struct({
includeArchived: Schema.Boolean
}),
success: TodoSnapshot
})
export const RenameTodoRpc = Rpc.make("renameTodo", {
payload: Schema.Struct({
id: Schema.String,
title: Schema.String
}),
success: TodoEvent
})
export const CompleteTodoRpc = Rpc.make("completeTodo", {
payload: Schema.Struct({
id: Schema.String,
completed: Schema.Boolean
}),
success: TodoEvent
})
export const ArchiveTodoRpc = Rpc.make("archiveTodo", {
payload: Schema.Struct({
id: Schema.String,
archived: Schema.Boolean
}),
success: TodoEvent
})
export const SubscribeTodosRpc = Rpc.make("subscribeTodos", {
payload: Schema.Struct({
fromOffset: Schema.Number,
includeArchived: Schema.Boolean
}),
success: TodoEvent,
stream: true
})
export const WsRpcGroup = RpcGroup.make(
EchoRpc,
SumRpc,
TimeRpc,
ListTodosRpc,
RenameTodoRpc,
CompleteTodoRpc,
ArchiveTodoRpc,
SubscribeTodosRpc
)
-73
View File
@@ -1,73 +0,0 @@
import * as Schema from "effect/Schema"
import * as SchemaTransformation from "effect/SchemaTransformation"
export const ClientMessage = Schema.Union([
Schema.Struct({
kind: Schema.Literal("echo"),
text: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("sum"),
left: Schema.Number,
right: Schema.Number
}),
Schema.Struct({
kind: Schema.Literal("time")
})
])
export type ClientMessage = Schema.Schema.Type<typeof ClientMessage>
export const ServerMessage = Schema.Union([
Schema.Struct({
kind: Schema.Literal("echo"),
text: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("sumResult"),
total: Schema.Number
}),
Schema.Struct({
kind: Schema.Literal("time"),
iso: Schema.String
}),
Schema.Struct({
kind: Schema.Literal("error"),
error: Schema.String
})
])
export type ServerMessage = Schema.Schema.Type<typeof ServerMessage>
export const decodeClientMessage = Schema.decodeUnknownEffect(ClientMessage)
const Utf8StringFromUint8Array = Schema.Uint8Array.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transform({
decode: (bytes) => new TextDecoder().decode(bytes),
encode: (text) => new TextEncoder().encode(text)
})
)
)
const ClientMessageFromWire = Schema.Union([
Schema.String,
Utf8StringFromUint8Array
]).pipe(
Schema.decodeTo(Schema.fromJsonString(ClientMessage))
)
export const decodeWireClientMessage = Schema.decodeUnknownEffect(ClientMessageFromWire)
export const routeClientMessage = (message: ClientMessage): ServerMessage => {
switch (message.kind) {
case "echo":
return { kind: "echo", text: message.text }
case "sum":
return { kind: "sumResult", total: message.left + message.right }
case "time":
return { kind: "time", iso: new Date().toISOString() }
}
}
-41
View File
@@ -1,41 +0,0 @@
/**
* MigrationsLive - Migration runner with inline loader
*
* Uses Migrator.make with fromRecord to define migrations inline.
* All migrations are statically imported - no dynamic file system loading.
*
* Migrations run automatically when the MigrationsLive layer is provided,
* ensuring the database schema is up-to-date before the application starts.
*/
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as ServiceMap from "effect/ServiceMap"
import * as Migrator from "effect/unstable/sql/Migrator"
import Migration0001 from "./Migrations/001_TodoSchema.ts"
const loader = Migrator.fromRecord({
"1_TodoSchema": Migration0001
})
const run = Migrator.make({})
export const runMigrations = Effect.gen(function*() {
yield* Effect.log("Running migrations...")
yield* run({ loader })
yield* Effect.log("Migrations ran successfully")
})
export interface MigrationsReadyApi {
readonly ready: true
}
export class MigrationsReady extends ServiceMap.Service<MigrationsReady, MigrationsReadyApi>()(
"effect-http-ws-cli/MigrationsReady"
) {}
export const MigrationsLive = Layer.effect(
MigrationsReady,
runMigrations.pipe(
Effect.as(MigrationsReady.of({ ready: true }))
)
)
-268
View File
@@ -1,268 +0,0 @@
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Option from "effect/Option"
import * as PubSub from "effect/PubSub"
import * as Schema from "effect/Schema"
import * as ServiceMap from "effect/ServiceMap"
import * as Stream from "effect/Stream"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import * as SqlSchema from "effect/unstable/sql/SqlSchema"
import type { Todo, TodoChange, TodoEvent, TodoSnapshot } from "./contracts.ts"
import { Todo as TodoSchema, TodoChange as TodoChangeSchema } from "./contracts.ts"
import { MigrationsReady } from "./migrations.ts"
export interface TodoStoreApi {
readonly list: (input: {
readonly includeArchived: boolean
}) => Effect.Effect<TodoSnapshot, never, SqlClient.SqlClient>
readonly rename: (input: {
readonly id: string
readonly title: string
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly complete: (input: {
readonly id: string
readonly completed: boolean
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly archive: (input: {
readonly id: string
readonly archived: boolean
}) => Effect.Effect<TodoEvent, never, SqlClient.SqlClient>
readonly subscribe: (input: {
readonly fromOffset: number
readonly includeArchived: boolean
}) => Stream.Stream<TodoEvent, never, SqlClient.SqlClient>
}
export class TodoStore extends ServiceMap.Service<TodoStore, TodoStoreApi>()(
"effect-http-ws-cli/TodoStore"
) {}
const TodoRow = Schema.Struct({
id: Schema.String,
title: Schema.String,
completed: Schema.BooleanFromBit,
archived: Schema.BooleanFromBit,
revision: Schema.Number,
updatedAt: Schema.String
})
const TodoEventRow = Schema.Struct({
offset: Schema.Number,
at: Schema.String,
todo: Schema.fromJsonString(TodoSchema),
change: Schema.fromJsonString(TodoChangeSchema)
})
const EventInsertRequest = Schema.Struct({
at: Schema.String,
todo: Schema.fromJsonString(TodoSchema),
change: Schema.fromJsonString(TodoChangeSchema),
archived: Schema.BooleanFromBit
})
const ListRequest = Schema.Struct({
includeArchived: Schema.Boolean
})
const CatchupRequest = Schema.Struct({
fromOffset: Schema.Number,
includeArchived: Schema.Boolean
})
const OffsetRow = Schema.Struct({
offset: Schema.Number
})
const makeQueries = (sql: SqlClient.SqlClient) => {
const listTodoRows = SqlSchema.findAll({
Request: ListRequest,
Result: TodoRow,
execute: (request) =>
request.includeArchived
? sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
ORDER BY id
`
: sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
WHERE archived = 0
ORDER BY id
`
})
const findTodoById = SqlSchema.findOneOption({
Request: Schema.String,
Result: TodoRow,
execute: (id) => sql<Todo>`
SELECT id, title, completed, archived, revision, updated_at AS updatedAt
FROM todos
WHERE id = ${id}
`
})
const upsertTodo = SqlSchema.void({
Request: TodoRow,
execute: (todo) => sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${todo.id}, ${todo.title}, ${todo.completed}, ${todo.archived}, ${todo.revision}, ${todo.updatedAt})
ON CONFLICT(id) DO UPDATE SET
title = excluded.title,
completed = excluded.completed,
archived = excluded.archived,
revision = excluded.revision,
updated_at = excluded.updated_at
`
})
const loadEventsSince = SqlSchema.findAll({
Request: CatchupRequest,
Result: TodoEventRow,
execute: (request) =>
request.includeArchived
? sql<TodoEvent>`
SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change
FROM todo_events
WHERE event_offset > ${request.fromOffset}
ORDER BY event_offset
`
: sql<TodoEvent>`
SELECT event_offset AS "offset", at, todo_json AS todo, change_json AS change
FROM todo_events
WHERE event_offset > ${request.fromOffset} AND archived = 0
ORDER BY event_offset
`
})
const insertTodoEvent = SqlSchema.findOne({
Request: EventInsertRequest,
Result: TodoEventRow,
execute: (request) => sql<TodoEvent>`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (${request.at}, ${request.todo}, ${request.change}, ${request.archived})
RETURNING event_offset AS "offset", at, todo_json AS todo, change_json AS change
`
})
const currentOffset = SqlSchema.findOne({
Request: Schema.Undefined,
Result: OffsetRow,
execute: () => sql<{ readonly offset: number }>`
SELECT COALESCE(MAX(event_offset), 0) AS "offset"
FROM todo_events
`
})
return {
listTodoRows,
findTodoById,
upsertTodo,
loadEventsSince,
insertTodoEvent,
currentOffset
} as const
}
export const layerTodoStore = Layer.effect(
TodoStore,
Effect.gen(function*() {
yield* MigrationsReady
const eventsPubSub = yield* PubSub.unbounded<TodoEvent>()
const append = (
todoId: string,
change: TodoChange,
update: (todo: Todo) => Todo
): Effect.Effect<TodoEvent, never, SqlClient.SqlClient> =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const queries = makeQueries(sql)
return sql.withTransaction(
queries.findTodoById(todoId).pipe(
Effect.flatMap(
Option.match({
onNone: () => Effect.die(`Todo not found: ${todoId}`),
onSome: (todo) => {
const updated = update(todo)
return queries.upsertTodo(updated).pipe(
Effect.flatMap(() =>
queries.insertTodoEvent({
at: updated.updatedAt,
todo: updated,
change,
archived: updated.archived
})
)
)
}
})
)
)
)
}).pipe(Effect.tap((event) => PubSub.publish(eventsPubSub, event)), Effect.orDie)
const visible = (todo: Todo, includeArchived: boolean) => includeArchived || !todo.archived
const subscribe = (input: {
readonly fromOffset: number
readonly includeArchived: boolean
}): Stream.Stream<TodoEvent, never, SqlClient.SqlClient> => {
const catchup = Stream.fromIterableEffect(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => makeQueries(sql).loadEventsSince(input))
).pipe(Stream.orDie)
const live = Stream.fromPubSub(eventsPubSub).pipe(
Stream.filter((event) => visible(event.todo, input.includeArchived))
)
return Stream.concat(catchup, live)
}
return TodoStore.of({
list: ({ includeArchived }) =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const queries = makeQueries(sql)
return Effect.all({
todos: queries.listTodoRows({ includeArchived }),
offset: queries.currentOffset(undefined).pipe(Effect.map(({ offset }) => offset))
}).pipe(
Effect.map(({ offset, todos }) => ({ offset, todos }))
)
}).pipe(Effect.orDie),
rename: ({ id, title }) =>
append(
id,
{ _tag: "TodoRenamed", title },
(todo) => ({
...todo,
title,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
complete: ({ id, completed }) =>
append(
id,
{ _tag: "TodoCompleted", completed },
(todo) => ({
...todo,
completed,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
archive: ({ id, archived }) =>
append(
id,
{ _tag: "TodoArchived", archived },
(todo) => ({
...todo,
archived,
revision: todo.revision + 1,
updatedAt: new Date().toISOString()
})
),
subscribe
})
})
)
-155
View File
@@ -1,155 +0,0 @@
import { NodeHttpServer } from "@effect/platform-node"
import * as SqliteNode from "@effect/sql-sqlite-node"
import * as Effect from "effect/Effect"
import * as FileSystem from "effect/FileSystem"
import * as Layer from "effect/Layer"
import * as Path from "effect/Path"
import * as Http from "node:http"
import {
HttpRouter,
HttpServerRequest,
HttpServerResponse
} from "effect/unstable/http"
import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization"
import * as RpcServer from "effect/unstable/rpc/RpcServer"
import * as Stream from "effect/Stream"
import {
ClientMessage,
routeClientMessage,
ServerMessage
} from "./messages.ts"
import { ServerConfig } from "./config.ts"
import { WsRpcGroup } from "./contracts.ts"
import { TodoStore, layerTodoStore } from "./model-store.ts"
import { MigrationsLive } from "./migrations.ts"
const respondMessage = HttpServerResponse.schemaJson(ServerMessage)
const messageDispatchRoute = HttpRouter.add(
"POST",
"/api/dispatch",
HttpServerRequest.schemaBodyJson(ClientMessage).pipe(
Effect.flatMap((message) => respondMessage(routeClientMessage(message))),
Effect.catchTag(
"SchemaError",
() => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid message schema" }, { status: 400 }))
),
Effect.catchTag(
"HttpServerError",
() => Effect.succeed(HttpServerResponse.jsonUnsafe({ kind: "error", error: "Invalid request body" }, { status: 400 }))
)
)
)
const websocketRpcRoute = RpcServer.layerHttp({
group: WsRpcGroup,
path: "/ws",
protocol: "websocket"
}).pipe(
Layer.provide(WsRpcGroup.toLayer({
echo: ({ text }) => Effect.succeed({ text }),
sum: ({ left, right }) => Effect.succeed({ total: left + right }),
time: () => Effect.sync(() => ({ iso: new Date().toISOString() })),
listTodos: ({ includeArchived }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.list({ includeArchived })),
renameTodo: ({ id, title }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.rename({ id, title })),
completeTodo: ({ id, completed }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.complete({ id, completed })),
archiveTodo: ({ id, archived }) =>
Effect.flatMap(Effect.service(TodoStore), (store) => store.archive({ id, archived })),
subscribeTodos: ({ fromOffset, includeArchived }) =>
Stream.unwrap(
Effect.map(
Effect.service(TodoStore),
(store) => store.subscribe({ fromOffset, includeArchived })
)
)
})),
Layer.provide(layerTodoStore),
Layer.provide(RpcSerialization.layerJson)
)
const staticRoute = HttpRouter.add(
"GET",
"*",
(request) =>
Effect.gen(function*() {
const fs = yield* FileSystem.FileSystem
const path = yield* Path.Path
const config = yield* ServerConfig
const url = HttpServerRequest.toURL(request)
if (!url) {
return HttpServerResponse.text("Bad Request", { status: 400 })
}
if (config.frontendDevOrigin) {
return HttpServerResponse.redirect(
new URL(`${url.pathname}${url.search}`, config.frontendDevOrigin),
{
status: 307,
headers: { "cache-control": "no-store" }
}
)
}
const root = path.resolve(config.assetsDir)
const decodedPath = decodeURIComponent(url.pathname)
const target = decodedPath === "/"
? "index.html"
: decodedPath.endsWith("/")
? `${decodedPath.slice(1)}index.html`
: decodedPath.slice(1)
const normalizedTarget = path.normalize(target)
const absoluteTarget = path.resolve(root, normalizedTarget)
const relativeToRoot = path.relative(root, absoluteTarget)
if (relativeToRoot.startsWith("..") || path.isAbsolute(relativeToRoot)) {
return HttpServerResponse.text("Forbidden", { status: 403 })
}
const exists = yield* fs.exists(absoluteTarget)
if (!exists) {
return HttpServerResponse.text("Not Found", { status: 404 })
}
return yield* HttpServerResponse.file(absoluteTarget)
}).pipe(Effect.catchCause(() => Effect.succeed(HttpServerResponse.text("Bad Request", { status: 400 }))))
)
export const makeRoutesLayer =
Layer.mergeAll(
HttpRouter.add(
"GET",
"/health",
HttpServerResponse.json({ ok: true })
),
messageDispatchRoute,
websocketRpcRoute,
staticRoute
)
export const makeServerLayer = Layer.unwrap(
Effect.gen(function*() {
const config = yield* ServerConfig
const sqliteLayer = SqliteNode.SqliteClient.layer({
filename: config.dbFilename
})
const persistenceLayer = MigrationsLive.pipe(
Layer.provideMerge(sqliteLayer)
)
return HttpRouter.serve(makeRoutesLayer, {
disableLogger: !config.requestLogging
}).pipe(
Layer.provideMerge(persistenceLayer),
Layer.provide(NodeHttpServer.layer(Http.createServer, {
host: config.host,
port: config.port
}))
)
})
)
export const runServer = Layer.launch(makeServerLayer)
-79
View File
@@ -1,79 +0,0 @@
import { describe, expect, it } from "@effect/vitest"
import * as ConfigProvider from "effect/ConfigProvider"
import * as Effect from "effect/Effect"
import * as Option from "effect/Option"
import { resolveServerConfig } from "../src/cli.ts"
describe("cli config resolution", () => {
it.effect("falls back to effect/config values when flags are omitted", () =>
Effect.gen(function*() {
const resolved = yield* resolveServerConfig({
host: Option.none(),
port: Option.none(),
assets: Option.none(),
db: Option.none(),
requestLogging: Option.none(),
frontendDevOrigin: Option.none()
}).pipe(
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
HOST: "0.0.0.0",
PORT: "4001",
ASSETS_DIR: "public",
DB_FILENAME: "dev.sqlite",
REQUEST_LOGGING: "false",
FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173"
}
})
)
)
expect(resolved).toEqual({
host: "0.0.0.0",
port: 4001,
assetsDir: "public",
dbFilename: "dev.sqlite",
requestLogging: false,
frontendDevOrigin: "http://127.0.0.1:5173"
})
})
)
it.effect("uses CLI flags when provided", () =>
Effect.gen(function*() {
const resolved = yield* resolveServerConfig({
host: Option.some("127.0.0.1"),
port: Option.some(8788),
assets: Option.some("public"),
db: Option.some("override.sqlite"),
requestLogging: Option.some(true),
frontendDevOrigin: Option.some("http://127.0.0.1:4173")
}).pipe(
Effect.provideService(
ConfigProvider.ConfigProvider,
ConfigProvider.fromEnv({
env: {
HOST: "0.0.0.0",
PORT: "4001",
ASSETS_DIR: "other",
DB_FILENAME: "ignored.sqlite",
REQUEST_LOGGING: "false",
FRONTEND_DEV_ORIGIN: "http://127.0.0.1:5173"
}
})
)
)
expect(resolved).toEqual({
host: "127.0.0.1",
port: 8788,
assetsDir: "public",
dbFilename: "override.sqlite",
requestLogging: true,
frontendDevOrigin: "http://127.0.0.1:4173"
})
})
)
})
-90
View File
@@ -1,90 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices"
import * as SqliteNode from "@effect/sql-sqlite-node"
import { describe, expect, it } from "@effect/vitest"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import * as FileSystem from "node:fs"
import * as OS from "node:os"
import * as NodePath from "node:path"
import { resetDatabase } from "../src/cli.ts"
import { MigrationsLive } from "../src/migrations.ts"
const countRows = (dbFilename: string, tableName: string) =>
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) =>
sql<{ readonly count: number }>`SELECT COUNT(*) AS count FROM ${sql(tableName)}`.pipe(
Effect.map((rows) => rows[0]?.count ?? 0)
)
).pipe(
Effect.provide(SqliteNode.SqliteClient.layer({ filename: dbFilename }))
)
const insertTodo = (dbFilename: string) =>
Effect.scoped(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const now = new Date().toISOString()
const id = "todo-reset-test"
const title = "before-reset"
return sql.withTransaction(
sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${id}, ${title}, 0, 0, 1, ${now})
`.pipe(
Effect.flatMap(() =>
sql`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (
${now},
${JSON.stringify({
id,
title,
completed: false,
archived: false,
revision: 1,
updatedAt: now
})},
${JSON.stringify({ _tag: "TodoCreated" })},
0
)
`
)
)
)
}).pipe(
Effect.provide(MigrationsLive.pipe(Layer.provideMerge(SqliteNode.SqliteClient.layer({ filename: dbFilename }))))
)
)
describe("reset command", () => {
it.effect("deletes the database and reruns migrations without reseeding todos", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-reset-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename)
const beforeCount = yield* countRows(dbFilename, "todos")
expect(beforeCount).toBe(1)
yield* resetDatabase(dbFilename).pipe(
Effect.provide(NodeServices.layer)
)
const todoCount = yield* countRows(dbFilename, "todos")
const migrationCount = yield* countRows(dbFilename, "effect_sql_migrations")
expect(todoCount).toBe(0)
expect(migrationCount).toBe(1)
yield* Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
})
)
})
-310
View File
@@ -1,310 +0,0 @@
import { NodeHttpServer } from "@effect/platform-node"
import * as SqliteNode from "@effect/sql-sqlite-node"
import { describe, expect, it } from "@effect/vitest"
import * as Effect from "effect/Effect"
import * as Layer from "effect/Layer"
import * as Stream from "effect/Stream"
import * as FileSystem from "node:fs"
import * as OS from "node:os"
import * as NodePath from "node:path"
import {
HttpBody,
HttpClient,
HttpClientResponse,
HttpServer,
HttpRouter
} from "effect/unstable/http"
import * as SqlClient from "effect/unstable/sql/SqlClient"
import { ServerConfig } from "../src/config.ts"
import { MigrationsLive } from "../src/migrations.ts"
import { ServerMessage } from "../src/messages.ts"
import { withWsRpcClient } from "../src/client.ts"
import { makeRoutesLayer } from "../src/server.ts"
const testServerConfig = {
host: "127.0.0.1",
port: 0,
assetsDir: new URL("../../public", import.meta.url).pathname,
dbFilename: ":memory:",
requestLogging: false,
frontendDevOrigin: undefined
}
const AppUnderTest = HttpRouter.serve(
makeRoutesLayer,
{
disableListenLog: true,
disableLogger: true
}
)
const persistenceLayer = (dbFilename: string) => {
const sqliteLayer = SqliteNode.SqliteClient.layer({ filename: dbFilename })
return MigrationsLive.pipe(Layer.provideMerge(sqliteLayer))
}
const appLayer = (dbFilename: string) =>
AppUnderTest.pipe(Layer.provideMerge(persistenceLayer(dbFilename)))
const insertTodo = (dbFilename: string, id: string, title: string) =>
Effect.scoped(
Effect.flatMap(Effect.service(SqlClient.SqlClient), (sql) => {
const now = new Date().toISOString()
return sql.withTransaction(
sql`
INSERT INTO todos (id, title, completed, archived, revision, updated_at)
VALUES (${id}, ${title}, 0, 0, 1, ${now})
`.pipe(
Effect.flatMap(() =>
sql`
INSERT INTO todo_events (at, todo_json, change_json, archived)
VALUES (
${now},
${JSON.stringify({
id,
title,
completed: false,
archived: false,
revision: 1,
updatedAt: now
})},
${JSON.stringify({ _tag: "TodoCreated" })},
0
)
`
)
)
)
}).pipe(
Effect.provide(persistenceLayer(dbFilename))
)
)
describe("server", () => {
it.effect("routes HTTP messages validated by Schema", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const client = yield* HttpClient.HttpClient
const response = yield* client.post("/api/dispatch", {
body: HttpBody.jsonUnsafe({ kind: "sum", left: 20, right: 22 })
})
const parsed = yield* HttpClientResponse.schemaBodyJson(ServerMessage)(response)
expect(parsed).toEqual({ kind: "sumResult", total: 42 })
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("serves static files from local filesystem", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const text = yield* HttpClient.get("/").pipe(
Effect.flatMap((response) => response.text)
)
expect(text).toContain("effect-http-ws-cli")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("redirects frontend requests to the Vite dev server when enabled", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
frontendDevOrigin: "http://127.0.0.1:5173"
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const response = yield* Effect.promise(() =>
fetch(`http://127.0.0.1:${address.port}/todos?filter=active`, {
redirect: "manual"
})
)
expect(response.status).toBe(307)
expect(response.headers.get("location")).toBe("http://127.0.0.1:5173/todos?filter=active")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("routes WebSocket RPC messages with shared contracts", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
const response = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) => client.echo({ text: "hello from ws" }))
)
expect(response).toEqual({ text: "hello from ws" })
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("routes WebSocket RPC calls for multiple procedures", () =>
Effect.gen(function*() {
yield* Layer.build(appLayer(testServerConfig.dbFilename)).pipe(
Effect.provideService(ServerConfig, testServerConfig)
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
const result = yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.all({
sum: client.sum({ left: 1, right: 2 }),
time: client.time(undefined)
})
)
)
expect(result.sum).toEqual({ total: 3 })
expect(typeof result.time.iso).toBe("string")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("lists todos and streams todo updates from offset", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-stream-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename, "todo-stream-test", "stream-seed")
const events = yield* Effect.scoped(
Effect.gen(function*() {
yield* Layer.build(appLayer(dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
dbFilename
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
return yield* withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const firstTodo = snapshot.todos[0]
if (!firstTodo) {
return yield* Effect.die("Expected a todo fixture")
}
yield* client.renameTodo({ id: firstTodo.id, title: "alpha" })
yield* client.completeTodo({ id: firstTodo.id, completed: true })
yield* client.archiveTodo({ id: firstTodo.id, archived: true })
return yield* client.subscribeTodos({
fromOffset: snapshot.offset,
includeArchived: true
}).pipe(
Stream.take(3),
Stream.runCollect
)
})
)
})
).pipe(
Effect.ensuring(
Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
)
)
expect(events).toHaveLength(3)
expect(events[0]?.change).toEqual({ _tag: "TodoRenamed", title: "alpha" })
expect(events[1]?.change).toEqual({ _tag: "TodoCompleted", completed: true })
expect(events[2]?.change).toEqual({ _tag: "TodoArchived", archived: true })
expect(events[0]?.todo.title).toBe("alpha")
expect(events[1]?.todo.completed).toBe(true)
expect(events[2]?.todo.archived).toBe(true)
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
it.effect("persists todos across server restarts when using a file database", () =>
Effect.gen(function*() {
const dbFilename = NodePath.join(
OS.tmpdir(),
`effect-http-ws-cli-${Date.now()}-${Math.random().toString(16).slice(2)}.sqlite`
)
yield* insertTodo(dbFilename, "todo-persist-test", "persist-seed")
const withServer = <A, E, R>(f: (wsUrl: string) => Effect.Effect<A, E, R>) =>
Effect.scoped(
Effect.gen(function*() {
yield* Layer.build(appLayer(dbFilename)).pipe(
Effect.provideService(ServerConfig, {
...testServerConfig,
dbFilename
})
)
const server = yield* HttpServer.HttpServer
const address = server.address as HttpServer.TcpAddress
const wsUrl = `ws://127.0.0.1:${address.port}/ws`
return yield* f(wsUrl)
})
)
const renamedTodoId = yield* withServer((wsUrl) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const firstTodo = snapshot.todos[0]
if (!firstTodo) {
return yield* Effect.die("Expected a todo fixture")
}
yield* client.renameTodo({ id: firstTodo.id, title: "persisted-title" })
return firstTodo.id
})
)
)
)
const persistedTitle = yield* withServer((wsUrl) =>
Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
Effect.gen(function*() {
const snapshot = yield* client.listTodos({ includeArchived: true })
const persisted = snapshot.todos.find((todo) => todo.id === renamedTodoId)
if (!persisted) {
return yield* Effect.die("Expected persisted todo")
}
return persisted.title
})
)
)
).pipe(
Effect.ensuring(
Effect.sync(() => {
try {
FileSystem.rmSync(dbFilename, { force: true })
} catch {
// ignore cleanup failures in tests
}
})
)
)
expect(persistedTitle).toBe("persisted-title")
}).pipe(Effect.provide(NodeHttpServer.layerTest))
)
})
-4
View File
@@ -1,4 +0,0 @@
{
"extends": "../tsconfig.json",
"include": ["src", "test", "vitest.config.ts"]
}
-8
View File
@@ -1,8 +0,0 @@
import { defineConfig } from "vitest/config"
export default defineConfig({
test: {
include: ["test/**/*.test.ts"],
environment: "node"
}
})
+2 -2
View File
@@ -7,7 +7,7 @@
## Project Snapshot
T3 Code is a minimal web GUI for using 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
View File
@@ -8,7 +8,7 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status.
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
View File
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new 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 -1
View File
@@ -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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.9",
"version": "0.0.10",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+3 -2
View File
@@ -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();
}
});
-15
View File
@@ -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.
}
}
+26 -4
View File
@@ -28,7 +28,7 @@ import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { 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),
];
@@ -1298,7 +1320,7 @@ async function bootstrap(): Promise<void> {
);
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
backendAuthToken = Crypto.randomBytes(24).toString("hex");
backendWsUrl = `ws://127.0.0.1:${backendPort}/ws?token=${encodeURIComponent(backendAuthToken)}`;
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
@@ -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");
});
});
+29
View File
@@ -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.
}
}
+2 -2
View File
@@ -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",
),
);
+6 -5
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.9",
"version": "0.0.10",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
@@ -22,12 +22,14 @@
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.76",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0"
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -40,10 +42,9 @@
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:",
"ws": "^8.18.0"
"vitest": "catalog:"
},
"engines": {
"node": "^22.13 || ^23.4 || >=24.10"
"node": "^22.16 || ^23.11 || >=24.10"
}
}
+40 -1
View File
@@ -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();
+14 -2
View File
@@ -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-");
+13 -2
View File
@@ -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
+1
View File
@@ -101,6 +101,7 @@ export interface GitCoreShape {
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
+66 -56
View File
@@ -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();
@@ -96,7 +96,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 +129,7 @@ describe("ProviderCommandReactor", () => {
: "full-access",
...(model !== undefined ? { model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
createdAt: now,
updatedAt: now,
};
@@ -351,6 +351,72 @@ describe("ProviderCommandReactor", () => {
});
});
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-claude"),
threadId: ThreadId.makeUnsafe("thread-claude"),
projectId: asProjectId("project-1"),
title: "Claude Thread",
model: "claude-sonnet-4-6",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort"),
threadId: ThreadId.makeUnsafe("thread-claude"),
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-claude"),
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
});
it("forwards plan interaction mode to the provider turn request", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -389,6 +455,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 +597,89 @@ describe("ProviderCommandReactor", () => {
expect(harness.stopSession.mock.calls.length).toBe(0);
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-create-claude-restart"),
threadId: ThreadId.makeUnsafe("thread-claude-restart"),
projectId: asProjectId("project-1"),
title: "Claude Restart Thread",
model: "claude-sonnet-4-6",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
worktreePath: null,
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-claude-effort-1"),
threadId: ThreadId.makeUnsafe("thread-claude-restart"),
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-claude-restart"),
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 +754,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 +767,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,13 +295,23 @@ const make = Effect.gen(function* () {
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelOptions = threadModelOptions.get(threadId);
const shouldRestartForModelOptionsChange =
currentProvider === "claudeAgent" &&
options?.modelOptions !== undefined &&
!sameModelOptions(previousModelOptions, options.modelOptions);
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelOptionsChange
) {
return existingSessionThreadId;
}
const resumeCursor =
providerChanged || shouldRestartForModelChange
providerChanged || shouldRestartForModelChange || shouldRestartForModelOptionsChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
@@ -287,6 +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
+86 -96
View File
@@ -1,8 +1,6 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { Effect, Option } from "effect";
import { HttpServerResponse } from "effect/unstable/http";
const FAVICON_MIME_TYPES: Record<string, string> = {
".png": "image/png",
@@ -72,110 +70,102 @@ function isPathWithinProject(projectCwd: string, candidatePath: string): boolean
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
async function isFile(candidatePath: string): Promise<boolean> {
try {
const stats = await fs.promises.stat(candidatePath);
return stats.isFile();
} catch {
return false;
}
}
async function resolveFaviconPath(projectCwd: string): Promise<string | null> {
for (const candidate of FAVICON_CANDIDATES) {
const candidatePath = path.join(projectCwd, candidate);
if (!isPathWithinProject(projectCwd, candidatePath)) {
continue;
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
const ext = path.extname(filePath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Read error");
return;
}
if (await isFile(candidatePath)) {
return candidatePath;
}
}
for (const sourceFile of ICON_SOURCE_FILES) {
const sourceFilePath = path.join(projectCwd, sourceFile);
let content: string;
try {
content = await fs.promises.readFile(sourceFilePath, "utf8");
} catch {
continue;
}
const href = extractIconHref(content);
if (!href) {
continue;
}
const candidates = resolveIconHref(projectCwd, href);
for (const candidatePath of candidates) {
if (!isPathWithinProject(projectCwd, candidatePath)) {
continue;
}
if (await isFile(candidatePath)) {
return candidatePath;
}
}
}
return null;
}
export const handleProjectFaviconRequest = (projectCwd: string | null) =>
Effect.gen(function* () {
if (!projectCwd) {
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
}
const faviconPath = yield* Effect.promise(() => resolveFaviconPath(projectCwd));
if (!faviconPath) {
return HttpServerResponse.text(FALLBACK_FAVICON_SVG, {
contentType: "image/svg+xml",
headers: { "Cache-Control": "public, max-age=3600" },
});
}
const data = yield* Effect.promise(() => fs.promises.readFile(faviconPath)).pipe(Effect.option);
if (Option.isNone(data)) {
return HttpServerResponse.text("Read error", { status: 500 });
}
const ext = path.extname(faviconPath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
return HttpServerResponse.uint8Array(new Uint8Array(data.value), {
contentType,
headers: { "Cache-Control": "public, max-age=3600" },
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
});
res.end(data);
});
}
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
}
void Effect.runPromise(handleProjectFaviconRequest(url.searchParams.get("cwd")))
.then((response) => {
const webResponse = HttpServerResponse.toWeb(response);
res.statusCode = webResponse.status;
for (const [header, value] of webResponse.headers.entries()) {
res.setHeader(header, value);
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing cwd parameter");
return true;
}
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
if (index >= paths.length) {
onExhausted();
return;
}
const candidate = paths[index]!;
if (!isPathWithinProject(projectCwd, candidate)) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
return webResponse
.arrayBuffer()
.then((buffer) => {
res.end(Buffer.from(buffer));
})
.catch(() => {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "text/plain" });
}
res.end("Read error");
});
})
.catch(() => {
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "text/plain" });
}
res.end("Read error");
serveFaviconFile(candidate, res);
});
};
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
serveFallbackFavicon(res);
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
fs.readFile(sourceFile, "utf8", (err, content) => {
if (err) {
trySourceFiles(index + 1);
return;
}
const href = extractIconHref(content);
if (!href) {
trySourceFiles(index + 1);
return;
}
const candidates = resolveIconHref(projectCwd, href);
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
});
};
const tryCandidates = (index: number): void => {
if (index >= FAVICON_CANDIDATES.length) {
trySourceFiles(0);
return;
}
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
if (!isPathWithinProject(projectCwd, candidate)) {
tryCandidates(index + 1);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryCandidates(index + 1);
return;
}
serveFaviconFile(candidate, res);
});
};
tryCandidates(0);
return true;
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -22,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");
});
});
});
+207 -11
View File
@@ -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,58 @@ 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 +668,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 +783,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 +793,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 +848,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>>;
}
+5
View File
@@ -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(
+26
View File
@@ -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"]);
+159 -30
View File
@@ -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 -1
View File
@@ -283,7 +283,7 @@ function asWebSocketResponse(message: unknown): WebSocketResponse | null {
function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
return new Promise((resolve, reject) => {
const query = token ? `?token=${encodeURIComponent(token)}` : "";
const ws = new WebSocket(`ws://127.0.0.1:${port}/ws${query}`);
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
const channels: SocketChannels = {
push: { queue: [], waiters: [] },
response: { queue: [], waiters: [] },
+300 -199
View File
@@ -7,6 +7,7 @@
* @module Server
*/
import http from "node:http";
import type { Duplex } from "node:stream";
import Mime from "@effect/platform-node/Mime";
import {
@@ -27,14 +28,12 @@ import {
type WsPushEnvelopeBase,
} from "@t3tools/contracts";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as Socket from "effect/unstable/socket/Socket";
import {
Cause,
Effect,
Exit,
FileSystem,
Layer,
Option,
Path,
Ref,
Result,
@@ -44,7 +43,7 @@ import {
Stream,
Struct,
} from "effect";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import { WebSocketServer, type WebSocket } from "ws";
import { createLogger } from "./logger";
import { GitManager } from "./git/Services/GitManager.ts";
@@ -61,7 +60,7 @@ import { clamp } from "effect/Number";
import { Open, resolveAvailableEditors } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { handleProjectFaviconRequest } from "./projectFaviconRoute";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
import {
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
@@ -76,7 +75,7 @@ import {
import { parseBase64DataUrl } from "./imageMime.ts";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
import { expandHomePath } from "./os-jank.ts";
import { makeServerPushBus, type ServerPushClient } from "./wsServer/pushBus.ts";
import { makeServerPushBus } from "./wsServer/pushBus.ts";
import { makeServerReadiness } from "./wsServer/readiness.ts";
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
@@ -104,11 +103,54 @@ export interface ServerShape {
*/
export class Server extends ServiceMap.Service<Server, ServerShape>()("t3/wsServer/Server") {}
function websocketRawToString(raw: string | Uint8Array): string {
const isServerNotRunningError = (error: Error): boolean => {
const maybeCode = (error as NodeJS.ErrnoException).code;
return (
maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
);
};
function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
socket.end(
`HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
"Connection: close\r\n" +
"Content-Type: text/plain\r\n" +
`Content-Length: ${Buffer.byteLength(message)}\r\n` +
"\r\n" +
message,
);
}
function websocketRawToString(raw: unknown): string | null {
if (typeof raw === "string") {
return raw;
}
return Buffer.from(raw).toString("utf8");
if (raw instanceof Uint8Array) {
return Buffer.from(raw).toString("utf8");
}
if (raw instanceof ArrayBuffer) {
return Buffer.from(new Uint8Array(raw)).toString("utf8");
}
if (Array.isArray(raw)) {
const chunks: string[] = [];
for (const chunk of raw) {
if (typeof chunk === "string") {
chunks.push(chunk);
continue;
}
if (chunk instanceof Uint8Array) {
chunks.push(Buffer.from(chunk).toString("utf8"));
continue;
}
if (chunk instanceof ArrayBuffer) {
chunks.push(Buffer.from(new Uint8Array(chunk)).toString("utf8"));
continue;
}
return null;
}
return chunks.join("");
}
return null;
}
function toPosixRelativePath(input: string): string {
@@ -228,7 +270,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const providerStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<ServerPushClient>());
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
const readiness = yield* makeServerReadiness;
@@ -368,130 +410,191 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
} satisfies OrchestrationCommand;
});
const serveHttpRequest = Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (!url) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
// HTTP server — serves static files or redirects to Vite dev server
const httpServer = http.createServer((req, res) => {
const respond = (
statusCode: number,
headers: Record<string, string>,
body?: string | Uint8Array,
) => {
res.writeHead(statusCode, headers);
res.end(body);
};
if (url.pathname === "/api/project-favicon") {
return yield* handleProjectFaviconRequest(url.searchParams.get("cwd"));
}
void Effect.runPromise(
Effect.gen(function* () {
const url = new URL(req.url ?? "/", `http://localhost:${port}`);
if (tryHandleProjectFaviconRequest(url, res)) {
return;
}
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
if (!normalizedRelativePath) {
return HttpServerResponse.text("Invalid attachment path", { status: 400 });
}
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
if (!normalizedRelativePath) {
respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
return;
}
const isIdLookup =
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
stateDir: serverConfig.stateDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
stateDir: serverConfig.stateDir,
relativePath: normalizedRelativePath,
const isIdLookup =
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
stateDir: serverConfig.stateDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
stateDir: serverConfig.stateDir,
relativePath: normalizedRelativePath,
});
if (!filePath) {
respond(
isIdLookup ? 404 : 400,
{ "Content-Type": "text/plain" },
isIdLookup ? "Not Found" : "Invalid attachment path",
);
return;
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
respond(404, { "Content-Type": "text/plain" }, "Not Found");
return;
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=31536000, immutable",
});
if (!filePath) {
return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
status: isIdLookup ? 404 : 400,
});
const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
Effect.sync(() => {
if (!res.destroyed) {
res.write(chunk);
}
}),
).pipe(Effect.exit);
if (Exit.isFailure(streamExit)) {
if (!res.destroyed) {
res.destroy();
}
return;
}
if (!res.writableEnded) {
res.end();
}
return;
}
// In dev mode, redirect to Vite dev server
if (devUrl) {
respond(302, { Location: devUrl.href });
return;
}
// Serve static files from the web app build
if (!staticDir) {
respond(
503,
{ "Content-Type": "text/plain" },
"No static directory configured and no dev URL set.",
);
return;
}
const staticRoot = path.resolve(staticDir);
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
if (
staticRelativePath.length === 0 ||
hasRawLeadingParentSegment ||
hasPathTraversalSegment ||
staticRelativePath.includes("\0")
) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
const isWithinStaticRoot = (candidate: string) =>
candidate === staticRoot ||
candidate.startsWith(
staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
);
let filePath = path.resolve(staticRoot, staticRelativePath);
if (!isWithinStaticRoot(filePath)) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
const ext = path.extname(filePath);
if (!ext) {
filePath = path.resolve(filePath, "index.html");
if (!isWithinStaticRoot(filePath)) {
respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
return;
}
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
const indexPath = path.resolve(staticRoot, "index.html");
const indexData = yield* fileSystem
.readFile(indexPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!indexData) {
respond(404, { "Content-Type": "text/plain" }, "Not Found");
return;
}
respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
return;
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
return;
}
respond(200, { "Content-Type": contentType }, data);
}),
).catch(() => {
if (!res.headersSent) {
respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
return HttpServerResponse.text("Not Found", { status: 404 });
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
return HttpServerResponse.text("Internal Server Error", { status: 500 });
}
return HttpServerResponse.uint8Array(data, {
contentType,
headers: { "Cache-Control": "public, max-age=31536000, immutable" },
});
}
if (devUrl) {
return HttpServerResponse.redirect(devUrl.href, { status: 302 });
}
if (!staticDir) {
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
status: 503,
});
}
const staticRoot = path.resolve(staticDir);
const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
if (
staticRelativePath.length === 0 ||
hasRawLeadingParentSegment ||
hasPathTraversalSegment ||
staticRelativePath.includes("\0")
) {
return HttpServerResponse.text("Invalid static file path", { status: 400 });
}
const isWithinStaticRoot = (candidate: string) =>
candidate === staticRoot ||
candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
let filePath = path.resolve(staticRoot, staticRelativePath);
if (!isWithinStaticRoot(filePath)) {
return HttpServerResponse.text("Invalid static file path", { status: 400 });
}
const ext = path.extname(filePath);
if (!ext) {
filePath = path.resolve(filePath, "index.html");
if (!isWithinStaticRoot(filePath)) {
return HttpServerResponse.text("Invalid static file path", { status: 400 });
}
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
const indexPath = path.resolve(staticRoot, "index.html");
const indexData = yield* fileSystem
.readFile(indexPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!indexData) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
return HttpServerResponse.uint8Array(indexData, {
contentType: "text/html; charset=utf-8",
});
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
return HttpServerResponse.text("Internal Server Error", { status: 500 });
}
return HttpServerResponse.uint8Array(data, { contentType });
});
});
const httpServer = http.createServer();
// WebSocket server — upgrades from the HTTP server
const wss = new WebSocketServer({ noServer: true });
const closeWebSocketServer = Effect.callback<void, ServerLifecycleError>((resume) => {
wss.close((error) => {
if (error && !isServerNotRunningError(error)) {
resume(
Effect.fail(
new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }),
),
);
} else {
resume(Effect.void);
}
});
});
const closeAllClients = Ref.get(clients).pipe(
Effect.flatMap(Effect.forEach((client) => Effect.sync(() => client.close()))),
Effect.flatMap(() => Ref.set(clients, new Set())),
);
const listenOptions = host ? { host, port } : { port };
@@ -587,11 +690,20 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const runPromise = Effect.runPromiseWith(runtimeServices);
const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
(event) => void runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
(event) => void Effect.runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
);
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* readiness.markTerminalSubscriptionsReady;
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
);
yield* readiness.markHttpListening;
yield* Effect.addFinalizer(() =>
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
);
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
switch (request.body._tag) {
case ORCHESTRATION_WS_METHODS.getSnapshot:
@@ -780,17 +892,21 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}
});
const handleMessage = Effect.fnUntraced(function* (
client: ServerPushClient,
raw: string | Uint8Array,
) {
const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) {
const sendWsResponse = (response: WsResponseMessage) =>
encodeWsResponse(response).pipe(
Effect.flatMap((encodedResponse) => client.send(encodedResponse)),
Effect.tap((encodedResponse) => Effect.sync(() => ws.send(encodedResponse))),
Effect.asVoid,
);
const messageText = websocketRawToString(raw);
if (messageText === null) {
return yield* sendWsResponse({
id: "unknown",
error: { message: "Invalid request format: Failed to read message" },
});
}
const request = decodeWebSocketRequest(messageText);
if (Result.isFailure(request)) {
return yield* sendWsResponse({
@@ -813,22 +929,31 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
});
const handleWebSocketConnection = Effect.fnUntraced(function* (socket: Socket.Socket) {
const writer = yield* socket.writer;
const client: ServerPushClient = {
send: (message) =>
writer(message).pipe(
Effect.as(true),
Effect.catch(() => Effect.succeed(false)),
),
};
yield* Effect.addFinalizer(() =>
Ref.update(clients, (currentClients) => {
currentClients.delete(client);
return currentClients;
}),
);
httpServer.on("upgrade", (request, socket, head) => {
socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
if (authToken) {
let providedToken: string | null = null;
try {
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
providedToken = url.searchParams.get("token");
} catch {
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
return;
}
if (providedToken !== authToken) {
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
return;
}
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit("connection", ws, request);
});
});
wss.on("connection", (ws) => {
const segments = cwd.split(/[/\\]/).filter(Boolean);
const projectName = segments[segments.length - 1] ?? "project";
@@ -838,63 +963,39 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
};
yield* socket
.runRaw((raw) => handleMessage(client, raw).pipe(Effect.ignoreCause({ log: true })), {
onOpen: readiness.awaitServerReady.pipe(
Effect.flatMap(() =>
pushBus.publishClient(client, WS_CHANNELS.serverWelcome, welcomeData),
),
Effect.flatMap((delivered) =>
delivered
? Ref.update(clients, (currentClients) => currentClients.add(client))
: Effect.void,
),
// Send welcome before adding to broadcast set so publishAll calls
// cannot reach this client before the welcome arrives.
void runPromise(
readiness.awaitServerReady.pipe(
Effect.flatMap(() => pushBus.publishClient(ws, WS_CHANNELS.serverWelcome, welcomeData)),
Effect.flatMap((delivered) =>
delivered ? Ref.update(clients, (clients) => clients.add(ws)) : Effect.void,
),
})
.pipe(Effect.catchReason("SocketError", "SocketCloseError", () => Effect.void));
});
const websocketRoute = Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (!url) {
return HttpServerResponse.text("Invalid WebSocket URL", { status: 400 });
}
if (authToken && url.searchParams.get("token") !== authToken) {
return HttpServerResponse.text("Unauthorized WebSocket connection", { status: 401 });
}
const socket = yield* request.upgrade.pipe(Effect.option);
if (Option.isNone(socket)) {
return HttpServerResponse.text("WebSocket upgrade required", { status: 400 });
}
yield* handleWebSocketConnection(socket.value);
return HttpServerResponse.empty();
});
const router = yield* HttpRouter.make;
yield* Effect.orDie(router.add("GET", "/ws", websocketRoute) as Effect.Effect<void>);
yield* Effect.orDie(router.add("GET", "*", serveHttpRequest) as Effect.Effect<void>);
const httpApp: Effect.Effect<
HttpServerResponse.HttpServerResponse,
never,
HttpServerRequest.HttpServerRequest | Scope.Scope
> = router
.asHttpEffect()
.pipe(
Effect.catchCause(() =>
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
);
const nodeHttpServer = yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
);
yield* nodeHttpServer.serve(httpApp);
yield* readiness.markHttpListening;
yield* Effect.addFinalizer(() => Ref.set(clients, new Set()));
ws.on("message", (raw) => {
void runPromise(handleMessage(ws, raw).pipe(Effect.ignoreCause({ log: true })));
});
ws.on("close", () => {
void runPromise(
Ref.update(clients, (clients) => {
clients.delete(ws);
return clients;
}),
);
});
ws.on("error", () => {
void runPromise(
Ref.update(clients, (clients) => {
clients.delete(ws);
return clients;
}),
);
});
});
return httpServer;
});
+24 -17
View File
@@ -1,22 +1,25 @@
import type { WebSocket } from "ws";
import { it } from "@effect/vitest";
import { describe, expect } from "vitest";
import { Effect, Ref } from "effect";
import { WS_CHANNELS } from "@t3tools/contracts";
import { makeServerPushBus, type ServerPushClient } from "./pushBus";
import { makeServerPushBus } from "./pushBus";
class MockPushClient implements ServerPushClient {
class MockWebSocket {
static readonly OPEN = 1;
readonly OPEN = MockWebSocket.OPEN;
readyState = MockWebSocket.OPEN;
readonly sent: string[] = [];
private readonly waiters = new Set<() => void>();
readonly send: ServerPushClient["send"] = (message: string) =>
Effect.sync(() => {
this.sent.push(message);
for (const waiter of this.waiters) {
waiter();
}
return true;
});
send(message: string) {
this.sent.push(message);
for (const waiter of this.waiters) {
waiter();
}
}
waitForSentCount(count: number): Promise<void> {
if (this.sent.length >= count) {
@@ -41,8 +44,8 @@ describe("makeServerPushBus", () => {
it.live("waits for the welcome push before a new client joins broadcast delivery", () =>
Effect.scoped(
Effect.gen(function* () {
const client = new MockPushClient();
const clients = yield* Ref.make(new Set<ServerPushClient>());
const client = new MockWebSocket();
const clients = yield* Ref.make(new Set<WebSocket>());
const pushBus = yield* makeServerPushBus({
clients,
logOutgoingPush: () => {},
@@ -53,13 +56,17 @@ describe("makeServerPushBus", () => {
providers: [],
});
const delivered = yield* pushBus.publishClient(client, WS_CHANNELS.serverWelcome, {
cwd: "/tmp/project",
projectName: "project",
});
const delivered = yield* pushBus.publishClient(
client as unknown as WebSocket,
WS_CHANNELS.serverWelcome,
{
cwd: "/tmp/project",
projectName: "project",
},
);
expect(delivered).toBe(true);
yield* Ref.update(clients, (current) => current.add(client));
yield* Ref.update(clients, (current) => current.add(client as unknown as WebSocket));
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: [],
+17 -18
View File
@@ -6,14 +6,11 @@ import {
} from "@t3tools/contracts";
import { Deferred, Effect, Queue, Ref, Schema } from "effect";
import type { Scope } from "effect";
export interface ServerPushClient {
readonly send: (message: string) => Effect.Effect<boolean>;
}
import type { WebSocket } from "ws";
type PushTarget =
| { readonly kind: "all" }
| { readonly kind: "client"; readonly client: ServerPushClient };
| { readonly kind: "client"; readonly client: WebSocket };
interface PushJob<C extends WsPushChannel = WsPushChannel> {
readonly channel: C;
@@ -28,14 +25,14 @@ export interface ServerPushBus {
data: WsPushData<C>,
) => Effect.Effect<void>;
readonly publishClient: <C extends WsPushChannel>(
client: ServerPushClient,
client: WebSocket,
channel: C,
data: WsPushData<C>,
) => Effect.Effect<boolean>;
}
export const makeServerPushBus = (input: {
readonly clients: Ref.Ref<Set<ServerPushClient>>;
readonly clients: Ref.Ref<Set<WebSocket>>;
readonly logOutgoingPush: (push: WsPushEnvelopeBase, recipients: number) => void;
}): Effect.Effect<ServerPushBus, never, Scope.Scope> =>
Effect.gen(function* () {
@@ -60,17 +57,19 @@ export const makeServerPushBus = (input: {
job.target.kind === "all" ? yield* Ref.get(input.clients) : new Set([job.target.client]);
return yield* encodePush(push).pipe(
Effect.flatMap((message) =>
Effect.forEach(recipients, (client) => client.send(message), {
concurrency: "unbounded",
}).pipe(
Effect.map((deliveries) => {
const recipientCount = deliveries.filter(Boolean).length;
input.logOutgoingPush(push, recipientCount);
return recipientCount > 0;
}),
),
),
Effect.map((message) => {
let recipientCount = 0;
for (const client of recipients) {
if (client.readyState !== client.OPEN) {
continue;
}
client.send(message);
recipientCount += 1;
}
input.logOutgoingPush(push, recipientCount);
return recipientCount > 0;
}),
);
});
+5 -3
View File
@@ -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"
}
+26 -12
View File
@@ -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
View File
@@ -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,
+51 -18
View File
@@ -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}
+9 -8
View File
@@ -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.");
}
+166 -3
View File
@@ -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,
+127
View File
@@ -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),
};
}
File diff suppressed because it is too large. Load diff
+161 -28
View File
@@ -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);
});
}, []);
+20 -41
View File
@@ -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>
);
}
+130 -26
View File
@@ -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>
+10 -1
View File
@@ -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)">
+10 -8
View File
@@ -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");
});
});
+40
View File
@@ -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;
+53 -181
View File
@@ -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;
}
+124
View File
@@ -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,115 @@
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;
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.provider === "codex" && 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.provider === "codex" && 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,148 @@
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;
selectedCodexFastModeEnabled: boolean;
reasoningOptions: ReadonlyArray<ProviderReasoningEffort>;
onEffortSelect: (effort: ProviderReasoningEffort) => void;
onCodexFastModeChange: (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.selectedProvider === "codex" ? (
<>
<MenuDivider />
<MenuGroup>
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
Fast Mode
</div>
<MenuRadioGroup
value={props.selectedCodexFastModeEnabled ? "on" : "off"}
onValueChange={(value) => {
props.onCodexFastModeChange(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>
);
});
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more