Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex bbb88d1f6b Merge origin/main into statemachine
Co-authored-by: codex <[email protected]>
2026-03-09 11:22:43 -07:00
Jason Laster 3faa32a0d6 Stabilize runtime orchestration and fix flaky CI tests
Add typed websocket push envelopes with ordered sequence numbers,
structured decode diagnostics, and a client transport state machine.

On the server, route pushes through a shared push bus, gate welcome
delivery on explicit readiness barriers, and make keybindings startup
an explicit runtime with start/ready lifecycle.

Fix the flaky keybindings watcher test on Linux CI:
- Subscribe eagerly via PubSub.subscribe instead of lazy
  Stream.fromPubSub to avoid missing events before the fiber
  is scheduled.
- Replace the hand-rolled Effect.sleep polling loop with
  fs.watchFile (Node's built-in stat-based poller on libuv
  timers) so file change detection is reliable regardless of
  Effect fiber scheduling pressure.

Add orchestration runtime receipts for checkpoint baseline capture,
checkpoint diff finalization, and turn quiescence, then update the
integration harness/tests to wait on those receipts instead of
timing-sensitive polling.

Use DrainableWorker for queue-based reactors so unit tests can
deterministically drain() instead of sleeping.

Adopt idiomatic Effect patterns: Effect.ignoreCause({ log: true })
for log-and-ignore error handling, Effect.tapCause for side-effecting
on errors before ignoring.
2026-03-08 18:13:15 -07:00
Jason Laster adf3f3b44c Fix test runner parity with CI 2026-03-08 18:12:57 -07:00
455 changed files with 21535 additions and 68088 deletions

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --base-dir ~/.t3-2`
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
-2
View File
@@ -1,2 +0,0 @@
# git autocrlf=true converts LF to CRLF on Windows, causing issues with oxfmt
* text=auto eol=lf
-117
View File
@@ -1,117 +0,0 @@
name: Bug report
description: Report broken behavior, regressions, crashes, or reliability issues.
title: "[Bug]: "
labels:
- bug
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for broken behavior, regressions, crashes, or reliability problems.
Search existing issues first and keep the report focused on one problem.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I included enough detail to reproduce or investigate the problem.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project is affected?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: steps
attributes:
label: Steps to reproduce
description: Provide a minimal, deterministic repro.
placeholder: |
1. Start the app with ...
2. Open ...
3. Disconnect the network
4. Reconnect and send another prompt
validations:
required: true
- type: textarea
id: expected
attributes:
label: Expected behavior
placeholder: The thread should resume normally and accept the new message.
validations:
required: true
- type: textarea
id: actual
attributes:
label: Actual behavior
placeholder: The composer clears, no new turn starts, and the session stays in a pending state.
validations:
required: true
- type: dropdown
id: impact
attributes:
label: Impact
description: How bad is this in practice?
options:
- Blocks work completely
- Major degradation or frequent failure
- Minor bug or occasional failure
- Cosmetic issue
validations:
required: true
- type: input
id: version
attributes:
label: Version or commit
description: Release version, commit SHA, or branch name if known.
placeholder: main @ abc1234
- type: input
id: environment
attributes:
label: Environment
description: OS, browser or desktop app version, Node/Bun version, provider/model if relevant.
placeholder: macOS 15.3, Chrome 135, Bun 1.3.9, Codex app-server ...
- type: textarea
id: logs
attributes:
label: Logs or stack traces
description: Paste the most relevant output only. Redact secrets.
render: shell
- type: upload
id: attachments
attributes:
label: Screenshots, recordings, or supporting files
description: Upload screenshots, short recordings, repro archives, or log files. Redact secrets before uploading.
validations:
required: false
accept: ".png,.jpg,.jpeg,.gif,.webp,.svg,.mp4,.mov,.webm,.log,.txt,.json,.zip"
- type: textarea
id: workaround
attributes:
label: Workaround
description: If you found a temporary workaround, include it.
placeholder: Restarting the provider session clears the stuck state.
-101
View File
@@ -1,101 +0,0 @@
name: Feature request
description: Propose a scoped improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for new capabilities or meaningful improvements to existing behavior.
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I am describing a concrete problem or use case, not just a vague idea.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project would this change affect?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do? What is hard, slow, or impossible today?
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the behavior, API, or UX you want.
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
validations:
required: true
- type: textarea
id: value
attributes:
label: Why this matters
description: Who benefits, and what outcome does this unlock?
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Smallest useful scope
description: What is the narrowest version of this request that would still solve your problem?
placeholder: A first pass only needs to support restoring the active session for the current thread.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Workarounds, prior art, or other approaches you considered.
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
- type: textarea
id: tradeoffs
attributes:
label: Risks or tradeoffs
description: What costs, complexity, or edge cases should be considered?
placeholder: This may require careful handling when the underlying provider session has already exited.
- type: textarea
id: references
attributes:
label: Examples or references
description: Links, screenshots, mockups, or comparable tools.
- type: checkboxes
id: contribution
attributes:
label: Contribution
options:
- label: I would be open to helping implement this.
-4
View File
@@ -19,7 +19,6 @@ github:hwanseoc
github:jamesx0416
github:jasonLaster
github:JoeEverest
github:maria-rcks
github:nmggithub
github:Noojuno
github:notkainoa
@@ -27,6 +26,3 @@ github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
github:shivamhwp
+7 -10
View File
@@ -8,11 +8,11 @@ on:
jobs:
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
name: Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-4vcpu-ubuntu-2404
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -20,12 +20,12 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Cache Bun and Turbo
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: |
~/.bun/install/cache
@@ -35,7 +35,7 @@ jobs:
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
uses: actions/cache@v4
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
@@ -45,9 +45,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
@@ -78,7 +75,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -86,7 +83,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
-75
View File
@@ -1,75 +0,0 @@
name: Issue Labels
on:
push:
branches:
- main
paths:
- .github/ISSUE_TEMPLATE/**
- .github/workflows/issue-labels.yml
workflow_dispatch:
permissions:
issues: write
jobs:
sync:
name: Sync issue labels
runs-on: ubuntu-24.04
steps:
- name: Ensure managed issue labels exist
uses: actions/github-script@v7
with:
script: |
const managedLabels = [
{
name: "bug",
color: "d73a4a",
description: "Something is broken or behaving incorrectly.",
},
{
name: "enhancement",
color: "a2eeef",
description: "Requested improvement or new capability.",
},
{
name: "needs-triage",
color: "fbca04",
description: "Issue needs maintainer review and initial categorization.",
},
];
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
-292
View File
@@ -1,292 +0,0 @@
name: PR Size
on:
pull_request_target:
types: [opened, reopened, synchronize, ready_for_review, converted_to_draft]
permissions:
contents: read
jobs:
prepare-config:
name: Prepare PR size config
runs-on: ubuntu-24.04
outputs:
labels_json: ${{ steps.config.outputs.labels_json }}
steps:
- id: config
name: Build PR size label config
uses: actions/github-script@v8
with:
result-encoding: string
script: |
const managedLabels = [
{
name: "size:XS",
color: "0e8a16",
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
},
];
core.setOutput("labels_json", JSON.stringify(managedLabels));
sync-label-definitions:
name: Sync PR size label definitions
needs: prepare-config
if: github.event_name != 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: write
steps:
- name: Ensure PR size labels exist
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
for (const label of managedLabels) {
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
});
if (
existing.color !== label.color ||
(existing.description ?? "") !== label.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
}
label:
name: Label PR size
needs: prepare-config
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04
permissions:
contents: read
issues: read
pull-requests: write
concurrency:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
- name: Checkout base repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Sync PR size label
uses: actions/github-script@v8
env:
PR_SIZE_LABELS_JSON: ${{ needs.prepare-config.outputs.labels_json }}
with:
script: |
const { execFileSync } = require("node:child_process");
const issueNumber = context.payload.pull_request.number;
const baseSha = context.payload.pull_request.base.sha;
const headSha = context.payload.pull_request.head.sha;
const headTrackingRef = `refs/remotes/pr-size/${issueNumber}`;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
// Keep this aligned with the repo's test entrypoints and test-only support files.
const testExcludePathspecs = [
":(glob,exclude)**/__tests__/**",
":(glob,exclude)**/test/**",
":(glob,exclude)**/tests/**",
":(glob,exclude)apps/server/integration/**",
":(glob,exclude)**/*.test.*",
":(glob,exclude)**/*.spec.*",
":(glob,exclude)**/*.browser.*",
":(glob,exclude)**/*.integration.*",
];
const sumNumstat = (text) =>
text
.split("\n")
.filter(Boolean)
.reduce((total, line) => {
const [insertionsRaw = "0", deletionsRaw = "0"] = line.split("\t");
const additions =
insertionsRaw === "-" ? 0 : Number.parseInt(insertionsRaw, 10) || 0;
const deletions =
deletionsRaw === "-" ? 0 : Number.parseInt(deletionsRaw, 10) || 0;
return total + additions + deletions;
}, 0);
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";
};
execFileSync("git", ["fetch", "--no-tags", "origin", baseSha], {
stdio: "inherit",
});
execFileSync(
"git",
["fetch", "--no-tags", "origin", `+refs/pull/${issueNumber}/head:${headTrackingRef}`],
{
stdio: "inherit",
},
);
const resolvedHeadSha = execFileSync("git", ["rev-parse", headTrackingRef], {
encoding: "utf8",
}).trim();
if (resolvedHeadSha !== headSha) {
core.warning(
`Fetched head SHA ${resolvedHeadSha} does not match pull request head SHA ${headSha}; using fetched ref for sizing.`,
);
}
execFileSync("git", ["cat-file", "-e", `${baseSha}^{commit}`], {
stdio: "inherit",
});
const diffArgs = [
"diff",
"--numstat",
"--ignore-all-space",
"--ignore-blank-lines",
`${baseSha}...${resolvedHeadSha}`,
];
const totalChangedLines = sumNumstat(
execFileSync(
"git",
diffArgs,
{ encoding: "utf8" },
),
);
const nonTestChangedLines = sumNumstat(
execFileSync("git", [...diffArgs, "--", ".", ...testExcludePathspecs], {
encoding: "utf8",
}),
);
const testChangedLines = Math.max(0, totalChangedLines - nonTestChangedLines);
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
const classification =
nonTestChangedLines === 0
? testChangedLines > 0
? "test-only PR"
: "no line changes"
: testChangedLines > 0
? "test lines excluded"
: "all non-test changes";
core.info(
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
);
+19 -43
View File
@@ -25,7 +25,7 @@ jobs:
targets: ${{ steps.collect.outputs.targets }}
steps:
- id: collect
uses: actions/github-script@v8
uses: actions/github-script@v7
with:
script: |
if (context.eventName === "pull_request_target") {
@@ -85,7 +85,7 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Sync PR labels
uses: actions/github-script@v8
uses: actions/github-script@v7
env:
PR_NUMBER: ${{ matrix.target.number }}
VOUCH_STATUS: ${{ steps.vouch.outputs.status }}
@@ -111,7 +111,7 @@ jobs:
},
];
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const managedLabelNames = managedLabels.map((label) => label.name);
for (const label of managedLabels) {
try {
@@ -138,19 +138,13 @@ jobs:
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: label.name,
color: label.color,
description: label.description,
});
}
}
@@ -165,35 +159,17 @@ jobs:
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
for (const label of currentLabels) {
if (!managedLabelNames.has(label.name) || label.name === nextLabelName) {
continue;
}
const preservedLabels = currentLabels
.map((label) => label.name)
.filter((name) => !managedLabelNames.includes(name));
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: label.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
if (!currentLabels.some((label) => label.name === nextLabelName)) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [nextLabelName],
});
}
await github.rest.issues.setLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [...preservedLabels, nextLabelName],
});
core.info(`PR #${issueNumber}: ${status} -> ${nextLabelName}`);
+14 -40
View File
@@ -27,7 +27,7 @@ jobs:
ref: ${{ github.sha }}
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
- id: release_meta
name: Resolve release version
@@ -61,7 +61,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
@@ -107,7 +107,7 @@ jobs:
arch: x64
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
@@ -118,16 +118,13 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build desktop artifact
shell: bash
env:
@@ -217,7 +214,7 @@ jobs:
fi
- name: Upload build artifacts
uses: actions/upload-artifact@v7
uses: actions/upload-artifact@v4
with:
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
path: release-publish/*
@@ -229,7 +226,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
@@ -239,7 +236,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
registry-url: https://registry.npmjs.org
@@ -247,9 +244,6 @@ jobs:
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build CLI package
run: bun run build --filter=@t3tools/web --filter=t3
@@ -262,17 +256,17 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
uses: actions/download-artifact@v4
with:
pattern: desktop-*
merge-multiple: true
@@ -308,31 +302,11 @@ jobs:
needs: [preflight, release]
runs-on: ubuntu-24.04
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
uses: actions/checkout@v4
with:
ref: main
fetch-depth: 0
token: ${{ steps.app_token.outputs.token }}
persist-credentials: true
- id: app_bot
name: Resolve GitHub App bot identity
env:
GH_TOKEN: ${{ steps.app_token.outputs.token }}
APP_SLUG: ${{ steps.app_token.outputs.app-slug }}
run: |
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Bun
uses: oven-sh/setup-bun@v2
@@ -340,7 +314,7 @@ jobs:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
uses: actions/setup-node@v4
with:
node-version-file: package.json
@@ -369,8 +343,8 @@ jobs:
exit 0
fi
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
git commit -m "chore(release): prepare $RELEASE_TAG"
-5
View File
@@ -12,12 +12,7 @@ packages/*/dist
build/
.logs/
release/
release-mock/
.t3
.idea/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
+2 -4
View File
@@ -1,15 +1,13 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
"**/routeTree.gen.ts"
],
"sortPackageJson": {}
"experimentalSortPackageJson": {}
}
-7
View File
@@ -1,24 +1,20 @@
# Plan: Centralize Model Normalization in Contracts
## Summary
Move model alias/default normalization into `packages/contracts` so desktop and renderer use one shared source of truth.
## Motivation
- Removes duplicated logic between:
- `apps/desktop/src/codexAppServerManager.ts`
- `apps/renderer/src/model-logic.ts`
- Prevents behavior drift when model aliases/defaults are updated.
## Scope
- Add shared model utilities to contracts.
- Update desktop and renderer to consume shared utilities.
- Keep renderer-specific display options in renderer.
## Proposed Changes
1. Add `packages/contracts/src/model.ts` with:
- Canonical model list
- Alias map
@@ -33,17 +29,14 @@ Move model alias/default normalization into `packages/contracts` so desktop and
- Keep renderer tests focused on renderer-only behavior.
## Risks
- Desktop/renderer may currently rely on slightly different fallback behavior.
- Import graph must avoid bundling issues for Electron main/preload.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual check that model selection and session start still send expected model slug.
## Done Criteria
- No duplicated alias/default map in desktop and renderer.
- Shared model utilities are contract-tested.
-7
View File
@@ -1,21 +1,17 @@
# Plan: Strengthen Typed IPC Boundaries in Main Process
## Summary
Replace loose payload casting in IPC handlers with strict schema parsing and typed helper wrappers.
## Motivation
- `apps/desktop/src/main.ts` currently uses casts like `payload as Parameters<...>`.
- Casts can hide contract breakages until runtime.
## Scope
- Desktop main process IPC registration.
- Optional shared helper for handler registration.
## Proposed Changes
1. Add IPC helper utility (e.g. `apps/desktop/src/ipcHelpers.ts`) to:
- Parse payload(s) with Zod schemas
- Standardize typed handler signatures
@@ -28,17 +24,14 @@ Replace loose payload casting in IPC handlers with strict schema parsing and typ
4. Add tests for handler parsing failure paths (invalid payloads).
## Risks
- Refactor can subtly change IPC error shape/messages.
- Helper abstraction should stay simple and not obscure control flow.
## Validation
- `bun run test`
- `bun run typecheck`
- Manual invalid payload check from renderer/devtools to confirm fast failure.
## Done Criteria
- No provider handler uses `payload as Parameters<...>`.
- All IPC entrypoints parse unknown payloads at boundary.
@@ -1,11 +1,9 @@
# Plan: Decompose CodexAppServerManager
## Summary
Split `CodexAppServerManager` into smaller modules with clear responsibilities.
## Motivation
- `apps/desktop/src/codexAppServerManager.ts` is large and mixes:
- Process lifecycle
- JSON-RPC parsing/routing
@@ -14,12 +12,10 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- This increases regression risk and slows changes.
## Scope
- Desktop provider internals only.
- Keep external behavior/API stable.
## Proposed Changes
1. Extract modules:
- `codex/processLifecycle.ts`
- `codex/jsonrpcRouter.ts`
@@ -33,16 +29,13 @@ Split `CodexAppServerManager` into smaller modules with clear responsibilities.
- Session state transitions
## Risks
- Reordering event handling can change behavior.
- Must preserve pending request timeout/cancellation semantics.
## Validation
- Existing tests pass.
- Add module-level tests for parsing and transition logic.
## Done Criteria
- Main manager file materially smaller and orchestration-focused.
- Core protocol/state logic covered by focused tests.
-7
View File
@@ -1,11 +1,9 @@
# Plan: Split ChatView into Smaller UI/Logic Units
## Summary
Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
## Motivation
- `apps/renderer/src/components/ChatView.tsx` is large and handles:
- Session orchestration
- Send/interrupt actions
@@ -15,12 +13,10 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
- Hard to test and maintain as one component.
## Scope
- Renderer component boundaries and hooks.
- Keep visual behavior unchanged.
## Proposed Changes
1. Create hook: `apps/renderer/src/hooks/useChatSession.ts`
- `ensureSession`
- `sendTurn`
@@ -33,15 +29,12 @@ Refactor `ChatView.tsx` into composable pieces with isolated responsibilities.
4. Add focused tests for hook behavior (error handling, session reuse).
## Risks
- Refactor can break subtle UI interactions (auto-scroll, menu close, keyboard send).
## Validation
- `bun run test`
- Manual smoke: send, stream, interrupt, model switch.
## Done Criteria
- `ChatView.tsx` significantly reduced and easier to scan.
- Session logic isolated from rendering.
@@ -1,21 +1,17 @@
# Plan: Move Renderer Persisted-State Validation to Zod
## Summary
Use explicit Zod schemas for localStorage state parsing and migration.
## Motivation
- `apps/renderer/src/store.ts` has large manual sanitize functions.
- Manual type guards are verbose and easier to get wrong during schema evolution.
## Scope
- Renderer state hydration/persistence path.
- No backend/protocol changes.
## Proposed Changes
1. Add schema module: `apps/renderer/src/persistenceSchema.ts`
- Persisted payload versions (`v1`, `v2`)
- Thread/message/project schemas
@@ -27,15 +23,12 @@ Use explicit Zod schemas for localStorage state parsing and migration.
- Unknown thread/project references filtered
## Risks
- Overly strict schemas could drop valid historical data unexpectedly.
## Validation
- Unit tests for migration/hydration.
- Manual reload test with existing localStorage data.
## Done Criteria
- Store hydration logic is schema-driven.
- Migration behavior is tested and documented.
@@ -1,21 +1,17 @@
# Plan: Add Provider Log Stream Lifecycle Management
## Summary
Ensure `ProviderManager` logging stream is initialized, rotated/structured, and closed safely.
## Motivation
- `apps/desktop/src/providerManager.ts` opens a write stream in constructor.
- Stream lifecycle is not explicit on shutdown.
## Scope
- Desktop provider logging behavior.
- App shutdown integration.
## Proposed Changes
1. Add explicit `dispose()` on `ProviderManager`:
- Remove event listeners
- End/close log stream
@@ -24,15 +20,12 @@ Ensure `ProviderManager` logging stream is initialized, rotated/structured, and
4. Optional: per-session log files under `.logs/providers/`.
## Risks
- Improper close sequencing may lose final log lines.
## Validation
- Manual run/quit cycle to ensure no open handle warnings.
- Confirm logs flush on quit and file descriptors are not leaked.
## Done Criteria
- ProviderManager owns complete log stream lifecycle.
- Shutdown path explicitly disposes provider resources.
-7
View File
@@ -1,21 +1,17 @@
# Plan: Add CI Workflow for Core Quality Gates
## Summary
Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-test) on pushes and PRs.
## Motivation
- Repository currently has no CI workflow files.
- Quality checks are only local/manual.
## Scope
- `.github/workflows/ci.yml`
- Bun + Turbo setup in CI.
## Proposed Changes
1. Add `ci.yml` with jobs:
- Setup Bun and Node environment
- Install deps
@@ -26,16 +22,13 @@ Add GitHub Actions workflow to run lint/typecheck/test (and optionally smoke-tes
3. Configure caching for Bun/Turbo as appropriate.
## Risks
- Smoke test may be flaky in headless CI environments.
- CI runtime can grow if caching is misconfigured.
## Validation
- Verify workflow runs on a branch PR.
- Ensure failures surface clearly by job name.
## Done Criteria
- CI blocks regressions in lint/typecheck/test.
- Workflow docs added to README.
-7
View File
@@ -1,21 +1,17 @@
# Plan: Add Pre-Commit Formatting/Lint Hooks
## Summary
Introduce pre-commit automation so formatting and basic lint checks happen before commits.
## Motivation
- Current lint failures include formatting-only issues.
- Shift-left feedback reduces noisy CI failures and cleanup churn.
## Scope
- Root tooling config and package scripts.
- No runtime code changes.
## Proposed Changes
1. Add hook tooling (e.g. Husky + lint-staged or Lefthook).
2. Configure staged-file tasks:
- `biome format --write`
@@ -24,16 +20,13 @@ Introduce pre-commit automation so formatting and basic lint checks happen befor
4. Keep checks fast to avoid developer friction.
## Risks
- Slow hooks can frustrate contributors and be bypassed.
- Need to ensure compatibility with Bun workspace setup.
## Validation
- Create sample staged changes and verify hook behavior.
- Confirm formatting fixes are applied automatically.
## Done Criteria
- Pre-commit hook installed and documented.
- Formatting-only lint failures drop significantly.
-7
View File
@@ -1,21 +1,17 @@
# Plan: Expand Event/State Transition Test Coverage
## Summary
Add focused tests for renderer event handling and session evolution logic.
## Motivation
- Core behavior is event-driven and stateful.
- Existing renderer tests cover only a subset of timeline/model behavior.
## Scope
- `apps/renderer/src/session-logic.test.ts`
- Optional reducer tests for `apps/renderer/src/store.ts`.
## Proposed Changes
1. Add tests for `evolveSession`:
- `thread/started`
- `turn/started`
@@ -28,15 +24,12 @@ Add focused tests for renderer event handling and session evolution logic.
3. Add reducer integration tests for `APPLY_EVENT`.
## Risks
- Tests may be brittle if event payload fixtures are too coupled to implementation details.
## Validation
- `bun run test`
- Ensure new tests remain deterministic and fast.
## Done Criteria
- High-risk event transitions are covered by unit tests.
- Regressions in stream assembly/session status are caught quickly.
@@ -1,21 +1,17 @@
# Plan: Unify Process and PTY Session Abstractions in ProcessManager
## Summary
Refactor `ProcessManager` to use a single runtime-session interface for child-process and PTY modes.
## Motivation
- `apps/desktop/src/processManager.ts` maintains parallel maps and branch-heavy logic.
- New execution backends/providers will multiply complexity.
## Scope
- Desktop process execution internals.
- Preserve public `ProcessManager` API.
## Proposed Changes
1. Introduce internal interface (e.g. `RuntimeSession`):
- `write(data)`
- `kill()`
@@ -28,15 +24,12 @@ Refactor `ProcessManager` to use a single runtime-session interface for child-pr
5. Add tests for both implementations.
## Risks
- PTY behavior differs by platform; abstraction must not hide required differences.
## Validation
- Existing `processManager.test.ts` passes.
- Add PTY-path tests where feasible.
## Done Criteria
- Manager no longer branches per backend in `write/kill/killAll`.
- Session backends are independently testable.
+3 -1
View File
@@ -1,3 +1,5 @@
PR 1: Service contracts + error taxonomy
Add ProviderService, CodexService, CheckpointStore as Context.Tag service defs.
Add typed Schema.TaggedError hierarchies for all 3 services (cause: Schema.optional(Schema.Defect) on each).
@@ -37,4 +39,4 @@ Remove throw-based flow entirely from provider path.
PR 10: Cleanup + deprecation removal
Remove legacy class implementations/adapters once parity is proven.
Finalize layer composition and startup graph docs.
Add architecture notes for service boundaries and error model.
Add architecture notes for service boundaries and error model.
-9
View File
@@ -1,14 +1,12 @@
# Effect Migration Plan (From Current State)
Current status summary:
- Service contracts, typed errors, and most checkpoint/persistence services exist.
- `ProviderServiceLive` is already native orchestration (not a thin adapter).
- Production server path still uses legacy `ProviderManager`/`FilesystemCheckpointStore`.
- Checkpoint flow now avoids snapshot re-sync and is write-time driven.
## PR 1: Wire Provider/Checkpoint Effect Stack Into `wsServer`
- Build one runtime layer graph for provider + checkpoint + persistence + orchestration.
- Resolve `ProviderService` from runtime in `wsServer`.
- Replace `ProviderManager` method calls in WS handlers with `ProviderService` calls.
@@ -16,14 +14,12 @@ Current status summary:
- Keep WS method/push payloads identical.
## PR 2: Runtime Composition + Startup Ownership
- Create/centralize `AppLive` composition for server startup.
- Ensure outer runtime provides Node/platform services once.
- Ensure migrations run at startup via scoped/layer startup path.
- Remove ad-hoc service initialization in request-time paths.
## PR 3: Session Lifecycle Hygiene + Checkpoint Invariants
- Add explicit checkpoint session cleanup on `stopSession` / `stopAll`.
- Remove per-session lock/cwd map leaks.
- Keep strict invariant model:
@@ -33,14 +29,12 @@ Current status summary:
- Add tests for lifecycle cleanup and invariant-failure surfaces.
## PR 4: Provider Event Stream Hardening (Without Extra Service Fragmentation)
- Keep `ProviderService` as the public event surface.
- Internally move callback fanout to Effect concurrency primitives (`Queue`/`PubSub`) for ordering/backpressure control.
- Keep API as `subscribeToEvents` unless we explicitly choose stream API later.
- Add tests for ordering and subscriber isolation under load.
## PR 5: Codex Runtime Split (Scoped Effect Core)
- Extract `CodexAppServerManager` responsibilities into Effect-native layers:
- scoped process lifecycle
- RPC request/response + pending map via `Deferred`
@@ -49,19 +43,16 @@ Current status summary:
- Preserve protocol behavior and timeout semantics.
## PR 6: Codex Protocol Decode Hardening
- Replace ad-hoc unknown parsing with runtime schema decode.
- Map decode failures to typed tagged errors with `cause` retained.
- Add regression tests for malformed/partial protocol frames.
## PR 7: Remove Legacy Provider Stack
- Remove `ProviderManager` + legacy checkpoint integration from runtime path.
- Remove `FilesystemCheckpointStore` from active server flow (keep only if explicitly needed for compatibility tooling).
- Update tests to assert only Effect service path is used.
## PR 8: Final Cleanup + Docs
- Update architecture docs with final layer graph and service boundaries.
- Document error model and recovery semantics.
- Trim dead compatibility code and stale plan references.
@@ -1,7 +1,6 @@
# ProviderService Integration Test Plan
Goal:
- Validate end-to-end `ProviderService` behavior with real layers:
- `ProviderServiceLive`
- `CheckpointServiceLive`
@@ -14,7 +13,6 @@ Goal:
## Test Harness
Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Layers/TestProviderAdapter.integration.ts`:
- Service contract: `ProviderAdapterShape<ProviderAdapterError>`.
- Internal state:
- session registry (session + cwd + threadId)
@@ -31,15 +29,13 @@ Build a deterministic `TestProviderAdapterLive` in `apps/server/src/provider/Lay
- `readThread`, `rollbackThread`, `stopSession`, `stopAll`.
Use real git-backed temporary workspaces in integration tests:
- initialize repo with baseline commit
- run provider turn in workspace
- assert checkpoint diffs against real git refs
## Core Integration Specs
1. `startSession` initializes checkpoint root exactly once
1) `startSession` initializes checkpoint root exactly once
- Arrange:
- start provider session in git repo.
- Assert:
@@ -47,8 +43,7 @@ Use real git-backed temporary workspaces in integration tests:
- checkpoint ref exists in git.
- second `startSession` for new session creates a new independent root.
2. Turn without filesystem change
2) Turn without filesystem change
- Arrange:
- emit normal turn events, no file mutation.
- Assert:
@@ -59,8 +54,7 @@ Use real git-backed temporary workspaces in integration tests:
- `listCheckpoints` returns root + turn 1.
- `getCheckpointDiff(0 -> 1)` returns empty/no-op diff.
3. Turn with filesystem change
3) Turn with filesystem change
- Arrange:
- mutate `README.md` during turn.
- Assert:
@@ -68,8 +62,7 @@ Use real git-backed temporary workspaces in integration tests:
- `getCheckpointDiff(0 -> 1)` contains file path and hunk.
- persisted checkpoint metadata includes non-empty `checkpointRef`.
4. Multi-turn sequencing and checkpoint monotonicity
4) Multi-turn sequencing and checkpoint monotonicity
- Arrange:
- turn 1: no file change
- turn 2: file change
@@ -79,8 +72,7 @@ Use real git-backed temporary workspaces in integration tests:
- latest checkpoint is marked current.
- diffs for adjacent turns map to expected filesystem deltas.
5. Revert to checkpoint
5) Revert to checkpoint
- Arrange:
- execute 3 turns with at least one file-changing turn.
- call `revertToCheckpoint(turnCount=1)`.
@@ -90,8 +82,7 @@ Use real git-backed temporary workspaces in integration tests:
- DB rows for turns >1 are removed.
- later refs are deleted from git.
6. Capture failure surface
6) Capture failure surface
- Arrange:
- adapter emits `turn/completed`, but file mutation leaves invalid repo state or store capture fails.
- Assert:
@@ -101,7 +92,6 @@ Use real git-backed temporary workspaces in integration tests:
## WebSocket Coverage (Thin Integration)
Add one ws server integration spec:
- Subscribe to `providers.event`.
- Run a deterministic provider turn through ws methods.
- Assert push stream includes:
@@ -111,13 +101,10 @@ Add one ws server integration spec:
## Proposed PR Split
PR A:
- Test adapter harness + shared integration fixtures (repo setup, runtime/layer setup).
PR B:
- Core ProviderService integration specs (cases 1-4).
PR C:
- Revert + failure-path specs (cases 5-6) + ws thin integration spec.
@@ -1,7 +1,6 @@
# Server-Authoritative Event-Sourcing Cleanup Plan
Goal:
- Move to a cleaner service architecture with:
- durable, server-authoritative event sourcing
- strict command routing/validation
@@ -86,7 +85,6 @@ CheckpointCatalog ------> SQLite
## Commit Series
### Commit 1: Split public vs system orchestration command contracts
- Create separate schemas/types:
- `ClientOrchestrationCommandSchema`
- `SystemOrchestrationCommandSchema`
@@ -102,7 +100,6 @@ CheckpointCatalog ------> SQLite
- preserve internal dispatch functionality for system commands
### Commit 2: Introduce `OrchestrationCommandRouter` + handler boundary
- Add dedicated router service to validate, authorize, and route commands.
- Move command-to-event mapping out of `orchestration/Layer.ts` into handlers.
- Add aggregate-level invariant checks before append (thread exists, project exists, etc.).
@@ -116,7 +113,6 @@ CheckpointCatalog ------> SQLite
- handler happy-path tests per command type
### Commit 3: Harden event store for idempotency + optimistic append metadata
- Add DB-level idempotency guard for `command_id` (`UNIQUE` where non-null).
- Extend append API to support idempotent replays and deterministic return of prior event on duplicate `commandId`.
- Add optional aggregate version metadata for future optimistic concurrency.
@@ -129,7 +125,6 @@ CheckpointCatalog ------> SQLite
- concurrent append behavior stays ordered and deterministic
### Commit 4: Extract provider-runtime -> orchestration bridge from `wsServer`
- Create `ProviderRuntimeIngestionService` that:
- subscribes to `ProviderService.streamEvents`
- translates runtime events into orchestration commands
@@ -144,7 +139,6 @@ CheckpointCatalog ------> SQLite
- ws integration confirms same external push behavior
### Commit 5: Make session directory durable (`ProviderSessionRegistry`)
- Replace in-memory-only `ProviderSessionDirectoryLive` with persistence-backed registry.
- Keep in-memory cache optional, but source of truth must be persistent.
- Add startup reconciliation to prune dead sessions / keep known thread mapping.
@@ -158,7 +152,6 @@ CheckpointCatalog ------> SQLite
- stale session cleanup semantics
### Commit 6: Re-key checkpoint metadata from session to thread identity
- Change checkpoint catalog primary identity from `provider_session_id` to durable `thread_id`.
- Keep `session_id` as nullable metadata only.
- Update checkpoint flows (`initialize`, `capture`, `list`, `diff`, `revert`) to use thread identity.
@@ -172,7 +165,6 @@ CheckpointCatalog ------> SQLite
- revert/diff still work after session churn
### Commit 7: Add durable projection persistence for orchestration read models
- Introduce projection tables/snapshots persisted in DB to avoid full replay dependency.
- Keep event stream as source of truth; projection rebuild stays deterministic.
- `getSnapshot` reads from projection store (memory cache optional).
@@ -185,7 +177,6 @@ CheckpointCatalog ------> SQLite
- projection rebuild from events yields same result as previous reducer semantics
### Commit 8: Narrow `ProviderService` responsibilities
- Keep `ProviderService` focused on provider RPC/session lifecycle + unified runtime stream.
- Move checkpoint-capture side effects out of provider event worker into dedicated ingestion/checkpoint pipeline service.
- Preserve adapter pluggability and provider-neutral contracts.
@@ -197,7 +188,6 @@ CheckpointCatalog ------> SQLite
- checkpoint capture still triggered by turn completion through new coordinator
### Commit 9: Look over schemas (contracts and events)
- Scan for unused schemas.
- Use effect/Schema everywhere
- Analyze which we need
@@ -206,7 +196,6 @@ CheckpointCatalog ------> SQLite
- Persistence entities
### Commit 10: Remove dead legacy path and finalize docs
- Remove unused legacy manager/store path from active architecture:
- `providerManager.ts`
- `filesystemCheckpointStore.ts` (if no longer needed by tests/tools)
@@ -221,7 +210,6 @@ CheckpointCatalog ------> SQLite
- no regressions in WS protocol behavior
## Risk Controls
- Keep WS method names and payload contracts stable throughout.
- Gate each commit with targeted integration tests before moving forward.
- Avoid broad event-type churn in one step; migrate schemas incrementally with clear compatibility windows.
+1 -2
View File
@@ -1,11 +1,10 @@
Rewrite `createServer` and `index.ts` to be Effect native.
Maybe use `effect/unstable/Socket` for the web socket server
- https://github.com/Effect-TS/effect-smol/blob/main/packages/effect/src/unstable/socket/SocketServer.ts
- https://github.com/Effect-TS/effect-smol/blob/main/packages/platform-node/test/NodeSocket.test.ts
- Migrate remaining runtime code to Effect
- `gitManager` -> `src/git`
- `terminalManager` -> `src/terminal` (Manager + PTY)
- ...
- ...
@@ -24,25 +24,21 @@
- Mark invalid/false-positive items with explicit rationale.
Exit criteria:
- Every open thread is mapped to one canonical fix item or marked invalid.
## Phase 1: Runtime Survival and Critical Event Wiring
Related bug groups solved together:
- Worker loop/fiber fatal error handling in orchestration reactors.
- WebSocket message error boundaries and unhandled rejection guards.
- Close invalid `providers.event` review findings as documented architecture mismatch (no code change expected).
Primary files:
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/wsServer.ts`
Exit criteria:
- A single event-processing failure cannot permanently stop ingestion/reactor loops.
- WS message handling cannot produce unhandled promise rejections.
- Invalid provider-event-channel review findings are closed with architecture rationale.
@@ -50,20 +46,17 @@ Exit criteria:
## Phase 2: State Consistency and Ordering
Related bug groups solved together:
- Fire-and-forget revert completion causing consistency windows.
- Non-atomic append/projection paths and retry behavior.
- Race-sensitive thread/event association issues.
Primary files:
- `apps/server/src/orchestration/Layers/CheckpointReactor.ts`
- `apps/server/src/orchestration/Layers/OrchestrationEngine.ts`
- `apps/server/src/orchestration/Layers/ProjectionPipeline.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
Exit criteria:
- Revert flow is deterministically reflected in read model updates.
- Append/project failure mode is explicit and safe under retry.
- No cross-thread misassociation under concurrent runtime events.
@@ -71,14 +64,12 @@ Exit criteria:
## Phase 3: Checkpointing Correctness Bundle
Related bug groups solved together:
- Checkpoint input normalization consistency.
- Snapshot/projector coverage mismatches.
- Checkpoint ref/workspace CWD utility duplication.
- Checkpoint diff/error handling behavior gaps.
Primary files:
- `apps/server/src/checkpointing/Layers/CheckpointStore.ts`
- `apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts`
- `apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts`
@@ -86,7 +77,6 @@ Primary files:
- `apps/server/src/wsServer.ts`
Exit criteria:
- Checkpoint capture/restore/revert paths use one normalization policy.
- Required projectors are actually represented in snapshot reads.
- Shared checkpoint/ref/CWD helpers are centralized.
@@ -94,32 +84,27 @@ Exit criteria:
## Phase 4: Memory and Lifecycle Hygiene
Related bug groups solved together:
- Unbounded in-memory dedup sets/maps.
- Missing cleanup/lifecycle protections in long-lived effects/resources.
Primary files:
- `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
- `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts`
- `apps/server/src/config.ts`
Exit criteria:
- Long-running server memory does not grow unbounded from dedup bookkeeping.
- Resource cleanup paths are registered for interruption/shutdown.
## Phase 5: Transport, Parsing, and Platform Edge Cases
Related bug groups solved together:
- UTF-8 chunk boundary decode correctness.
- Markdown/file-link parsing edge cases.
- Shell/OS-specific PATH parsing behavior.
- Git rename parsing and small keybinding edge cases.
Primary files:
- `apps/server/src/wsServer.ts`
- `apps/server/src/git/Layers/CodexTextGeneration.ts`
- `apps/web/src/markdown-links.ts`
@@ -128,27 +113,23 @@ Primary files:
- `apps/server/src/keybindings.ts`
Exit criteria:
- Edge-case parsers are robust across valid but non-trivial inputs.
- Platform-dependent command behavior has safe fallbacks.
## Phase 6: Build and Maintainability Cleanup
Related bug groups solved together:
- Build script/runtime assumption cleanup.
- Redundant error-union declarations and utility/type duplication.
- Non-functional cleanup comments/docs markers.
Primary files:
- `apps/server/package.json`
- `apps/server/src/checkpointing/Errors.ts`
- Shared utility locations introduced during earlier phases
- `AGENTS.md` (if cleanup is still pending)
Exit criteria:
- Build path is explicit and environment-safe.
- Redundant types/utilities are removed in favor of single sources of truth.
@@ -159,7 +140,6 @@ Exit criteria:
- Resolve threads with fix references per canonical checklist item.
Exit criteria:
- Lint passes.
- Backend tests pass.
- All actionable review threads are resolved or explicitly justified.
+4 -5
View File
@@ -5,7 +5,6 @@ _Last updated: 2026-02-26_
This is the working checklist for remediation execution.
Status values:
- `TODO`: Not started
- `IN_PROGRESS`: Currently being worked
- `BLOCKED`: Waiting on decision/dependency
@@ -151,7 +150,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Area: `WebSocket robustness`
- File: `apps/web/src/wsTransport.ts:59`
- Threads: PRRT_kwDORLtfbc5whtrN
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
- Audit note: Transport _tag override risk exists but current callsites are constrained.
### Phase 2
@@ -182,7 +181,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Threads: PRRT_kwDORLtfbc5whxJO
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [x] `C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes *after* the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
@@ -199,7 +198,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
- Severity: `Medium`
- Area: `Checkpointing correctness`
- File: `apps/server/src/checkpointing/Layers/CheckpointStore.ts:94`
- Threads: PRRT*kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv*, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
- Threads: PRRT_kwDORLtfbc5widJw, PRRT_kwDORLtfbc5wnWv_, PRRT_kwDORLtfbc5w0_g7, PRRT_kwDORLtfbc5w1C36 (+3 duplicate thread(s))
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
- [x] `C017` `REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
@@ -251,7 +250,7 @@ Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
### Phase 5
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [ ] `C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after ` => ` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
-441
View File
@@ -1,441 +0,0 @@
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
1. `orchestration.dispatchCommand` (client intent)
2. `OrchestrationEngine` (decide + persist + publish domain events)
3. `ProviderCommandReactor` (domain intent -> `ProviderService`)
4. `ProviderService` (adapter routing + canonical runtime stream)
5. `ProviderRuntimeIngestion` (provider runtime -> internal orchestration commands)
6. `orchestration.domainEvent` (single push channel consumed by web)
Claude integration must plug into this path instead of reintroducing legacy provider-specific flows.
---
## Current constraints to design around (post-Stage 1)
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3. `resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4. `ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
- `providerOptions.codex`
- `providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
---
## Phase 2: Claude adapter implementation
### 2.1 Add adapter service + layer
Create:
1. `apps/server/src/provider/Services/ClaudeAdapter.ts`
2. `apps/server/src/provider/Layers/ClaudeAdapter.ts`
Adapter must implement `ProviderAdapterShape<ProviderAdapterError>`.
### 2.1.a SDK dependency and baseline config
Add server dependency:
1. `@anthropic-ai/claude-agent-sdk`
Baseline adapter options to support from day one:
1. `cwd`
2. `model`
3. `pathToClaudeCodeExecutable` (from `providerOptions.claudeCode.binaryPath`)
4. `permissionMode` (from `providerOptions.claudeCode.permissionMode`)
5. `maxThinkingTokens` (from `providerOptions.claudeCode.maxThinkingTokens`)
6. `resume`
7. `resumeSessionAt`
8. `includePartialMessages`
9. `canUseTool`
10. `hooks`
11. `env` and `additionalDirectories` (if needed for sandbox/workspace parity)
### 2.2 Claude runtime bridge
Implement a Claude runtime bridge (either directly in adapter layer or via dedicated manager file) that wraps Agent SDK query lifecycle.
Required capabilities:
1. Long-lived session context per adapter session.
2. Multi-turn input queue.
3. Interrupt support.
4. Approval request/response bridge.
5. Resume support via opaque `resumeCursor` (parsed inside Claude adapter only).
#### 2.2.a Agent SDK details to preserve
The adapter should explicitly rely on these SDK capabilities:
1. `query()` returns an async iterable message stream and control methods (`interrupt`, `setModel`, `setPermissionMode`, `setMaxThinkingTokens`, account/status helpers).
2. Multi-turn input is supported via async-iterable prompt input.
3. Tool approval decisions are provided via `canUseTool`.
4. Resume support uses `resume` and optional `resumeSessionAt`, both derived by parsing adapter-owned `resumeCursor`.
5. Hooks can be used for lifecycle signals (`Stop`, `PostToolUse`, etc.) when we need adapter-originated checkpoint/runtime events.
#### 2.2.b Effect-native session lifecycle skeleton
```ts
import { query } from "@anthropic-ai/claude-agent-sdk";
import { Effect } from "effect";
const acquireSession = (input: ProviderSessionStartInput) =>
Effect.acquireRelease(
Effect.tryPromise({
try: async () => {
const claudeOptions = input.providerOptions?.claudeCode;
const resumeState = readClaudeResumeState(input.resumeCursor);
const abortController = new AbortController();
const result = query({
prompt: makePromptAsyncIterable(),
options: {
cwd: input.cwd,
model: input.model,
permissionMode: claudeOptions?.permissionMode,
maxThinkingTokens: claudeOptions?.maxThinkingTokens,
pathToClaudeCodeExecutable: claudeOptions?.binaryPath,
resume: resumeState?.threadId,
resumeSessionAt: resumeState?.sessionAt,
signal: abortController.signal,
includePartialMessages: true,
canUseTool: makeCanUseTool(),
hooks: makeClaudeHooks(),
},
});
return { abortController, result };
},
catch: (cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId: "pending",
detail: "Failed to start Claude runtime session.",
cause,
}),
}),
({ abortController }) => Effect.sync(() => abortController.abort()),
);
```
#### 2.2.c AsyncIterable -> Effect Stream integration
Preferred when available in the pinned Effect version:
```ts
const sdkMessageStream = Stream.fromAsyncIterable(
session.result,
(cause) =>
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
```
Portable fallback (already aligned with current server patterns):
```ts
const sdkMessageStream = Stream.async<ClaudeSdkMessage, ProviderAdapterProcessError>((emit) => {
let cancelled = false;
void (async () => {
try {
for await (const message of session.result) {
if (cancelled) break;
emit.single(message);
}
emit.end();
} catch (cause) {
emit.fail(
new ProviderAdapterProcessError({
provider: "claudeCode",
sessionId,
detail: "Claude runtime stream failed.",
cause,
}),
);
}
})();
return Effect.sync(() => {
cancelled = true;
});
});
```
### 2.3 Canonical event mapping
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interface ClaudeResumeCursor {
readonly version: 1;
readonly threadId?: string;
readonly sessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
### 2.5 Interrupt and stop semantics
Map orchestration stop/interrupt expectations onto SDK controls:
1. `interruptTurn()` -> active query interrupt.
2. `stopSession()` -> close session resources and prevent future sends.
3. `rollbackThread()` -> see Phase 4.
---
## Phase 3: Provider service and composition
### 3.1 Register Claude adapter
Update provider registry layer to include Claude:
1. add `claudeCode` -> `ClaudeAdapter`
2. ensure `ProviderService.listProviderStatuses()` reports Claude availability
### 3.2 Persist provider binding
Current `ProviderSessionDirectory` already stores provider/thread binding and opaque `resumeCursor`.
Required validation:
1. Claude bindings survive restart.
2. resume cursor remains opaque and round-trips untouched.
3. stopAll + restart can recover Claude sessions when possible.
### 3.3 Provider start routing
Update `ProviderCommandReactor` / orchestration flow:
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1. `apps/web/src/store.ts`
2. `apps/web/src/components/ChatView.tsx`
3. `apps/web/src/types.ts`
4. `packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
---
## Phase 7: Rollout order
Recommended implementation order:
1. contracts/provider-aware models
2. provider field on turn-start
3. Claude adapter skeleton + start/send/stream
4. canonical event mapping
5. provider registry/service wiring
6. orchestration recovery + checkpoint strategy
7. web provider/model picker
8. full integration tests
---
## Non-goals
1. Reintroducing provider-specific WS methods/channels.
2. Storing provider-native thread ids as orchestration ids.
3. Bypassing orchestration engine for Claude-specific UI flows.
4. Encoding Claude resume semantics outside adapter-owned `resumeCursor`.
@@ -3,81 +3,60 @@
## Summary
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
## Implementation Status
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
### New files
| File | Purpose |
|------|---------|
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
| `packages/shared/src/schemaJson.ts` | Two-phase JSON→Schema decode helpers (`decodeJsonResult`, `formatSchemaError`) |
| `apps/server/src/wsServer/pushBus.ts` | `ServerPushBus` — ordered typed push pipeline with auto-incrementing sequence |
| `apps/server/src/wsServer/readiness.ts` | `ServerReadiness` — Deferred-based barriers for startup sequencing |
| `apps/server/src/orchestration/Services/RuntimeReceiptBus.ts` | Receipt schema union: checkpoint captured, diff finalized, turn quiesced |
| `apps/server/src/orchestration/Layers/RuntimeReceiptBus.ts` | PubSub-backed receipt bus implementation |
| `apps/server/src/watchFileWithStatPolling.ts` | Stat-polling file watcher for containers where `fs.watch` is unreliable |
| `apps/server/vitest.config.ts` | Server-specific test config (timeout bumps) |
| `apps/server/src/wsServer/pushBus.test.ts` | Push bus serialization and welcome-gating tests |
| `packages/shared/src/DrainableWorker.test.ts` | Drainable worker enqueue/drain lifecycle tests |
### Key modifications
| File | Change |
|------|--------|
| `packages/contracts/src/ws.ts` | Channel-indexed `WsPushPayloadByChannel` map, `WsPush` union schema, `WsPushSequence` |
| `apps/server/src/wsServer.ts` | Integrated `ServerPushBus` and `ServerReadiness`; welcome gated on readiness |
| `apps/server/src/keybindings.ts` | Explicit runtime with `start`/`ready`/`snapshot`; dual `fs.watch` + stat-polling watcher |
| `apps/web/src/wsTransport.ts` | Connection state machine (`connecting`→`open`→`reconnecting`→`closed`→`disposed`); two-phase decode at boundary; cached latest push by channel |
| `apps/web/src/wsNativeApi.ts` | Removed decode logic; delegates to pre-validated transport messages |
| `apps/server/src/orchestration/Layers/CheckpointReactor.ts` | Uses `DrainableWorker`; publishes completion receipts |
| `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts` | Uses `DrainableWorker` for command processing |
| `apps/server/src/orchestration/Layers/ProviderRuntimeIngestion.ts` | Uses `DrainableWorker` for event ingestion |
| `apps/server/integration/OrchestrationEngineHarness.integration.ts` | Receipt-based waits replace polling loops |
## Key Changes
### 1. Strengthen the generic boundaries, not the Codex boundary — DONE
- `ProviderRuntimeEvent` remains the canonical provider event contract; `ProviderService` remains the only cross-provider facade.
- Raw Codex payloads and event ordering stay isolated in `CodexAdapter.ts` and `codexAppServerManager.ts`.
- `ProviderKind` was not expanded. The runtime stays provider-neutral by contract.
### 1. Strengthen the generic boundaries, not the Codex boundary
- Keep `ProviderRuntimeEvent` as the canonical provider event contract and `ProviderService` as the only cross-provider facade.
- Do not expose raw Codex payloads or Codex event ordering outside `CodexAdapter.ts` and `codexAppServerManager.ts`.
- Do not expand `ProviderKind` in this change. The runtime stays provider-neutral by contract, while the product remains Codex-only in concrete support.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes — DONE
- `packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
- `packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
- `packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
### 2. Replace loose websocket envelopes with channel-indexed typed pushes
- Refactor `packages/contracts/src/ws.ts` so push messages are derived from a channel-to-schema map instead of `channel: string` plus `data: unknown`.
- Add `sequence: number` to every server push. Ordering becomes explicit and testable.
- Add structured decode diagnostics with stable machine fields: `code`, `reason`, `expected`, `actual`, `path`, optional `jsonOffset`.
- Remove runtime/test dependence on engine-specific pretty strings. Human-readable formatting remains a logging helper only.
### 3. Introduce explicit server readiness and a single push pipeline — DONE
- `apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
- `apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
- `server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer.ts` no longer publishes directly from ad hoc background streams.
### 3. Introduce explicit server readiness and a single push pipeline
- Add a `ServerPushBus` service in `apps/server` backed by one ordered queue/pubsub path. All pushes go through it: `server.welcome`, `server.configUpdated`, terminal events, orchestration domain events.
- Add a `ServerReadiness` service with explicit barriers for:
- HTTP listening
- push bus ready
- keybindings runtime ready
- terminal subscriptions ready
- orchestration subscriptions ready
- Strengthen `server.welcome` semantics: it is emitted only after connection-scoped and server-scoped readiness is complete.
- `wsServer` should never publish directly from ad hoc background streams once the bus exists.
### 4. Turn background watchers into explicit runtimes — DONE
- `apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
- `watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
### 4. Turn background watchers into explicit runtimes
- Extract keybindings watching into a `KeybindingsRuntime` service with `start`, `ready`, `snapshot`, and `changes`.
- Initial config load, startup sync, cache warmup, and watcher attachment complete before `ready` resolves.
- Keep the real `fs.watch` adapter thin. Most behavior tests use a fake watch source and deterministic change stream.
### 5. Replace polling-based orchestration waiting with receipts — DONE
- `RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
- `CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
### 5. Replace polling-based orchestration waiting with receipts
- Add server-owned completion receipts for operations that tests currently infer by polling:
- checkpoint capture complete
- checkpoint diff finalized
- turn processing quiesced
- A receipt means append, projection, and required side effects are complete. It must not mean the provider emitted a certain event sequence.
- Update the orchestration harness and checkpoint tests to await receipts/barriers instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding — DONE
- `apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
### 6. Centralize client transport state and decoding
- Refactor `apps/web/src/wsTransport.ts` into an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Decode and validate typed push payloads at the transport boundary, not downstream in `apps/web/src/wsNativeApi.ts`.
- Keep cached latest welcome/config behavior only if it is modeled as explicit state, not as a late-subscriber race workaround.
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
- `DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
### 7. Replace ad hoc test helpers with semantic test clients
- Add a shared `WsTestClient` for server/websocket tests:
- connect
- await semantic welcome
- await typed push by channel and optional predicate
- track `sequence`
- match RPC responses by id
- Add one orchestration test harness that waits on receipts/barriers instead of custom `waitForThread`, `waitForGitRef`, and arbitrary retry loops.
- Keep only a narrow set of integration tests for real filesystem/watch/socket behavior. Move behavioral assertions to deterministic unit-style harnesses.
## Provider-Coupling Guardrails
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
- No readiness barrier may be defined as “Codex has emitted X.” Readiness is owned by the server runtime, not by provider event order.
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
-89
View File
@@ -1,89 +0,0 @@
# Replace React Query With AtomRpc + Atom State
## Summary
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
- Keep Zustand for orchestration read model and UI state.
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
## Target Architecture
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
## Phase 1: Infrastructure First
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
2. Build the AtomRpc client on top of that layer.
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
5. Land this as a no-behavior-change PR.
## Phase 2: Replace `wsNativeApi`-Owned Push State
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
## Phase 3: Replace React Query Domain By Domain
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
6. Defer the desktop updater until the last phase.
## Phase 4: Move Root Invalidation Off `queryClient`
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
2. Keep Zustand orchestration/event application unchanged.
3. Map current effects exactly:
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
- file creation/deletion/restoration touches `project:${cwd}`
- config-affecting server events touch `server-config`
## Phase 5: Remove Imperative `NativeApi` Usage
1. Create narrow modules instead of a replacement mega-facade:
- `rpc/orchestrationActions.ts`
- `rpc/terminalActions.ts`
- `rpc/gitActions.ts`
- `rpc/projectActions.ts`
- `platform/desktopBridge.ts`
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
## Phase 6: Remove React Query Completely
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
4. Delete the old query-option tests.
## Public Interfaces And Types
- Preserve the current server-state hook names during the transition.
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
- Do not expose raw AtomRpc clients to components.
- Do not add Suspense as part of this migration.
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
## Test Plan
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
- Acceptance scenarios:
- welcome still bootstraps snapshot and navigation
- keybindings toast still responds to config stream updates
- git status/branches refresh after checkout/pull/worktree actions
- PR resolve dialog keeps cached result while typing
- `@` path search refreshes after file mutations and orchestration events
- diff panel refreshes when checkpoints arrive
- desktop updater still reflects push events and button actions
## Assumptions And Defaults
- Zustand stays in scope; only `react-query` is being removed.
- `desktopBridge` remains the only non-RPC boundary.
- The migration lands as 5-6 small PRs, each green independently.
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
-51
View File
@@ -3,16 +3,13 @@
Goal: Align the orchestration model to `SPEC.md` 1:1 and remove legacy persistence/application cruft.
Execution mode for this plan:
- Hard cutover only. Existing DB and migration history are disposable.
- Intermediate steps are allowed to break runtime, tests, typecheck, and lint.
- We optimize for small, reviewable work units, not continuous app operability.
- Only the final gate requires everything to run cleanly.
## 1. Freeze SPEC contract as source of truth
Work units:
- Create `.plans/spec-contract-matrix.md` with one row per requirement in `SPEC.md` sections `7.1`-`7.4`.
- Add exact SQL-level requirements per row: table, column, type, nullability, PK/unique, index, and invariants.
- Add app-level requirements per row: writer path, reader path, and owning module.
@@ -20,22 +17,17 @@ Work units:
- Identify any ambiguous spec lines and record a concrete interpretation in the matrix.
Deliverables:
- Complete matrix file with no unclassified rows.
- Single source checklist used by all later steps.
Breakage allowed:
- No code changes required yet.
Exit criteria:
- Every requirement in `7.1`-`7.4` has exactly one matrix row.
## 2. Hard cutover migrations (replace current migration set)
Work units:
- Delete the current legacy migration files and rewrite migration loader ordering.
- Create `001_orchestration_events.ts` with full envelope columns and required event indexes.
- Create `002_orchestration_command_receipts.ts` with PK + lookup indexes.
@@ -55,22 +47,17 @@ Work units:
- Ensure old tables (`projects`, `provider_checkpoints`, `provider_sessions`) are not recreated.
Deliverables:
- New 5-file migration chain.
- Updated migration loader references only new migrations.
Breakage allowed:
- Repositories/services can be temporarily broken due to removed old tables.
Exit criteria:
- Fresh DB initializes with only canonical tables plus migration bookkeeping.
## 3. Align persistence row/request schemas to DB 1:1
Work units:
- Define row schemas for each canonical table (contracts or persistence layer module).
- Define request schemas for every insert/update/query operation touching canonical tables.
- Remove or deprecate row/request schemas tied to deleted legacy tables.
@@ -78,22 +65,17 @@ Work units:
- Ensure SQL aliases map 1:1 to schema field names (no implicit shape transforms).
Deliverables:
- Canonical row/request schemas committed.
- Zero references to legacy row schemas in active code paths.
Breakage allowed:
- Runtime can still fail while query layers are being rewired.
Exit criteria:
- Every canonical table used in code has a typed row schema and typed request schema.
## 4. Rewrite event store for full persisted envelope
Work units:
- Refactor append path to write full envelope fields:
- `event_id`, `aggregate_kind`, `stream_id`, `stream_version`, `event_type`, `occurred_at`, `command_id`, `causation_event_id`, `correlation_id`, `actor_kind`, `payload_json`, `metadata_json`
- Implement stream version assignment/checking per aggregate stream.
@@ -102,21 +84,16 @@ Work units:
- Add explicit SQL ordering guarantees for replay (`ORDER BY sequence ASC`).
Deliverables:
- Event store append/replay fully aligned with canonical envelope.
Breakage allowed:
- Command dispatch flow can be partially broken until receipts/projectors are updated.
Exit criteria:
- Event store no longer depends on legacy event table shape.
## 5. Add command receipt idempotency
Work units:
- Introduce persistence access layer for `orchestration_command_receipts`.
- In command dispatch flow, check existing receipt by `commandId` before append.
- On first execution, persist accepted receipt with `resultSequence`.
@@ -125,21 +102,16 @@ Work units:
- Ensure receipt write and event append ordering is deterministic.
Deliverables:
- Dispatch path with idempotency behavior wired through receipts.
Breakage allowed:
- Snapshot/read model may still be inconsistent until projectors are fully wired.
Exit criteria:
- Duplicate command IDs no longer create duplicate events.
## 6. Build DB-backed projection pipeline
Work units:
- Create projector runner that consumes events and applies table-specific projections.
- Implement projector handlers for each projection table.
- For each handler, update target row(s) and `projection_state.last_applied_sequence` in the same transaction.
@@ -148,21 +120,16 @@ Work units:
- Add safe resume logic from projector `last_applied_sequence`.
Deliverables:
- Persistent projector pipeline writing all `projection_*` tables.
Breakage allowed:
- Web/API layer may still read old in-memory model until step 7.
Exit criteria:
- Events drive projection rows in DB; projection state advances transactionally.
## 7. Move RPC reads to projections and diff blobs
Work units:
- Implement snapshot query service reading only projection tables.
- Build thread hydration from projection rows: messages, activities, checkpoints, session.
- Compute `snapshotSequence` as the minimum required projector sequence from `projection_state`.
@@ -171,21 +138,16 @@ Work units:
- Validate replay handoff contract: snapshot sequence -> replay from `fromSequenceExclusive`.
Deliverables:
- `orchestration.getSnapshot` and `orchestration.getTurnDiff` served from DB projections/blob store.
Breakage allowed:
- Provider runtime persistence may still be partially legacy until step 8.
Exit criteria:
- No orchestration read RPC depends on legacy tables or in-memory-only state.
## 8. Migrate provider runtime persistence to canonical table
Work units:
- Create repository/service for `provider_session_runtime`.
- Update adapter/session manager to persist runtime/resume cursor in new table.
- Ensure domain-visible session state still flows through orchestration events to `projection_thread_sessions`.
@@ -193,21 +155,16 @@ Work units:
- Verify restart/resume path reads runtime state from canonical table only.
Deliverables:
- Provider runtime state entirely backed by `provider_session_runtime`.
Breakage allowed:
- Some legacy interfaces may still exist but should be disconnected.
Exit criteria:
- Runtime restore no longer reads/writes legacy provider session persistence.
## 9. Remove old cruft aggressively
Work units:
- Delete legacy repositories/services that map to removed tables.
- Remove dead migration imports and obsolete persistence service interfaces.
- Remove compatibility code paths that translate legacy row shapes.
@@ -215,21 +172,16 @@ Work units:
- Update internal docs/comments to reference canonical projection/event model only.
Deliverables:
- Legacy persistence and translation layers removed from active codebase.
Breakage allowed:
- Temporary compile failures acceptable while deletion/refactor is in progress.
Exit criteria:
- No production code path references deleted legacy tables/services.
## 10. Final verification gate (first point where green is required)
Work units:
- Add migration tests that assert canonical tables, columns, constraints, and indexes.
- Add event store tests for envelope persistence, metadata, actor kind, and replay.
- Add receipt idempotency tests for accept/reject/duplicate paths.
@@ -240,13 +192,10 @@ Work units:
- Run project lint/typecheck/tests and fix failures.
Deliverables:
- Green checks with canonical schema + persistence model in place.
Breakage allowed:
- None at end of step.
Exit criteria:
- SPEC `7.1`-`7.4` requirements satisfied and validated by tests.
-32
View File
@@ -1,7 +1,6 @@
# SPEC Contract Matrix (Sections 7.1-7.4)
Status legend:
- `required`: requirement acknowledged, no current implementation claim yet.
- `implemented`: requirement currently satisfied in code + schema.
- `to-replace`: partial/misaligned implementation exists and must be replaced.
@@ -10,7 +9,6 @@ Status legend:
## 7.1 Write-Side Persisted Tables
### W1
- Spec ref: `7.1.1 orchestration_events`
- Requirement: append-only event store with canonical envelope columns.
- SQL contract:
@@ -34,7 +32,6 @@ Status legend:
- Notes: current migration/table lacks `stream_id`, `stream_version`, `causation_event_id`, `correlation_id`, `actor_kind`, `metadata_json`.
### W2
- Spec ref: `7.1.2 orchestration_command_receipts`
- Requirement: command idempotency + ack replay receipts table.
- SQL contract:
@@ -52,7 +49,6 @@ Status legend:
- Notes: missing table and missing idempotency flow.
### W3
- Spec ref: `7.1.3 checkpoint_diff_blobs`
- Requirement: store large plaintext diffs separate from checkpoint summaries.
- SQL contract:
@@ -69,7 +65,6 @@ Status legend:
- Notes: no canonical diff blob table yet.
### W4
- Spec ref: `7.1.4 provider_session_runtime`
- Requirement: server-internal provider runtime/resume state.
- SQL contract:
@@ -91,7 +86,6 @@ Status legend:
## 7.2 Canonical Persisted Event Schema
### E1
- Spec ref: `7.2 OrchestrationPersistedEventSchema`
- Requirement: full typed persisted event envelope in shared contracts.
- SQL contract: envelope fields in W1 must map 1:1 to contracts schema.
@@ -102,7 +96,6 @@ Status legend:
- Notes: contract schema exists; DB + store mapping still incomplete.
### E2
- Spec ref: `7.2 Rules/payload discriminated by eventType`
- Requirement: `payload` validation keyed by `eventType`.
- SQL contract: `event_type` drives payload decode schema; invalid combinations rejected.
@@ -113,7 +106,6 @@ Status legend:
- Notes: decode is present but DB does not persist full envelope columns.
### E3
- Spec ref: `7.2 Rules/provider ids scope`
- Requirement: provider ids live in metadata/provider payload, not as thread identity replacement.
- SQL contract: provider fields persisted inside `metadata_json`; `stream_id` remains project/thread id.
@@ -124,7 +116,6 @@ Status legend:
- Notes: metadata plumbing is incomplete in persistence path.
### E4
- Spec ref: `7.2 Rules/streamVersion concurrency guard`
- Requirement: stream version monotonic per aggregate stream; enforced on write.
- SQL contract: `stream_version INTEGER NOT NULL` + uniqueness/invariant enforcement per stream.
@@ -137,7 +128,6 @@ Status legend:
## 7.3 Required Projected Tables (Read Models)
### P1
- Spec ref: `7.3.1 projection_projects`
- Requirement: persisted project projection table.
- SQL contract:
@@ -155,7 +145,6 @@ Status legend:
- Notes: legacy `projects` table is separate concept and should be removed from orchestration model.
### P2
- Spec ref: `7.3.2 projection_threads`
- Requirement: persisted thread projection table.
- SQL contract:
@@ -176,7 +165,6 @@ Status legend:
- Notes: missing table and projector writes.
### P3
- Spec ref: `7.3.3 projection_thread_messages`
- Requirement: persisted thread message projection table.
- SQL contract:
@@ -195,7 +183,6 @@ Status legend:
- Notes: missing table and message projection writes.
### P4
- Spec ref: `7.3.4 projection_thread_activities`
- Requirement: persisted thread activity projection table.
- SQL contract:
@@ -214,7 +201,6 @@ Status legend:
- Notes: no canonical activity projection persistence.
### P5
- Spec ref: `7.3.5 projection_thread_sessions`
- Requirement: persisted thread session projection table.
- SQL contract:
@@ -233,7 +219,6 @@ Status legend:
- Notes: current provider session table is not this domain projection.
### P6
- Spec ref: `7.3.6 projection_thread_turns`
- Requirement: persisted thread turn projection table.
- SQL contract:
@@ -252,7 +237,6 @@ Status legend:
- Notes: missing table and projection logic.
### P7
- Spec ref: `7.3.7 projection_checkpoints`
- Requirement: persisted checkpoint summary projection table.
- SQL contract:
@@ -272,7 +256,6 @@ Status legend:
- Notes: current table semantics do not match canonical checkpoint projection schema.
### P8
- Spec ref: `7.3.8 projection_pending_approvals`
- Requirement: persisted pending-approval projection table.
- SQL contract:
@@ -290,7 +273,6 @@ Status legend:
- Notes: missing table and projection logic.
### P9
- Spec ref: `7.3.9 projection_state`
- Requirement: projector progress tracking table.
- SQL contract:
@@ -304,7 +286,6 @@ Status legend:
- Notes: missing table and projector bookkeeping.
### P10
- Spec ref: `7.3 Projection consistency rules`
- Requirement: projector row updates and `projection_state` update must be atomic per event.
- SQL contract: per-projector transaction boundary covering both projection write and state update.
@@ -315,7 +296,6 @@ Status legend:
- Notes: requires transactional projection executor.
### P11
- Spec ref: `7.3 Optional debug field`
- Requirement: `lastEventSequence` on projection rows is optional and not required for correctness.
- SQL contract: optional; not required in baseline schema.
@@ -328,7 +308,6 @@ Status legend:
## 7.4 Snapshot and RPC Requirements
### R1
- Spec ref: `7.4.1`
- Requirement: `orchestration.getSnapshot` fully served from projection tables and returns `snapshotSequence`.
- SQL contract: snapshot query joins/reads only `projection_*` + `projection_state`.
@@ -339,7 +318,6 @@ Status legend:
- Notes: current in-memory read model path must be removed for SPEC compliance.
### R2
- Spec ref: `7.4.2`
- Requirement: snapshot `projects[]` source is `projection_projects`.
- SQL contract: `projects` collection assembled from `projection_projects` rows.
@@ -350,7 +328,6 @@ Status legend:
- Notes: no DB project projection reader exists yet.
### R3
- Spec ref: `7.4.3`
- Requirement: thread snapshot `checkpoints[]` source is `projection_checkpoints` with required fields.
- SQL contract: fields `turnId`, `completedAt`, `status`, `files[]`, `checkpointRef`, optional `assistantMessageId`, `checkpointTurnCount`.
@@ -361,7 +338,6 @@ Status legend:
- Notes: canonical projection table and reader not implemented.
### R4
- Spec ref: `7.4.4`
- Requirement: no `listCheckpoints` orchestration RPC; list in snapshot + full diff via `getTurnDiff` from diff blobs.
- SQL contract: `getTurnDiff` reads `checkpoint_diff_blobs` only.
@@ -372,7 +348,6 @@ Status legend:
- Notes: current checkpoint repository is not canonical source.
### R5
- Spec ref: `7.4.5`
- Requirement: client acts on `ThreadId`; server resolves provider session via `projection_thread_sessions`.
- SQL contract: session lookup by `thread_id` from projection table.
@@ -383,7 +358,6 @@ Status legend:
- Notes: remove provider-session-as-routing-key behavior.
### R6
- Spec ref: `7.4.6`
- Requirement: `snapshotSequence` derived from `projection_state` minimum over dependent projectors.
- SQL contract: `MIN(last_applied_sequence)` across required projector keys.
@@ -394,7 +368,6 @@ Status legend:
- Notes: must move from in-memory sequence to DB projection-state semantics.
### R7
- Spec ref: `7.4.7`
- Requirement: snapshot/replay handoff has no gap (`getSnapshot` -> subscribe from snapshot sequence).
- SQL contract: read consistency strategy guaranteeing no missing events between snapshot visibility and replay start.
@@ -407,27 +380,22 @@ Status legend:
## Ambiguous/Interpretation Decisions (tracked upfront)
### A1
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
### A2
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
### A3
- Topic: `snapshotSequence` dependency set for min-sequence computation.
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
### A4
- Topic: no-gap handoff mechanism in `7.4.7`.
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
## Checklist Completeness Statement
- Coverage scope: `SPEC.md` sections `7.1`, `7.2`, `7.3`, `7.4`.
- Requirement rows present: `W1-W4`, `E1-E4`, `P1-P11`, `R1-R7`.
- Unclassified rows: `0`.
+3 -3
View File
@@ -2,12 +2,12 @@
## Task Completion Requirements
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- Both `bun lint` and `bun typecheck` must pass before considering tasks completed.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
T3 Code is a minimal web GUI for using coding agents like Codex and Claude.
T3 Code is a minimal web GUI for using code agents like Codex and Claude Code (coming soon).
This repository is a VERY EARLY WIP. Proposing sweeping changes that improve long-term maintainability is encouraged.
@@ -21,7 +21,7 @@ If a tradeoff is required, choose correctness and robustness over short-term con
## Maintainability
Long term maintainability is a core priority. If you add new functionality, first check if there is shared logic that can be extracted to a separate module. Duplicate logic across multiple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
## Package Roles
+1 -1
View File
@@ -8,7 +8,7 @@ You can still open an issue or PR, but please do so knowing there is a high chan
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
PRs are automatically labeled with a `vouch:*` trust status and a `size:*` diff size based on changed lines.
PRs are automatically labeled with a `vouch:*` trust status.
If you are an external contributor, expect `vouch:unvouched` until we explicitly add you to [.github/VOUCHED.td](.github/VOUCHED.td).
+1 -1
View File
@@ -51,7 +51,7 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
- `terminal.new`: create new terminal (in focused terminal context by default)
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
- `chat.newLocal`: create a new local chat thread for the active project (no worktree context)
- `editor.openFavorite`: open current project/worktree in the last-used editor
- `script.{id}.run`: run a project script by id (for example `script.test.run`)
+5 -29
View File
@@ -1,43 +1,19 @@
# T3 Code
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
## Installation
## How to use
> [!WARNING]
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
```bash
npx t3
```
### Desktop app
You can also just install the desktop app. It's cooler.
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
#### Windows (`winget`)
```bash
winget install T3Tools.T3Code
```
#### macOS (Homebrew)
```bash
brew install --cask t3-code
```
#### Arch Linux (AUR)
```bash
yay -S t3code-bin
```
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
## Some notes
+9 -12
View File
@@ -6,24 +6,21 @@ Use this when you want to open T3 Code from another device (phone, tablet, anoth
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
| CLI flag | Env var | Notes |
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
| CLI flag | Env var | Notes |
| ----------------------- | --------------------- | ---------------------------------- |
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
> TIP: Use the `--help` flag to see all available options and their descriptions.
## Security First
- Always set `--auth-token` before exposing the server outside localhost.
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
- Treat the token like a password.
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
+3 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.15",
"version": "0.0.9",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
@@ -24,7 +24,8 @@
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
"vitest": "catalog:",
"wait-on": "^8.0.2"
},
"productName": "T3 Code (Alpha)"
}
+13 -24
View File
@@ -1,29 +1,23 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/bin.mjs",
];
const requiredFiles = ["dist-electron/main.js", "dist-electron/preload.js", "../server/dist/index.mjs"];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitForResources({
baseDir: desktopDir,
files: requiredFiles,
tcpPort: port,
await waitOn({
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
});
const childEnv = { ...process.env };
@@ -82,13 +76,12 @@ function startApp() {
}
});
app.once("exit", (code, signal) => {
app.once("exit", () => {
if (currentApp === app) {
currentApp = null;
}
const exitedAbnormally = signal !== null || code !== 0;
if (!shuttingDown && !expectedExits.has(app) && exitedAbnormally) {
if (!shuttingDown && !expectedExits.has(app)) {
scheduleRestart();
}
});
@@ -155,17 +148,13 @@ function scheduleRestart() {
function startWatchers() {
for (const { directory, files } of watchedDirectories) {
const watcher = watch(
join(desktopDir, directory),
{ persistent: true },
(_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
const watcher = watch(join(desktopDir, directory), { persistent: true }, (_eventType, filename) => {
if (typeof filename !== "string" || !files.has(filename)) {
return;
}
scheduleRestart();
},
);
scheduleRestart();
});
watchers.push(watcher);
}
-119
View File
@@ -1,119 +0,0 @@
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await FileSystem.access(filePath);
return true;
} catch {
return false;
}
}
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = Net.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
if (settled) {
return;
}
settled = true;
socket.removeAllListeners();
socket.destroy();
resolveReady(ready);
};
socket.once("connect", () => {
finish(true);
});
socket.once("timeout", () => {
finish(false);
});
socket.once("error", () => {
finish(false);
});
socket.setTimeout(connectTimeoutMs);
});
}
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
}
let tcpReady = false;
for (const host of tcpHosts) {
tcpReady = await tcpPortIsReady({
host,
port: tcpPort,
connectTimeoutMs,
});
if (tcpReady) {
break;
}
}
return {
pendingFiles,
tcpReady,
};
}
export async function waitForResources({
baseDir,
files = [],
intervalMs = 100,
timeoutMs = 120_000,
tcpHost,
tcpPort,
connectTimeoutMs = 500,
}) {
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
throw new TypeError("waitForResources requires a positive integer tcpPort");
}
const startedAt = Date.now();
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
while (true) {
const { pendingFiles, tcpReady } = await resolvePendingResources({
baseDir,
files,
tcpPort,
tcpHosts,
connectTimeoutMs,
});
if (pendingFiles.length === 0 && tcpReady) {
return;
}
if (Date.now() - startedAt >= timeoutMs) {
const pendingResources = [];
if (!tcpReady) {
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
}
for (const filePath of pendingFiles) {
pendingResources.push(`file:${filePath}`);
}
throw new Error(
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
);
}
await Timers.setTimeout(intervalMs);
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
+15
View File
@@ -0,0 +1,15 @@
import { readPathFromLoginShell } from "@t3tools/shared/shell";
export function fixPath(): void {
if (process.platform !== "darwin") return;
try {
const shell = process.env.SHELL ?? "/bin/zsh";
const result = readPathFromLoginShell(shell);
if (result) {
process.env.PATH = result;
}
} catch {
// Keep inherited PATH if shell lookup fails.
}
}
+41 -198
View File
@@ -4,33 +4,21 @@ import * as FS from "node:fs";
import * as OS from "node:os";
import * as Path from "node:path";
import {
app,
BrowserWindow,
dialog,
ipcMain,
Menu,
nativeImage,
nativeTheme,
protocol,
shell,
} from "electron";
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from "electron";
import type { MenuItemConstructorOptions } from "electron";
import * as Effect from "effect/Effect";
import type {
DesktopTheme,
DesktopUpdateActionResult,
DesktopUpdateCheckResult,
DesktopUpdateState,
} from "@t3tools/contracts";
import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/contracts";
import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
import { fixPath } from "./fixPath";
import {
getAutoUpdateDisabledReason,
shouldBroadcastDownloadProgress,
} from "./updateState";
import {
createInitialDesktopUpdateState,
reduceDesktopUpdateStateOnCheckFailure,
@@ -45,11 +33,10 @@ import {
} from "./updateMachine";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
syncShellEnvironment();
fixPath();
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
@@ -57,17 +44,13 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const STATE_DIR =
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
@@ -82,9 +65,6 @@ const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
type LinuxDesktopNamedApp = Electron.App & {
setDesktopName?: (desktopName: string) => void;
};
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess.ChildProcess | null = null;
@@ -121,17 +101,6 @@ function sanitizeLogValue(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function backendChildEnv(): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env.T3CODE_PORT;
delete env.T3CODE_AUTH_TOKEN;
delete env.T3CODE_MODE;
delete env.T3CODE_NO_BROWSER;
delete env.T3CODE_HOST;
delete env.T3CODE_DESKTOP_WS_URL;
return env;
}
function writeDesktopLogHeader(message: string): void {
if (!desktopLogSink) return;
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
@@ -171,14 +140,6 @@ function getSafeExternalUrl(rawUrl: unknown): string | null {
return parsedUrl.toString();
}
function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
if (rawTheme === "light" || rawTheme === "dark" || rawTheme === "system") {
return rawTheme;
}
return null;
}
function writeDesktopStreamChunk(
streamName: "stdout" | "stderr",
chunk: unknown,
@@ -268,10 +229,6 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void {
initializePackagedLogging();
if (process.platform === "linux") {
app.commandLine.appendSwitch("class", LINUX_WM_CLASS);
}
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
if (process.platform !== "darwin") return undefined;
if (destructiveMenuIconCache !== undefined) {
@@ -298,12 +255,10 @@ let updatePollTimer: ReturnType<typeof setInterval> | null = null;
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
let updateCheckInFlight = false;
let updateDownloadInFlight = false;
let updateInstallInFlight = false;
let updaterConfigured = false;
let updateState: DesktopUpdateState = initialUpdateState();
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
if (updateInstallInFlight) return "install";
if (updateDownloadInFlight) return "download";
if (updateCheckInFlight) return "check";
return updateState.errorContext;
@@ -399,7 +354,7 @@ function resolveAboutCommitHash(): string | null {
}
function resolveBackendEntry(): string {
return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs");
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
@@ -560,28 +515,7 @@ function handleCheckForUpdatesMenuClick(): void {
if (!BrowserWindow.getAllWindows().length) {
mainWindow = createWindow();
}
void checkForUpdatesFromMenu();
}
async function checkForUpdatesFromMenu(): Promise<void> {
await checkForUpdates("menu");
if (updateState.status === "up-to-date") {
void dialog.showMessageBox({
type: "info",
title: "You're up to date!",
message: `T3 Code ${updateState.currentVersion} is currently the newest version available.`,
buttons: ["OK"],
});
} else if (updateState.status === "error") {
void dialog.showMessageBox({
type: "warning",
title: "Update check failed",
message: "Could not check for updates.",
detail: updateState.message ?? "An unknown error occurred. Please try again later.",
buttons: ["OK"],
});
}
void checkForUpdates("menu");
}
function configureApplicationMenu(): void {
@@ -632,21 +566,7 @@ function configureApplicationMenu(): void {
],
},
{ role: "editMenu" },
{
label: "View",
submenu: [
{ role: "reload" },
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
{ type: "separator" },
{ role: "togglefullscreen" },
],
},
{ role: "viewMenu" },
{ role: "windowMenu" },
{
role: "help",
@@ -665,7 +585,6 @@ function configureApplicationMenu(): void {
function resolveResourcePath(fileName: string): string | null {
const candidates = [
Path.join(__dirname, "../resources", fileName),
Path.join(__dirname, "../prod-resources", fileName),
Path.join(process.resourcesPath, "resources", fileName),
Path.join(process.resourcesPath, fileName),
];
@@ -724,10 +643,6 @@ function configureAppIdentity(): void {
app.setAppUserModelId(APP_USER_MODEL_ID);
}
if (process.platform === "linux") {
(app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME);
}
if (process.platform === "darwin" && app.dock) {
const iconPath = resolveIconPath("png");
if (iconPath) {
@@ -771,13 +686,13 @@ function shouldEnableAutoUpdates(): boolean {
);
}
async function checkForUpdates(reason: string): Promise<boolean> {
if (isQuitting || !updaterConfigured || updateCheckInFlight) return false;
async function checkForUpdates(reason: string): Promise<void> {
if (isQuitting || !updaterConfigured || updateCheckInFlight) return;
if (updateState.status === "downloading" || updateState.status === "downloaded") {
console.info(
`[desktop-updater] Skipping update check (${reason}) while status=${updateState.status}.`,
);
return false;
return;
}
updateCheckInFlight = true;
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
@@ -785,14 +700,10 @@ async function checkForUpdates(reason: string): Promise<boolean> {
try {
await autoUpdater.checkForUpdates();
return true;
} catch (error: unknown) {
const message = error instanceof Error ? error.message : String(error);
setUpdateState(
reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()),
);
setUpdateState(reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()));
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
return true;
} finally {
updateCheckInFlight = false;
}
@@ -826,22 +737,13 @@ async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed
}
isQuitting = true;
updateInstallInFlight = true;
clearUpdatePollTimer();
try {
await stopBackendAndWaitForExit();
// Destroy all windows before launching the NSIS installer to avoid the installer finding live windows it needs to close.
for (const win of BrowserWindow.getAllWindows()) {
win.destroy();
}
// `quitAndInstall()` only starts the handoff to the updater. The actual
// install may still fail asynchronously, so keep the action incomplete
// until we either quit or receive an updater error.
autoUpdater.quitAndInstall(true, true);
return { accepted: true, completed: false };
autoUpdater.quitAndInstall();
return { accepted: true, completed: true };
} catch (error: unknown) {
const message = formatErrorMessage(error);
updateInstallInFlight = false;
isQuitting = false;
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
console.error(`[desktop-updater] Failed to install update: ${message}`);
@@ -862,7 +764,9 @@ function configureAutoUpdater(): void {
updaterConfigured = true;
const githubToken =
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() || process.env.GH_TOKEN?.trim() || "";
process.env.T3CODE_DESKTOP_UPDATE_GITHUB_TOKEN?.trim() ||
process.env.GH_TOKEN?.trim() ||
"";
if (githubToken) {
// When a token is provided, re-configure the feed with `private: true` so
// electron-updater uses the GitHub API (api.github.com) instead of the
@@ -878,13 +782,6 @@ function configureAutoUpdater(): void {
}
}
if (process.env.T3CODE_DESKTOP_MOCK_UPDATES) {
autoUpdater.setFeedURL({
provider: "generic",
url: `http://localhost:${process.env.T3CODE_DESKTOP_MOCK_UPDATE_SERVER_PORT ?? 3000}`,
});
}
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
// Keep alpha branding, but force all installs onto the stable update track.
@@ -904,13 +801,7 @@ function configureAutoUpdater(): void {
console.info("[desktop-updater] Looking for updates...");
});
autoUpdater.on("update-available", (info) => {
setUpdateState(
reduceDesktopUpdateStateOnUpdateAvailable(
updateState,
info.version,
new Date().toISOString(),
),
);
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));
lastLoggedDownloadMilestone = -1;
console.info(`[desktop-updater] Update available: ${info.version}`);
});
@@ -921,13 +812,6 @@ function configureAutoUpdater(): void {
});
autoUpdater.on("error", (error) => {
const message = formatErrorMessage(error);
if (updateInstallInFlight) {
updateInstallInFlight = false;
isQuitting = false;
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
console.error(`[desktop-updater] Updater error: ${message}`);
return;
}
if (!updateCheckInFlight && !updateDownloadInFlight) {
setUpdateState({
status: "error",
@@ -972,6 +856,17 @@ function configureAutoUpdater(): void {
}, AUTO_UPDATE_POLL_INTERVAL_MS);
updatePollTimer.unref();
}
function backendEnv(): NodeJS.ProcessEnv {
return {
...process.env,
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_STATE_DIR: STATE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
@@ -995,35 +890,16 @@ function startBackend(): void {
}
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
cwd: resolveBackendCwd(),
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendChildEnv(),
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
stdio: captureBackendLogs
? ["ignore", "pipe", "pipe", "pipe"]
: ["ignore", "inherit", "inherit", "pipe"],
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
});
const bootstrapStream = child.stdio[3];
if (bootstrapStream && "write" in bootstrapStream) {
bootstrapStream.write(
`${JSON.stringify({
mode: "desktop",
noBrowser: true,
port: backendPort,
t3Home: BASE_DIR,
authToken: backendAuthToken,
})}\n`,
);
bootstrapStream.end();
} else {
child.kill("SIGTERM");
scheduleBackendRestart("missing desktop bootstrap pipe");
return;
}
backendProcess = child;
let backendSessionClosed = false;
const closeBackendSession = (details: string) => {
@@ -1134,11 +1010,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
event.returnValue = backendWsUrl;
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -1163,16 +1034,6 @@ function registerIpcHandlers(): void {
return showDesktopConfirmDialog(message, owner);
});
ipcMain.removeHandler(SET_THEME_CHANNEL);
ipcMain.handle(SET_THEME_CHANNEL, async (_event, rawTheme: unknown) => {
const theme = getSafeTheme(rawTheme);
if (!theme) {
return;
}
nativeTheme.themeSource = theme;
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
@@ -1183,7 +1044,6 @@ function registerIpcHandlers(): void {
id: item.id,
label: item.label,
destructive: item.destructive === true,
disabled: item.disabled === true,
}));
if (normalizedItems.length === 0) {
return null;
@@ -1214,7 +1074,6 @@ function registerIpcHandlers(): void {
}
const itemOption: MenuItemConstructorOptions = {
label: item.label,
enabled: !item.disabled,
click: () => resolve(item.id),
};
if (item.destructive) {
@@ -1280,21 +1139,6 @@ function registerIpcHandlers(): void {
state: updateState,
} satisfies DesktopUpdateActionResult;
});
ipcMain.removeHandler(UPDATE_CHECK_CHANNEL);
ipcMain.handle(UPDATE_CHECK_CHANNEL, async () => {
if (!updaterConfigured) {
return {
checked: false,
state: updateState,
} satisfies DesktopUpdateCheckResult;
}
const checked = await checkForUpdates("web-ui");
return {
checked,
state: updateState,
} satisfies DesktopUpdateCheckResult;
});
}
function getIconOption(): { icon: string } | Record<string, never> {
@@ -1404,9 +1248,9 @@ async function bootstrap(): Promise<void> {
);
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
backendAuthToken = Crypto.randomBytes(24).toString("hex");
const baseUrl = `ws://127.0.0.1:${backendPort}`;
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
registerIpcHandlers();
writeDesktopLogHeader("bootstrap ipc handlers registered");
@@ -1418,7 +1262,6 @@ async function bootstrap(): Promise<void> {
app.on("before-quit", () => {
isQuitting = true;
updateInstallInFlight = false;
writeDesktopLogHeader("before-quit received");
clearUpdatePollTimer();
stopBackend();
@@ -1448,7 +1291,7 @@ app
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin" && !isQuitting) {
if (process.platform !== "darwin") {
app.quit();
}
});
+2 -9
View File
@@ -3,25 +3,19 @@ import type { DesktopBridge } from "@t3tools/contracts";
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
const CONFIRM_CHANNEL = "desktop:confirm";
const SET_THEME_CHANNEL = "desktop:set-theme";
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
const MENU_ACTION_CHANNEL = "desktop:menu-action";
const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => {
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
return typeof result === "string" ? result : null;
},
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
onMenuAction: (listener) => {
@@ -36,7 +30,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
onUpdateState: (listener) => {
+2 -1
View File
@@ -25,7 +25,8 @@ export function resolveDesktopRuntimeInfo(
};
}
const hostArch = appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
const hostArch =
appArch === "arm64" || input.runningUnderArm64Translation ? "arm64" : appArch;
return {
hostArch,
@@ -1,105 +0,0 @@
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
describe("syncShellEnvironment", () => {
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("preserves an inherited SSH_AUTH_SOCK value", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/login-shell.sock",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("preserves inherited values when the login shell omits them", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/opt/homebrew/bin:/usr/bin",
}));
syncShellEnvironment(env, {
platform: "darwin",
readEnvironment,
});
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
const readEnvironment = vi.fn(() => ({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "linux",
readEnvironment,
});
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
});
it("does nothing outside macOS and linux", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "C:/Program Files/Git/bin/bash.exe",
PATH: "C:\\Windows\\System32",
SSH_AUTH_SOCK: "/tmp/inherited.sock",
};
const readEnvironment = vi.fn(() => ({
PATH: "/usr/local/bin:/usr/bin",
SSH_AUTH_SOCK: "/tmp/secretive.sock",
}));
syncShellEnvironment(env, {
platform: "win32",
readEnvironment,
});
expect(readEnvironment).not.toHaveBeenCalled();
expect(env.PATH).toBe("C:\\Windows\\System32");
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
});
});
-36
View File
@@ -1,36 +0,0 @@
import {
readEnvironmentFromLoginShell,
resolveLoginShell,
ShellEnvironmentReader,
} from "@t3tools/shared/shell";
export function syncShellEnvironment(
env: NodeJS.ProcessEnv = process.env,
options: {
platform?: NodeJS.Platform;
readEnvironment?: ShellEnvironmentReader;
} = {},
): void {
const platform = options.platform ?? process.platform;
if (platform !== "darwin" && platform !== "linux") return;
try {
const shell = resolveLoginShell(platform, env.SHELL);
if (!shell) return;
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.
}
}
+1 -4
View File
@@ -83,10 +83,7 @@ describe("updateMachine", () => {
},
"1.1.0",
);
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(
downloaded,
"backend shutdown timed out",
);
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
expect(downloaded.status).toBe("downloaded");
expect(downloaded.downloadedVersion).toBe("1.1.0");
+2 -2
View File
@@ -10,10 +10,10 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^5.7.13"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
"@astrojs/check": "^0.9.4",
"typescript": "catalog:"
}
}
-228
View File
@@ -1,228 +0,0 @@
---
interface Props {
title?: string;
description?: string;
}
const {
title = "T3 Code",
description = "T3 Code — The best way to code with AI.",
} = Astro.props;
---
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content={description} />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>{title}</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<main class="main">
<slot />
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<style is:global>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
</style>
<style>
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem;
}
.footer {
padding: 1.25rem;
}
}
</style>
-30
View File
@@ -1,30 +0,0 @@
const REPO = "pingdotgg/t3code";
export const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
const CACHE_KEY = "t3code-latest-release";
export interface ReleaseAsset {
name: string;
browser_download_url: string;
}
export interface Release {
tag_name: string;
html_url: string;
assets: ReleaseAsset[];
}
export async function fetchLatestRelease(): Promise<Release> {
const cached = sessionStorage.getItem(CACHE_KEY);
if (cached) return JSON.parse(cached);
const data = await fetch(API_URL).then((r) => r.json());
if (data?.assets) {
sessionStorage.setItem(CACHE_KEY, JSON.stringify(data));
}
return data;
}
-271
View File
@@ -1,271 +0,0 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
<h1 class="heading">Download T3 Code</h1>
<p class="subheading">
<span id="version-label">Loading latest release&hellip;</span>
<a id="changelog-link" class="changelog-link" href="#" target="_blank" rel="noopener noreferrer" style="display:none">View changelog<span aria-hidden="true"> &#8599;</span></a>
</p>
<div class="platforms" id="platforms">
<!-- macOS -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<h2 class="platform-name">macOS</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="arm64.dmg" href="#">
<span class="card-arch">Apple Silicon (arm64)</span>
<span class="card-format">.dmg</span>
</a>
<a class="download-card" data-asset="x64.dmg" href="#">
<span class="card-arch">Intel (x64)</span>
<span class="card-format">.dmg</span>
</a>
</div>
</section>
<!-- Windows -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<h2 class="platform-name">Windows</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x64.exe" href="#">
<span class="card-arch">Windows 10, 11</span>
<span class="card-format">.exe</span>
</a>
</div>
</section>
<!-- Linux -->
<section class="platform-section">
<div class="platform-header">
<svg class="platform-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<h2 class="platform-name">Linux</h2>
</div>
<div class="download-cards">
<a class="download-card" data-asset="x86_64.AppImage" href="#">
<span class="card-arch">x86_64</span>
<span class="card-format">AppImage</span>
</a>
</div>
</section>
</div>
<p class="releases-link">
Looking for older versions? Check the
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
</p>
</Layout>
<script>
import { fetchLatestRelease, RELEASES_URL } from "../lib/releases";
async function init() {
const versionLabel = document.getElementById("version-label");
const cards = document.querySelectorAll<HTMLAnchorElement>(".download-card");
try {
const release = await fetchLatestRelease();
if (versionLabel && release.tag_name) {
versionLabel.textContent = `Latest (${release.tag_name})`;
}
const changelogLink = document.getElementById("changelog-link") as HTMLAnchorElement | null;
if (changelogLink && release.html_url) {
changelogLink.href = release.html_url;
changelogLink.style.display = "";
}
cards.forEach((card) => {
const suffix = card.dataset.asset;
if (!suffix) return;
const match = (release.assets ?? []).find((a) => a.name.endsWith(`-${suffix}`));
if (match) {
card.href = match.browser_download_url;
} else {
card.href = RELEASES_URL;
}
});
} catch {
if (versionLabel) {
versionLabel.textContent = "Could not load release info.";
}
cards.forEach((card) => {
card.href = RELEASES_URL;
});
}
}
init();
</script>
<style>
.main {
padding: 8vh 1.5rem 4rem;
}
/* ── Heading ── */
.heading {
font-weight: 500;
font-size: clamp(1.75rem, 4vw, 2.75rem);
letter-spacing: -0.035em;
line-height: 1.15;
text-align: center;
margin-bottom: 0.5rem;
opacity: 0;
animation: fade-in 1s ease-out forwards;
}
.subheading {
font-size: 0.9rem;
color: var(--fg-dim);
margin-bottom: 3.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.1s forwards;
display: flex;
align-items: center;
gap: 0.75rem;
}
.changelog-link {
color: var(--fg-muted);
font-size: 0.8rem;
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.changelog-link:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Platforms ── */
.platforms {
width: 100%;
max-width: 720px;
display: flex;
flex-direction: column;
gap: 2.5rem;
opacity: 0;
animation: fade-in 1s ease-out 0.2s forwards;
}
.platform-section {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.platform-header {
display: flex;
align-items: center;
gap: 0.6rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--border);
}
.platform-icon {
width: 1.15em;
height: 1.15em;
color: var(--fg-muted);
flex-shrink: 0;
}
.platform-name {
font-weight: 500;
font-size: 1.1rem;
letter-spacing: -0.01em;
}
/* ── Download cards ── */
.download-cards {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 0.5rem;
}
.download-card {
display: flex;
flex-direction: column;
gap: 0.2rem;
padding: 0.85rem 1rem;
border-radius: 10px;
border: 1px solid var(--border);
background: rgba(255, 255, 255, 0.02);
transition: background 0.2s ease, border-color 0.2s ease, transform 0.2s ease;
}
.download-card:hover {
background: rgba(255, 255, 255, 0.06);
border-color: rgba(255, 255, 255, 0.15);
transform: translateY(-1px);
}
.download-card:active {
transform: translateY(0);
}
.card-arch {
font-weight: 600;
font-size: 0.95rem;
}
.card-format {
font-size: 0.8rem;
color: var(--fg-dim);
}
/* ── Releases link ── */
.releases-link {
margin-top: 3rem;
font-size: 0.825rem;
color: var(--fg-dim);
opacity: 0;
animation: fade-in 1s ease-out 0.35s forwards;
}
.releases-link a {
color: var(--fg-muted);
text-decoration: underline;
text-decoration-color: rgba(161, 161, 170, 0.4);
text-underline-offset: 3px;
transition: color 0.3s ease, text-decoration-color 0.3s ease;
}
.releases-link a:hover {
color: var(--fg);
text-decoration-color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.main {
padding: 5vh 1.25rem 4rem;
}
.platforms {
padding: 0 0.25rem;
}
.download-cards {
grid-template-columns: 1fr;
}
}
</style>
+238 -42
View File
@@ -1,30 +1,75 @@
---
import Layout from "../layouts/Layout.astro";
---
<Layout>
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="T3 Code — The best way to code with AI." />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16" />
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
<title>T3 Code</title>
</head>
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
</nav>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
class="hero-button"
>
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<span id="download-label">Download now</span>
</a>
<main class="main">
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
<a href="/download" class="other-platforms">Other platforms</a>
<a
id="download-btn"
href="https://github.com/pingdotgg/t3code/releases"
class="hero-button"
>
<svg class="hero-button-icon hero-button-icon--apple" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 814 1000" aria-hidden="true"><path fill="currentColor" d="M788.1 340.9c-5.8 4.5-108.2 62.2-108.2 190.5 0 148.4 130.3 200.9 134.2 202.2-.6 3.2-20.7 71.9-68.7 141.9-42.8 61.6-87.5 123.1-155.5 123.1s-85.5-39.5-164-39.5c-76.5 0-103.7 40.8-165.9 40.8s-105.6-57-155.5-127C46.7 790.7 0 663 0 541.8c0-194.4 126.4-297.5 250.8-297.5 66.1 0 121.2 43.4 162.7 43.4 39.5 0 101.1-46 176.3-46 28.5 0 130.9 2.6 198.3 99.2zm-234-181.5c31.1-36.9 53.1-88.1 53.1-139.3 0-7.1-.6-14.3-1.9-20.1-50.6 1.9-110.8 33.7-147.1 75.8-28.5 32.4-55.1 83.6-55.1 135.5 0 7.8 1.3 15.6 1.9 18.1 3.2.6 8.4 1.3 13.6 1.3 45.4 0 102.5-30.4 135.5-71.3z"/></svg>
<svg class="hero-button-icon hero-button-icon--windows" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 88 88" aria-hidden="true"><path fill="currentColor" d="m0 12.402 35.687-4.86.016 34.423-35.67.203zm35.67 33.529.028 34.453L.028 75.48.026 45.7zm4.326-39.025L87.314 0v41.527l-47.318.376zm47.329 39.349-.011 41.34-47.318-6.678-.066-34.739z"/></svg>
<svg class="hero-button-icon hero-button-icon--linux" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 295" aria-hidden="true"><defs><linearGradient id="lt0" x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt6" x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%"><stop offset="0%" stop-color="#FFEED7"/><stop offset="100%" stop-color="#BDBFC2"/></linearGradient><linearGradient id="lt8" x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%"><stop offset="0%" stop-color="#FFF" stop-opacity=".8"/><stop offset="100%" stop-color="#FFF" stop-opacity="0"/></linearGradient><linearGradient id="ltc" x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lte" x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient><linearGradient id="lti" x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%"><stop offset="0%" stop-color="#FFA63F"/><stop offset="100%" stop-color="#FF0"/></linearGradient></defs><g fill="none"><path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905"/><path fill="url(#lt6)" d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903"/><path fill="url(#lt8)" d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293"/><path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z"/><path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z"/><path fill="url(#ltc)" stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)"/><path fill="url(#lte)" stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)"/><path fill="url(#lti)" stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)"/><path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255"/></g></svg>
<span id="download-label">Download now</span>
</a>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</Layout>
<div class="screenshot-wrap">
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
</div>
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
</div>
</footer>
</div>
</body>
</html>
<script>
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
const REPO = "pingdotgg/t3code";
const RELEASES_URL = `https://github.com/${REPO}/releases`;
const API_URL = `https://api.github.com/repos/${REPO}/releases/latest`;
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
@@ -42,7 +87,10 @@ import Layout from "../layouts/Layout.astro";
return null;
}
function pickAsset(assets: ReleaseAsset[], platform: Platform): string | null {
function pickAsset(
assets: Array<{ name: string; browser_download_url: string }>,
platform: Platform,
): string | null {
if (platform.os === "win") {
return (
assets.find((a) => a.name.endsWith("-x64.exe"))
@@ -77,8 +125,16 @@ import Layout from "../layouts/Layout.astro";
label.textContent = platform.label;
try {
const release = await fetchLatestRelease();
const url = pickAsset(release.assets ?? [], platform);
const cached = sessionStorage.getItem("t3code-latest-release");
const data = cached
? JSON.parse(cached)
: await fetch(API_URL).then((r) => r.json());
if (!cached && data?.assets) {
sessionStorage.setItem("t3code-latest-release", JSON.stringify(data));
}
const url = pickAsset(data.assets ?? [], platform);
if (url) {
btn.href = url;
btn.removeAttribute("target");
@@ -93,7 +149,120 @@ import Layout from "../layouts/Layout.astro";
</script>
<style>
:root {
--bg: #09090b;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--border: rgba(255, 255, 255, 0.08);
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
color-scheme: dark;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
}
body::after {
content: "";
position: fixed;
inset: 0;
pointer-events: none;
opacity: 0.035;
background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
background-repeat: repeat;
background-size: 256px 256px;
z-index: 9999;
}
a {
color: inherit;
text-decoration: none;
}
img {
display: block;
max-width: 100%;
}
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
flex-direction: column;
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
}
.nav-brand {
display: flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
}
/* ── Main content ── */
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding-top: 10vh;
}
@@ -122,7 +291,7 @@ import Layout from "../layouts/Layout.astro";
border-radius: 999px;
font-weight: 600;
font-size: 0.9rem;
margin-bottom: 1.25rem;
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.15s forwards;
transition: transform 0.25s ease, box-shadow 0.25s ease;
@@ -156,25 +325,6 @@ import Layout from "../layouts/Layout.astro";
display: block;
}
/* ── Other platforms link ── */
.other-platforms {
font-size: 0.825rem;
color: var(--fg-dim);
margin-bottom: 5vh;
opacity: 0;
animation: fade-in 1s ease-out 0.3s forwards;
transition: color 0.3s ease;
text-decoration: underline;
text-decoration-color: rgba(113, 113, 122, 0.4);
text-underline-offset: 3px;
}
.other-platforms:hover {
color: var(--fg-muted);
text-decoration-color: var(--fg-muted);
}
/* ── Screenshot ── */
.screenshot-wrap {
@@ -208,6 +358,44 @@ import Layout from "../layouts/Layout.astro";
pointer-events: none;
}
/* ── Footer ── */
.footer {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
color: var(--fg-dim);
}
.footer-links {
display: flex;
gap: 1.25rem;
}
.footer-links a {
color: var(--fg-dim);
transition: color 0.3s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Animations ── */
@keyframes fade-in {
from {
opacity: 0;
transform: translateY(8px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes screenshot-in {
from {
opacity: 0;
@@ -222,6 +410,10 @@ import Layout from "../layouts/Layout.astro";
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem 1.25rem;
}
.main {
padding-top: 7vh;
}
@@ -233,5 +425,9 @@ import Layout from "../layouts/Layout.astro";
.screenshot-wrap {
width: 95vw;
}
.footer {
padding: 1.25rem;
}
}
</style>
@@ -1,20 +1,20 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
ApprovalRequestId,
ProviderKind,
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
FileSystem,
Layer,
ManagedRuntime,
Option,
Path,
Ref,
Schedule,
Schema,
@@ -24,7 +24,6 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -38,7 +37,6 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
@@ -67,9 +65,7 @@ import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import { ServerConfig } from "../src/config.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -79,16 +75,14 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
});
}
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
const fileSystem = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
});
}
export function gitRefExists(cwd: string, ref: string): boolean {
try {
@@ -126,7 +120,7 @@ function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 40_000,
timeoutMs = 10_000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
@@ -211,7 +205,7 @@ export interface OrchestrationIntegrationHarness {
}
interface MakeOrchestrationIntegrationHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
readonly realCodex?: boolean;
}
@@ -219,9 +213,7 @@ export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const sleep = (ms: number) => Effect.sleep(ms);
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
@@ -238,16 +230,13 @@ export const makeOrchestrationIntegrationHarness = (
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
});
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const workspaceDir = path.join(rootDir, "workspace");
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
Effect.provideService(Path.Path, path),
);
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
yield* initializeGitWorkspace(workspaceDir);
const stateDir = path.join(rootDir, "state");
const dbPath = path.join(stateDir, "state.sqlite");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(stateDir, { recursive: true });
initializeGitWorkspace(workspaceDir);
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -272,7 +261,7 @@ export const makeOrchestrationIntegrationHarness = (
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
@@ -288,45 +277,32 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
CheckpointStoreLive,
providerLayer,
RuntimeReceiptBusLive,
);
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
} as unknown as GitCoreShape);
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
generateBranchName: () => Effect.succeed({ branch: null }),
} as unknown as TextGenerationShape);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
@@ -335,8 +311,7 @@ export const makeOrchestrationIntegrationHarness = (
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -370,13 +345,13 @@ export const makeOrchestrationIntegrationHarness = (
const scope = yield* Scope.make("sequential");
yield* tryRuntimePromise("start OrchestrationReactor", () =>
runtime.runPromise(reactor.start().pipe(Scope.provide(scope))),
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
).pipe(Effect.orDie);
const receiptHistory = yield* Ref.make<ReadonlyArray<OrchestrationRuntimeReceipt>>([]);
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
@@ -465,7 +440,9 @@ export const makeOrchestrationIntegrationHarness = (
return waitFor(
readMatchingReceipt,
(receipt): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
(
receipt,
): receipt is OrchestrationRuntimeReceipt => receipt !== undefined,
"runtime receipt",
timeoutMs,
);
@@ -493,7 +470,13 @@ export const makeOrchestrationIntegrationHarness = (
}
});
yield* shutdown;
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
@@ -10,7 +10,6 @@ import {
ProviderTurnStartResult,
ThreadId,
TurnId,
ProviderKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
@@ -36,7 +35,7 @@ export interface TestTurnResponse {
export type FixtureProviderRuntimeEvent = {
readonly type: string;
readonly eventId: EventId;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly createdAt: string;
readonly threadId: string;
readonly turnId?: string | undefined;
@@ -73,9 +72,10 @@ function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupt
return "completed";
}
function mapRequestType(
requestKind: unknown,
): "command_execution_approval" | "file_change_approval" | "unknown" {
function mapRequestType(requestKind: unknown):
| "command_execution_approval"
| "file_change_approval"
| "unknown" {
if (requestKind === "command") {
return "command_execution_approval";
}
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
export interface TestProviderAdapterHarness {
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
readonly provider: ProviderKind;
readonly provider: "codex";
readonly queueTurnResponse: (
threadId: ThreadId,
response: TestTurnResponse,
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
}
interface MakeTestProviderAdapterHarnessOptions {
readonly provider?: ProviderKind;
readonly provider?: "codex";
}
function nowIso(): string {
@@ -206,7 +206,7 @@ function nowIso(): string {
}
function sessionNotFound(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
@@ -216,7 +216,7 @@ function sessionNotFound(
}
function missingSessionEffect(
provider: ProviderKind,
provider: "codex",
threadId: ThreadId,
): Effect.Effect<never, ProviderAdapterError> {
return Effect.fail(sessionNotFound(provider, threadId));
@@ -239,323 +239,323 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
}>
>();
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== provider) {
return yield* new ProviderAdapterValidationError({
provider,
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
operation: "startSession",
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
});
}
return session;
sessionCount += 1;
const threadId = input.threadId;
const createdAt = nowIso();
const session: ProviderSession = {
provider,
status: "ready",
runtimeMode: input.runtimeMode,
threadId,
cwd: input.cwd,
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
createdAt,
updatedAt: createdAt,
};
sessions.set(threadId, {
session,
snapshot: {
threadId,
turns: [],
},
turnCount: 0,
queuedResponses: queuedResponsesForNextSession.splice(0),
rollbackCalls: [],
});
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
return session;
});
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* missingSessionEffect(provider, input.threadId);
}
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
state.turnCount += 1;
const turnCount = state.turnCount;
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
const response = state.queuedResponses.shift();
if (!response) {
return yield* new ProviderAdapterValidationError({
provider,
operation: "sendTurn",
issue: `No queued turn response for thread ${input.threadId}.`,
});
}
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
const assistantDeltas: string[] = [];
const deferredTurnCompletedEvents: ProviderRuntimeEvent[] = [];
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
provider,
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
createdAt: nowIso(),
};
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
rawEvent.turnId = turnId;
}
return {
const runtimeEvent = normalizeFixtureEvent(rawEvent);
const runtimeType = (runtimeEvent as { type: string }).type;
if (runtimeType === "content.delta") {
const payload = runtimeEvent.payload as { delta?: unknown } | undefined;
if (typeof payload?.delta === "string") {
assistantDeltas.push(payload.delta);
}
} else if (runtimeType === "message.delta") {
const legacyDelta = (runtimeEvent as { delta?: unknown }).delta;
if (typeof legacyDelta === "string") {
assistantDeltas.push(legacyDelta);
}
}
if (runtimeEvent.type === "turn.completed") {
deferredTurnCompletedEvents.push(runtimeEvent);
continue;
}
yield* emit(runtimeEvent);
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
type: "userMessage",
content: [{ type: "text", text: input.input }],
} as const;
const assistantText = assistantDeltas.join("");
const nextItems: Array<unknown> =
assistantText.length > 0
? [userItem, { type: "agentMessage", text: assistantText }]
: [userItem];
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: nextItems,
};
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.makeUnsafe(randomUUID()),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
);
payload: {
state: "completed",
},
});
} else {
for (const completedEvent of deferredTurnCompletedEvents) {
yield* emit(completedEvent);
}
}
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
return {
threadId: state.snapshot.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = interruptCallsBySession.get(threadId) ?? [];
existing.push(turnId);
interruptCallsBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
requestId,
decision,
) =>
sessions.has(threadId)
? Effect.sync(() => {
const existing = approvalResponsesBySession.get(threadId) ?? [];
existing.push({
threadId,
requestId,
decision,
});
approvalResponsesBySession.set(threadId, existing);
})
: missingSessionEffect(provider, threadId);
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers,
) => (sessions.has(threadId) ? Effect.void : missingSessionEffect(provider, threadId));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.sync(() => {
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
return Effect.succeed(state.snapshot);
};
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) => {
const state = sessions.get(threadId);
if (!state) {
return missingSessionEffect(provider, threadId);
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return Effect.fail(
new ProviderAdapterValidationError({
provider,
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and current turn count.",
}),
);
}
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
return Effect.sync(() => {
state.rollbackCalls.push(numTurns);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
};
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.sync(() => {
sessions.clear();
});
const getStartCount = (): number => sessionCount;
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
provider,
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
};
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const queueTurnResponse = (
threadId: ThreadId,
response: TestTurnResponse,
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
Effect.sync(() => sessions.get(threadId)).pipe(
Effect.flatMap((state) =>
state
? Effect.sync(() => {
state.queuedResponses.push(response);
})
: Effect.fail(sessionNotFound(provider, threadId)),
),
);
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
const state = sessions.get(threadId);
if (!state) {
return [];
}
return [...state.rollbackCalls];
};
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
const getStartCount = (): number => sessionCount;
const getInterruptCalls = (threadId: ThreadId): ReadonlyArray<TurnId | undefined> => {
const calls = interruptCallsBySession.get(threadId);
if (!calls) {
return [];
}
return [...calls];
};
const listActiveSessionIds = (): ReadonlyArray<ThreadId> =>
Array.from(sessions.values(), (state) => state.session.threadId);
const getApprovalResponses = (
threadId: ThreadId,
): ReadonlyArray<{
readonly threadId: ThreadId;
readonly requestId: ApprovalRequestId;
readonly decision: ProviderApprovalDecision;
}> => {
const responses = approvalResponsesBySession.get(threadId);
if (!responses) {
return [];
}
return [...responses];
};
return {
adapter,
provider,
queueTurnResponse,
queueTurnResponseForNextSession,
getStartCount,
getRollbackCalls,
getInterruptCalls,
listActiveSessionIds,
getApprovalResponses,
} satisfies TestProviderAdapterHarness;
});
@@ -73,7 +73,7 @@ export const codexTurnToolFixture = [
turnId: TURN_ID,
payload: {
itemType: "command_execution",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -85,7 +85,7 @@ export const codexTurnToolFixture = [
payload: {
itemType: "command_execution",
status: "completed",
title: "Ran command",
title: "Command run",
detail: "echo integration",
},
},
@@ -5,13 +5,10 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ProviderKind,
ThreadId,
ModelSelection,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -28,7 +25,6 @@ import type {
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -40,7 +36,7 @@ const PROJECT_ID = asProjectId("project-1");
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
const FIXTURE_TURN_ID = "fixture-turn";
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
type IntegrationProvider = ProviderKind;
type IntegrationProvider = "codex";
function nowIso() {
return new Date().toISOString();
@@ -53,11 +49,13 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
timeoutMs = 3000,
): Effect.Effect<A, never> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
@@ -70,7 +68,7 @@ function waitForSync<A>(
if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* Effect.sleep(10);
yield* sleep(10);
}
});
}
@@ -91,7 +89,7 @@ function withHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
function withRealCodexHarness<A, E>(
@@ -101,14 +99,12 @@ function withRealCodexHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
Effect.gen(function* () {
const createdAt = nowIso();
const provider = harness.adapterHarness?.provider ?? "codex";
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
yield* harness.engine.dispatch({
type: "project.create",
@@ -116,10 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider,
model: defaultModel,
},
defaultModel: "gpt-5-codex",
createdAt,
});
@@ -129,10 +122,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider,
model: defaultModel,
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -146,7 +136,7 @@ const startTurn = (input: {
readonly commandId: string;
readonly messageId: string;
readonly text: string;
readonly modelSelection?: ModelSelection;
readonly provider?: IntegrationProvider;
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
@@ -158,11 +148,7 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
...(input.modelSelection !== undefined
? {
modelSelection: input.modelSelection,
}
: {}),
...(input.provider !== undefined ? { provider: input.provider } : {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
@@ -265,10 +251,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
defaultModel: "gpt-5.3-codex",
createdAt,
});
@@ -278,10 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -902,435 +882,3 @@ it.live(
}),
),
);
it.live("starts a claudeAgent session on first turn when provider is requested", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Claude first turn.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.session.status === "ready" &&
entry.messages.some(
(message) => message.role === "assistant" && message.text === "Claude first turn.\n",
),
);
assert.equal(thread.session?.providerName, "claudeAgent");
}),
"claudeAgent",
),
);
it.live("recovers claudeAgent sessions after provider stopAll using persisted resume state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn before restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.adapter.stopAll();
yield* waitForSync(
() => harness.adapterHarness!.listActiveSessionIds(),
(sessionIds) => sessionIds.length === 0,
"provider stopAll",
);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Turn after restart.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-recover-2",
messageId: "msg-user-claude-recover-2",
text: "After restart",
});
yield* waitForSync(
() => harness.adapterHarness!.getStartCount(),
(count) => count === 2,
"claude provider recovery start",
);
const recoveredThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.session?.providerName === "claudeAgent" &&
entry.messages.some(
(message) => message.role === "user" && message.text === "After restart",
) &&
!entry.activities.some((activity) => activity.kind === "provider.turn.start.failed"),
);
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
assert.equal(recoveredThread.session?.threadId, "thread-1");
}),
"claudeAgent",
),
);
it.live("forwards claudeAgent approval responses to the provider session", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "approval.requested",
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
requestId: APPROVAL_REQUEST_ID,
requestKind: "command",
detail: "Approve Claude tool call",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
entry.activities.some((activity) => activity.kind === "approval.requested"),
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.approval.respond",
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
threadId: THREAD_ID,
requestId: APPROVAL_REQUEST_ID,
decision: "accept",
createdAt: nowIso(),
});
yield* harness.waitForPendingApproval(
"req-approval-1",
(row) => row.status === "resolved" && row.decision === "accept",
);
const approvalResponses = yield* waitForSync(
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
(responses) => responses.length === 1,
"claude provider approval response",
);
assert.equal(approvalResponses[0]?.decision, "accept");
}),
"claudeAgent",
),
);
it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "Long running output.\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
const thread = yield* harness.waitForThread(
THREAD_ID,
(entry) => entry.session?.threadId === "thread-1",
);
assert.equal(thread.session?.threadId, "thread-1");
yield* harness.engine.dispatch({
type: "thread.turn.interrupt",
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
threadId: THREAD_ID,
createdAt: nowIso(),
});
yield* harness.waitForDomainEvent(
(event) => event.type === "thread.turn-interrupt-requested",
);
const interruptCalls = yield* waitForSync(
() => harness.adapterHarness!.getInterruptCalls(THREAD_ID),
(calls) => calls.length === 1,
"claude provider interrupt call",
);
assert.equal(interruptCalls.length, 1);
}),
"claudeAgent",
),
);
it.live("reverts claudeAgent turns and rolls back provider conversation state", () =>
withHarness(
(harness) =>
Effect.gen(function* () {
yield* seedProjectAndThread(harness);
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v2\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-1" && entry.session?.threadId === "thread-1",
);
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
events: [
{
type: "turn.started",
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
},
{
type: "message.delta",
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
delta: "README -> v3\n",
},
{
type: "turn.completed",
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
threadId: THREAD_ID,
turnId: FIXTURE_TURN_ID,
status: "completed",
},
],
mutateWorkspace: ({ cwd }) =>
Effect.sync(() => {
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
}),
});
yield* startTurn({
harness,
commandId: "cmd-turn-start-claude-revert-2",
messageId: "msg-user-claude-revert-2",
text: "Second Claude edit",
});
yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.latestTurn?.turnId === "turn-2" &&
entry.checkpoints.length === 2 &&
entry.session?.providerName === "claudeAgent",
);
yield* harness.engine.dispatch({
type: "thread.checkpoint.revert",
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
threadId: THREAD_ID,
turnCount: 1,
createdAt: nowIso(),
});
const revertedThread = yield* harness.waitForThread(
THREAD_ID,
(entry) =>
entry.checkpoints.length === 1 && entry.checkpoints[0]?.checkpointTurnCount === 1,
);
assert.equal(revertedThread.checkpoints[0]?.checkpointTurnCount, 1);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 1)),
true,
);
assert.equal(
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
false,
);
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
}),
"claudeAgent",
),
);
@@ -1,6 +1,5 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
@@ -13,7 +12,6 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -62,7 +60,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
+8 -9
View File
@@ -1,36 +1,34 @@
{
"name": "t3",
"version": "0.0.15",
"license": "MIT",
"version": "0.0.9",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
"directory": "apps/server"
},
"bin": {
"t3": "./dist/bin.mjs"
"t3": "./dist/index.mjs"
},
"files": [
"dist"
],
"type": "module",
"scripts": {
"dev": "bun run src/bin.ts",
"dev": "bun run src/index.ts",
"build": "node scripts/cli.ts build",
"start": "node dist/bin.mjs",
"start": "node dist/index.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-bun": "catalog:",
"@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,11 +38,12 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
"node": "^22.13 || ^23.4 || >=24.10"
}
}
+4 -5
View File
@@ -6,10 +6,7 @@ import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import { DEVELOPMENT_ICON_OVERRIDES, PUBLISH_ICON_OVERRIDES } from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -240,7 +237,9 @@ const publishCmd = Command.make(
Effect.gen(function* () {
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
Effect.catch((error) =>
Effect.logError(`[cli] Failed to restore publish icon overrides: ${String(error)}`),
Effect.logError(
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
),
),
);
yield* fs.rename(backupPath, packageJsonPath);
+2 -2
View File
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
}
export function resolveAttachmentRelativePath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
return null;
}
const attachmentsRoot = path.resolve(input.attachmentsDir);
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
+8 -6
View File
@@ -44,32 +44,34 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
});
+6 -5
View File
@@ -12,7 +12,8 @@ import { inferImageExtension, SAFE_IMAGE_FILE_EXTENSIONS } from "./imageMime.ts"
const ATTACHMENT_FILENAME_EXTENSIONS = [...SAFE_IMAGE_FILE_EXTENSIONS, ".bin"];
const ATTACHMENT_ID_THREAD_SEGMENT_MAX_CHARS = 80;
const ATTACHMENT_ID_THREAD_SEGMENT_PATTERN = "[a-z0-9_]+(?:-[a-z0-9_]+)*";
const ATTACHMENT_ID_UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_UUID_PATTERN =
"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
const ATTACHMENT_ID_PATTERN = new RegExp(
`^(${ATTACHMENT_ID_THREAD_SEGMENT_PATTERN})-(${ATTACHMENT_ID_UUID_PATTERN})$`,
"i",
@@ -66,17 +67,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
}
export function resolveAttachmentPath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
@@ -85,7 +86,7 @@ export function resolveAttachmentPathById(input: {
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
-17
View File
@@ -1,17 +0,0 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { Command } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import { cli } from "./cli";
import { version } from "../package.json" with { type: "json" };
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
Command.run(cli, { version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
NodeRuntime.runMain,
);
-149
View File
@@ -1,149 +0,0 @@
import * as NFS from "node:fs";
import * as path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { FileSystem, Schema } from "effect";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import { TestClock } from "effect/testing";
import { vi } from "vitest";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { assertNone, assertSome } from "@effect/vitest/utils";
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
vi.mock("node:fs", async (importOriginal) => {
const actual = await importOriginal<typeof import("node:fs")>();
return {
...actual,
openSync: (...args: Parameters<typeof actual.openSync>) => {
const [filePath, flags] = args;
if (
typeof filePath === "string" &&
filePath === openSyncInterceptor.failPath &&
flags === "r"
) {
const error = new Error("no such device or address");
Object.assign(error, { code: "ENXIO" });
throw error;
}
return (actual.openSync as (...a: typeof args) => number)(...args);
},
};
});
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
it.effect("uses platform-specific fd paths", () =>
Effect.sync(() => {
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
assert.equal(resolveFdPath(3, "win32"), undefined);
}),
);
it.effect("reads a bootstrap envelope from a provided fd", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
);
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NFS.closeSync(fd)),
);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertSome(payload, {
mode: "desktop",
});
}),
);
it.effect("falls back to reading the inherited fd when path duplication fails", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
);
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
// so the stream owns the fd lifecycle and closes it asynchronously on end.
// Attempting to also close it synchronously in a finalizer races with the
// stream's async close and produces an uncaught EBADF.
const fd = NFS.openSync(filePath, "r");
openSyncInterceptor.failPath = `/proc/self/fd/${fd}`;
try {
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertSome(payload, {
mode: "desktop",
});
} finally {
openSyncInterceptor.failPath = null;
}
}),
);
it.effect("returns none when the fd is unavailable", () =>
Effect.gen(function* () {
const fd = NFS.openSync("/dev/null", "r");
NFS.closeSync(fd);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertNone(payload);
}),
);
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
const fifoPath = path.join(tempDir, "bootstrap.pipe");
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
const _writer = yield* Effect.acquireRelease(
Effect.sync(() =>
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
stdio: ["ignore", "ignore", "ignore"],
}),
),
(writer) =>
Effect.sync(() => {
writer.kill("SIGKILL");
}),
);
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NFS.openSync(fifoPath, "r")),
(fd) => Effect.sync(() => NFS.closeSync(fd)),
);
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(100));
const payload = yield* Fiber.join(fiber);
assertNone(payload);
}).pipe(Effect.provide(TestClock.layer())),
);
});
-173
View File
@@ -1,173 +0,0 @@
import * as NFS from "node:fs";
import * as Net from "node:net";
import * as readline from "node:readline";
import type { Readable } from "node:stream";
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
class BootstrapError extends Data.TaggedError("BootstrapError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
schema: Schema.Codec<A, I>,
fd: number,
options?: {
timeoutMs?: number;
},
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
const fdReady = yield* isFdReady(fd);
if (!fdReady) return Option.none();
const stream = yield* makeBootstrapInputStream(fd);
const timeoutMs = options?.timeoutMs ?? 1000;
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
const input = readline.createInterface({
input: stream,
crlfDelay: Infinity,
});
const cleanup = () => {
stream.removeListener("error", handleError);
input.removeListener("line", handleLine);
input.removeListener("close", handleClose);
input.close();
stream.destroy();
};
const handleError = (error: Error) => {
if (isUnavailableBootstrapFdError(error)) {
resume(Effect.succeedNone);
return;
}
resume(
Effect.fail(
new BootstrapError({
message: "Failed to read bootstrap envelope.",
cause: error,
}),
),
);
};
const handleLine = (line: string) => {
const parsed = decodeJsonResult(schema)(line);
if (Result.isSuccess(parsed)) {
resume(Effect.succeedSome(parsed.success));
} else {
resume(
Effect.fail(
new BootstrapError({
message: "Failed to decode bootstrap envelope.",
cause: parsed.failure,
}),
),
);
}
};
const handleClose = () => {
resume(Effect.succeedNone);
};
stream.once("error", handleError);
input.once("line", handleLine);
input.once("close", handleClose);
return Effect.sync(cleanup);
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
});
const isUnavailableBootstrapFdError = Predicate.compose(
Predicate.hasProperty("code"),
(_) => _.code === "EBADF" || _.code === "ENOENT",
);
const isFdReady = (fd: number) =>
Effect.try({
try: () => NFS.fstatSync(fd),
catch: (error) =>
new BootstrapError({
message: "Failed to stat bootstrap fd.",
cause: error,
}),
}).pipe(
Effect.as(true),
Effect.catchIf(
(error) => isUnavailableBootstrapFdError(error.cause),
() => Effect.succeed(false),
),
);
const makeBootstrapInputStream = (fd: number) =>
Effect.try<Readable, BootstrapError>({
try: () => {
const fdPath = resolveFdPath(fd);
if (fdPath === undefined) {
return makeDirectBootstrapStream(fd);
}
let streamFd: number | undefined;
try {
streamFd = NFS.openSync(fdPath, "r");
return NFS.createReadStream("", {
fd: streamFd,
encoding: "utf8",
autoClose: true,
});
} catch (error) {
if (isBootstrapFdPathDuplicationError(error)) {
if (streamFd !== undefined) {
NFS.closeSync(streamFd);
}
return makeDirectBootstrapStream(fd);
}
throw error;
}
},
catch: (error) =>
new BootstrapError({
message: "Failed to duplicate bootstrap fd.",
cause: error,
}),
});
const makeDirectBootstrapStream = (fd: number): Readable => {
try {
return NFS.createReadStream("", {
fd,
encoding: "utf8",
autoClose: true,
});
} catch {
const stream = new Net.Socket({
fd,
readable: true,
writable: false,
});
stream.setEncoding("utf8");
return stream;
}
};
const isBootstrapFdPathDuplicationError = Predicate.compose(
Predicate.hasProperty("code"),
(_) => _.code === "ENXIO" || _.code === "EINVAL" || _.code === "EPERM",
);
export function resolveFdPath(
fd: number,
platform: NodeJS.Platform = process.platform,
): string | undefined {
if (platform === "linux") {
return `/proc/self/fd/${fd}`;
}
if (platform === "win32") {
return undefined;
}
return `/dev/fd/${fd}`;
}
+1 -1
View File
@@ -1,6 +1,6 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCommandError } from "../git/Errors.ts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
@@ -31,7 +31,7 @@ function makeSnapshot(input: {
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
@@ -43,10 +43,7 @@ function makeSnapshot(input: {
id: input.threadId,
projectId: input.projectId,
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -61,7 +58,6 @@ function makeSnapshot(input: {
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
@@ -1,122 +0,0 @@
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ThreadId } from "@t3tools/contracts";
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-store-test-",
});
const GitCoreTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfigLayer),
Layer.provide(NodeServices.layer),
);
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
Layer.provide(GitCoreTestLayer),
Layer.provide(NodeServices.layer),
);
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
function makeTmpDir(
prefix = "checkpoint-store-test-",
): Effect.Effect<string, PlatformError.PlatformError, FileSystem.FileSystem | Scope.Scope> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({ prefix });
});
}
function writeTextFile(
filePath: string,
contents: string,
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(filePath, contents);
});
}
function git(
cwd: string,
args: ReadonlyArray<string>,
): Effect.Effect<string, GitCommandError, GitCore> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
const result = yield* gitCore.execute({
operation: "CheckpointStore.test.git",
cwd,
args,
timeoutMs: 10_000,
});
return result.stdout.trim();
});
}
function initRepoWithCommit(
cwd: string,
): Effect.Effect<
void,
GitCommandError | PlatformError.PlatformError,
GitCore | FileSystem.FileSystem
> {
return Effect.gen(function* () {
const core = yield* GitCore;
yield* core.initRepo({ cwd });
yield* git(cwd, ["config", "user.email", "[email protected]"]);
yield* git(cwd, ["config", "user.name", "Test"]);
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
yield* git(cwd, ["add", "."]);
yield* git(cwd, ["commit", "-m", "initial commit"]);
});
}
function buildLargeText(lineCount = 20_000): string {
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
.join("\n")
.concat("\n");
}
it.layer(TestLayer)("CheckpointStoreLive", (it) => {
describe("diffCheckpoints", () => {
it.effect("returns full oversized checkpoint diffs without truncation", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const checkpointStore = yield* CheckpointStore;
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: fromCheckpointRef,
});
yield* writeTextFile(path.join(tmp, "README.md"), buildLargeText());
yield* checkpointStore.captureCheckpoint({
cwd: tmp,
checkpointRef: toCheckpointRef,
});
const diff = yield* checkpointStore.diffCheckpoints({
cwd: tmp,
fromCheckpointRef,
toCheckpointRef,
});
expect(diff).toContain("diff --git");
expect(diff).not.toContain("[truncated]");
expect(diff).toContain("+line 19999");
}),
);
});
});
@@ -14,15 +14,16 @@ import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitServiceLive } from "../../git/Layers/GitService.ts";
import { GitService } from "../../git/Services/GitService.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitCore;
const git = yield* GitService;
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
@@ -276,4 +277,6 @@ const makeCheckpointStore = Effect.gen(function* () {
} satisfies CheckpointStoreShape;
});
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
Layer.provideMerge(GitServiceLive),
);
-318
View File
@@ -1,318 +0,0 @@
import os from "node:os";
import { assert, expect, it } from "@effect/vitest";
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect";
import { NetService } from "@t3tools/shared/Net";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "./config";
import { resolveServerConfig } from "./cli";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
});
it.effect("falls back to effect/config values when flags are omitted", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-env-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "env-token",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Warn",
mode: "desktop",
port: 4001,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "0.0.0.0",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
authToken: "env-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
}),
);
it.effect("uses CLI flags when provided", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some(true),
authToken: Option.some("flag-token"),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(true),
logWebSocketEvents: Option.some(true),
},
Option.some("Debug"),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "false",
T3CODE_AUTH_TOKEN: "ignored-token",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "false",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Debug",
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
authToken: "flag-token",
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
}),
);
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = "/tmp/t3-bootstrap-home";
const fd = yield* openBootstrapFd({
mode: "desktop",
port: 4888,
host: "127.0.0.2",
t3Home: baseDir,
devUrl: "http://127.0.0.1:5173",
noBrowser: true,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_BOOTSTRAP_FD: String(fd),
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Info",
mode: "desktop",
port: 4888,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.2",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
assert.equal(join(baseDir, "dev"), resolved.stateDir);
}),
);
it.effect("creates derived runtime directories during config resolution", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
const resolved = yield* resolveServerConfig(
{
mode: Option.some("desktop"),
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
NetService.layer,
),
),
);
for (const directory of [
resolved.stateDir,
resolved.logsDir,
resolved.providerLogsDir,
resolved.terminalLogsDir,
resolved.attachmentsDir,
resolved.worktreesDir,
path.dirname(resolved.serverLogPath),
]) {
expect(yield* fs.exists(directory)).toBe(true);
}
}),
);
it.effect("applies flag then env precedence over bootstrap envelope values", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
const fd = yield* openBootstrapFd({
mode: "desktop",
port: 4888,
host: "127.0.0.2",
t3Home: "/tmp/t3-bootstrap-home",
devUrl: "http://127.0.0.1:5173",
noBrowser: false,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.none(),
authToken: Option.some("flag-token"),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.some("Debug"),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_MODE: "web",
T3CODE_BOOTSTRAP_FD: String(fd),
T3CODE_HOME: baseDir,
T3CODE_NO_BROWSER: "true",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Debug",
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
authToken: "flag-token",
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
}),
);
});
-37
View File
@@ -1,37 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as CliError from "effect/unstable/cli/CliError";
import { Command } from "effect/unstable/cli";
import { cli } from "./cli.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
it.effect("accepts the built-in lowercase log-level flag values", () =>
Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
Effect.provide(CliRuntimeLayer),
),
);
it.effect("rejects invalid log-level casing before launching the server", () =>
Effect.gen(function* () {
const error = yield* Command.runWith(cli, { version: "0.0.0" })([
"--log-level",
"Debug",
]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "InvalidValue") {
assert.fail(`Expected InvalidValue, got ${error._tag}`);
}
assert.equal(error.option, "log-level");
assert.equal(error.value, "Debug");
}),
);
});
-292
View File
@@ -1,292 +0,0 @@
import { NetService } from "@t3tools/shared/Net";
import { Config, Effect, LogLevel, Option, Schema } from "effect";
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
DEFAULT_PORT,
deriveServerPaths,
ensureServerDirectories,
resolveStaticDir,
ServerConfig,
RuntimeMode,
type ServerConfigShape,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
const BootstrapEnvelopeSchema = Schema.Struct({
mode: Schema.optional(RuntimeMode),
port: Schema.optional(PortSchema),
host: Schema.optional(Schema.String),
t3Home: Schema.optional(Schema.String),
devUrl: Schema.optional(Schema.URLFromString),
noBrowser: Schema.optional(Schema.Boolean),
authToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
});
const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
Flag.optional,
);
const portFlag = Flag.integer("port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("Port for the HTTP/WebSocket server."),
Flag.optional,
);
const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
Flag.optional,
);
const baseDirFlag = Flag.string("base-dir").pipe(
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
Flag.optional,
);
const devUrlFlag = Flag.string("dev-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
Flag.optional,
);
const noBrowserFlag = Flag.boolean("no-browser").pipe(
Flag.withDescription("Disable automatic browser opening."),
Flag.optional,
);
const authTokenFlag = Flag.string("auth-token").pipe(
Flag.withDescription("Auth token required for WebSocket connections."),
Flag.withAlias("token"),
Flag.optional,
);
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
Flag.withSchema(Schema.Int),
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
Flag.optional,
);
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
Flag.withDescription(
"Create a project for the current working directory on startup when missing.",
),
Flag.optional,
);
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
Flag.withDescription(
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
),
Flag.withAlias("log-ws-events"),
Flag.optional,
);
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
});
interface CliServerFlags {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly baseDir: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
export const resolveServerConfig = (
flags: CliServerFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const env = yield* EnvServerConfig;
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
: Option.none();
const mode: RuntimeMode = Option.getOrElse(
resolveOptionPrecedence(
flags.mode,
Option.fromUndefinedOr(env.mode),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
),
() => "web",
);
const port = yield* Option.match(
resolveOptionPrecedence(
flags.port,
Option.fromUndefinedOr(env.port),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
),
{
onSome: (value) => Effect.succeed(value),
onNone: () => {
if (mode === "desktop") {
return Effect.succeed(DEFAULT_PORT);
}
return findAvailablePort(DEFAULT_PORT);
},
},
);
const devUrl = Option.getOrElse(
resolveOptionPrecedence(
flags.devUrl,
Option.fromUndefinedOr(env.devUrl),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
),
() => undefined,
);
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(
resolveOptionPrecedence(
flags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.t3Home),
),
),
),
);
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
const noBrowser = resolveBooleanFlag(
flags.noBrowser,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.noBrowser),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.noBrowser),
),
),
() => mode === "desktop",
),
);
const authToken = Option.getOrUndefined(
resolveOptionPrecedence(
flags.authToken,
Option.fromUndefinedOr(env.authToken),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.authToken),
),
),
);
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
flags.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
);
const logWebSocketEvents = resolveBooleanFlag(
flags.logWebSocketEvents,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
),
),
() => Boolean(devUrl),
),
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
flags.host,
Option.fromUndefinedOr(env.host),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
),
() => (mode === "desktop" ? "127.0.0.1" : undefined),
);
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
const config: ServerConfigShape = {
logLevel,
mode,
port,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host,
staticDir,
devUrl,
noBrowser,
authToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
};
return config;
});
const commandFlags = {
mode: modeFlag,
port: portFlag,
host: hostFlag,
baseDir: baseDirFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
} as const;
const rootCommand = Command.make("t3", commandFlags).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveServerConfig(flags, logLevel);
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
}),
),
);
export const cli = rootCommand;
+70 -304
View File
@@ -37,7 +37,6 @@ function createSendTurnHarness() {
planType: null,
sparkEnabled: true,
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -76,7 +75,6 @@ function createThreadControlHarness() {
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -119,7 +117,6 @@ function createPendingUserInputHarness() {
},
],
]),
collabReceiverTurns: new Map(),
};
const requireSession = vi
@@ -138,43 +135,6 @@ function createPendingUserInputHarness() {
return { manager, context, requireSession, writeMessage, emitEvent };
}
function createCollabNotificationHarness() {
const manager = new CodexAppServerManager();
const context = {
session: {
provider: "codex",
status: "running",
threadId: asThreadId("thread_1"),
runtimeMode: "full-access",
model: "gpt-5.3-codex",
activeTurnId: "turn_parent",
resumeCursor: { threadId: "provider_parent" },
createdAt: "2026-02-10T00:00:00.000Z",
updatedAt: "2026-02-10T00:00:00.000Z",
},
account: {
type: "unknown",
planType: null,
sparkEnabled: true,
},
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map<string, string>(),
nextRequestId: 1,
stopping: false,
};
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
const updateSession = vi
.spyOn(manager as unknown as { updateSession: (...args: unknown[]) => void }, "updateSession")
.mockImplementation(() => {});
return { manager, context, emitEvent, updateSession };
}
describe("classifyCodexStderrLine", () => {
it("ignores empty lines", () => {
expect(classifyCodexStderrLine(" ")).toBeNull();
@@ -207,42 +167,6 @@ describe("classifyCodexStderrLine", () => {
});
});
describe("process stderr events", () => {
it("emits classified stderr lines as notifications", () => {
const manager = new CodexAppServerManager();
const emitEvent = vi
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
.mockImplementation(() => {});
(
manager as unknown as {
emitNotificationEvent: (
context: { session: { threadId: ThreadId } },
method: string,
message: string,
) => void;
}
).emitNotificationEvent(
{
session: {
threadId: asThreadId("thread-1"),
},
},
"process/stderr",
"fatal: permission denied",
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
kind: "notification",
method: "process/stderr",
threadId: "thread-1",
message: "fatal: permission denied",
}),
);
});
});
describe("normalizeCodexModelSlug", () => {
it("maps 5.3 aliases to gpt-5.3-codex", () => {
expect(normalizeCodexModelSlug("5.3")).toBe("gpt-5.3-codex");
@@ -310,7 +234,7 @@ describe("readCodexAccountSnapshot", () => {
});
});
it("disables spark for api key accounts", () => {
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
@@ -318,20 +242,7 @@ describe("readCodexAccountSnapshot", () => {
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: false,
});
});
it("disables spark for unknown chatgpt plans", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
}),
).toEqual({
type: "chatgpt",
planType: "unknown",
sparkEnabled: false,
sparkEnabled: true,
});
});
});
@@ -356,16 +267,6 @@ describe("resolveCodexModelForAccount", () => {
}),
).toBe("gpt-5.3-codex-spark");
});
it("falls back from spark to default for api key auth", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "apiKey",
planType: null,
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
});
describe("startSession", () => {
@@ -401,7 +302,6 @@ describe("startSession", () => {
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
@@ -450,7 +350,6 @@ describe("startSession", () => {
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow(
@@ -822,7 +721,6 @@ describe("respondToUserInput", () => {
},
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
@@ -850,221 +748,89 @@ describe("respondToUserInput", () => {
});
});
describe("collab child conversation routing", () => {
it("rewrites child notification turn ids onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/agentMessage/delta",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "msg_child_1",
delta: "working",
},
});
expect(emitEvent).toHaveBeenLastCalledWith(
expect.objectContaining({
method: "item/agentMessage/delta",
turnId: "turn_parent",
itemId: "msg_child_1",
}),
);
});
it("suppresses child lifecycle notifications so they cannot replace the parent turn", () => {
const { manager, context, emitEvent, updateSession } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
updateSession.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/started",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1" },
},
});
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "turn/completed",
params: {
threadId: "child_provider_1",
turn: { id: "turn_child_1", status: "completed" },
},
});
expect(emitEvent).not.toHaveBeenCalled();
expect(updateSession).not.toHaveBeenCalled();
});
it("rewrites child approval requests onto the parent turn", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerRequest: (context: unknown, request: Record<string, unknown>) => void;
}
).handleServerRequest(context, {
id: 42,
method: "item/commandExecution/requestApproval",
params: {
threadId: "child_provider_1",
turnId: "turn_child_1",
itemId: "call_child_1",
command: "bun install",
},
});
expect(Array.from(context.pendingApprovals.values())[0]).toEqual(
expect.objectContaining({
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "item/commandExecution/requestApproval",
turnId: "turn_parent",
itemId: "call_child_1",
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
it("keeps prior thread history when resuming with a changed runtime mode", async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
it(
"keeps prior thread history when resuming with a changed runtime mode",
async () => {
const workspaceDir = mkdtempSync(path.join(os.tmpdir(), "codex-live-resume-"));
writeFileSync(path.join(workspaceDir, "README.md"), "hello\n", "utf8");
const manager = new CodexAppServerManager();
const manager = new CodexAppServerManager();
try {
const firstSession = await manager.startSession({
threadId: asThreadId("thread-live"),
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
binaryPath: process.env.CODEX_BINARY_PATH!,
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
});
try {
const firstSession = await manager.startSession({
threadId: asThreadId("thread-live"),
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { binaryPath: process.env.CODEX_BINARY_PATH }
: {}),
...(process.env.CODEX_HOME_PATH
? { homePath: process.env.CODEX_HOME_PATH }
: {}),
},
},
});
const firstTurn = await manager.sendTurn({
threadId: firstSession.threadId,
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
});
const firstTurn = await manager.sendTurn({
threadId: firstSession.threadId,
input: `Reply with exactly the word ALPHA ${randomUUID()}`,
});
expect(firstTurn.threadId).toBe(firstSession.threadId);
expect(firstTurn.threadId).toBe(firstSession.threadId);
await vi.waitFor(
async () => {
await vi.waitFor(async () => {
const snapshot = await manager.readThread(firstSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(0);
},
{ timeout: 120_000, interval: 1_000 },
);
}, { timeout: 120_000, interval: 1_000 });
const firstSnapshot = await manager.readThread(firstSession.threadId);
const originalThreadId = firstSnapshot.threadId;
const originalTurnCount = firstSnapshot.turns.length;
const firstSnapshot = await manager.readThread(firstSession.threadId);
const originalThreadId = firstSnapshot.threadId;
const originalTurnCount = firstSnapshot.turns.length;
manager.stopSession(firstSession.threadId);
manager.stopSession(firstSession.threadId);
const resumedSession = await manager.startSession({
threadId: firstSession.threadId,
provider: "codex",
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
binaryPath: process.env.CODEX_BINARY_PATH!,
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
});
const resumedSession = await manager.startSession({
threadId: firstSession.threadId,
provider: "codex",
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH
? { binaryPath: process.env.CODEX_BINARY_PATH }
: {}),
...(process.env.CODEX_HOME_PATH
? { homePath: process.env.CODEX_HOME_PATH }
: {}),
},
},
});
expect(resumedSession.threadId).toBe(originalThreadId);
expect(resumedSession.threadId).toBe(originalThreadId);
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
const resumedSnapshotBeforeTurn = await manager.readThread(resumedSession.threadId);
expect(resumedSnapshotBeforeTurn.threadId).toBe(originalThreadId);
expect(resumedSnapshotBeforeTurn.turns.length).toBeGreaterThanOrEqual(originalTurnCount);
await manager.sendTurn({
threadId: resumedSession.threadId,
input: `Reply with exactly the word BETA ${randomUUID()}`,
});
await manager.sendTurn({
threadId: resumedSession.threadId,
input: `Reply with exactly the word BETA ${randomUUID()}`,
});
await vi.waitFor(
async () => {
await vi.waitFor(async () => {
const snapshot = await manager.readThread(resumedSession.threadId);
expect(snapshot.turns.length).toBeGreaterThan(originalTurnCount);
},
{ timeout: 120_000, interval: 1_000 },
);
} finally {
manager.stopAll();
rmSync(workspaceDir, { recursive: true, force: true });
}
}, 180_000);
}, { timeout: 120_000, interval: 1_000 });
} finally {
manager.stopAll();
rmSync(workspaceDir, { recursive: true, force: true });
}
},
180_000,
);
});
+125 -130
View File
@@ -14,6 +14,7 @@ import {
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderTurnStartResult,
RuntimeMode,
ProviderInteractionMode,
@@ -26,15 +27,6 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
import {
readCodexAccountSnapshot,
resolveCodexModelForAccount,
type CodexAccountSnapshot,
} from "./provider/codexAccount";
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
export { buildCodexInitializeParams } from "./provider/codexAppServer";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
type PendingRequestKey = string;
@@ -78,7 +70,6 @@ interface CodexSessionContext {
pending: Map<PendingRequestKey, PendingRequest>;
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
nextRequestId: number;
stopping: boolean;
}
@@ -105,6 +96,23 @@ interface JsonRpcNotification {
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
@@ -122,8 +130,7 @@ export interface CodexAppServerStartSessionInput {
readonly model?: string;
readonly serviceTier?: string;
readonly resumeCursor?: unknown;
readonly binaryPath: string;
readonly homePath?: string;
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
readonly runtimeMode: RuntimeMode;
}
@@ -154,6 +161,50 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -306,13 +357,32 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
};
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
killCodexChildProcess(child);
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
}
export function normalizeCodexModelSlug(
@@ -331,6 +401,19 @@ export function normalizeCodexModelSlug(
return normalized;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
function buildCodexCollaborationMode(input: {
readonly interactionMode?: "default" | "plan";
readonly model?: string;
@@ -457,8 +540,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
updatedAt: now,
};
const codexBinaryPath = input.binaryPath;
const codexHomePath = input.homePath;
const codexOptions = readCodexProviderOptions(input);
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
const codexHomePath = codexOptions.homePath;
this.assertSupportedCodexCliVersion({
binaryPath: codexBinaryPath,
cwd: resolvedCwd,
@@ -487,7 +571,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
pending: new Map(),
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -649,7 +732,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
@@ -962,7 +1044,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
continue;
}
this.emitNotificationEvent(context, "process/stderr", classified.message);
this.emitErrorEvent(context, "process/stderr", classified.message);
}
});
@@ -1039,16 +1121,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
context: CodexSessionContext,
notification: JsonRpcNotification,
): void {
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const isChildConversation = childParentTurnId !== undefined;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
) {
return;
}
const route = this.readRouteFields(notification.params);
const textDelta =
notification.method === "item/agentMessage/delta"
? this.readString(notification.params, "delta")
@@ -1061,10 +1134,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: notification.method,
...((childParentTurnId ?? rawRoute.turnId)
? { turnId: childParentTurnId ?? rawRoute.turnId }
: {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
turnId: route.turnId,
itemId: route.itemId,
textDelta,
payload: notification.params,
});
@@ -1080,9 +1151,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/started") {
if (isChildConversation) {
return;
}
const turnId = toTurnId(this.readString(this.readObject(notification.params)?.turn, "id"));
this.updateSession(context, {
status: "running",
@@ -1092,10 +1160,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "turn/completed") {
if (isChildConversation) {
return;
}
context.collabReceiverTurns.clear();
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
@@ -1108,9 +1172,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
if (notification.method === "error") {
if (isChildConversation) {
return;
}
const message = this.readString(this.readObject(notification.params)?.error, "message");
const willRetry = this.readBoolean(notification.params, "willRetry");
@@ -1122,9 +1183,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
}
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
const route = this.readRouteFields(request.params);
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
@@ -1140,8 +1199,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
: "item/fileChange/requestApproval",
requestKind,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
@@ -1152,8 +1211,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestId,
jsonRpcId: request.id,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(route.turnId ? { turnId: route.turnId } : {}),
...(route.itemId ? { itemId: route.itemId } : {}),
});
}
@@ -1164,8 +1223,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method: request.method,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
turnId: route.turnId,
itemId: route.itemId,
requestId,
requestKind,
payload: request.params,
@@ -1270,22 +1329,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
});
}
private emitNotificationEvent(
context: CodexSessionContext,
method: string,
message: string,
): void {
this.emitEvent({
id: EventId.makeUnsafe(randomUUID()),
kind: "notification",
provider: "codex",
threadId: context.session.threadId,
createdAt: new Date().toISOString(),
method,
message,
});
}
private emitEvent(event: ProviderEvent): void {
this.emit("event", event);
}
@@ -1408,64 +1451,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return route;
}
private readProviderConversationId(params: unknown): string | undefined {
return (
this.readString(params, "threadId") ??
this.readString(this.readObject(params, "thread"), "id") ??
this.readString(params, "conversationId")
);
}
private readChildParentTurnId(context: CodexSessionContext, params: unknown): TurnId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverTurns.get(providerConversationId);
}
private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
parentTurnId: TurnId | undefined,
): void {
if (!parentTurnId) {
return;
}
const payload = this.readObject(params);
const item = this.readObject(payload, "item") ?? payload;
const itemType = this.readString(item, "type") ?? this.readString(item, "kind");
if (itemType !== "collabAgentToolCall") {
return;
}
const receiverThreadIds =
this.readArray(item, "receiverThreadIds")
?.map((value) => (typeof value === "string" ? value : null))
.filter((value): value is string => value !== null) ?? [];
for (const receiverThreadId of receiverThreadIds) {
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
}
}
private shouldSuppressChildConversationNotification(method: string): boolean {
return (
method === "thread/started" ||
method === "thread/status/changed" ||
method === "thread/archived" ||
method === "thread/unarchived" ||
method === "thread/closed" ||
method === "thread/compacted" ||
method === "thread/name/updated" ||
method === "thread/tokenUsage/updated" ||
method === "turn/started" ||
method === "turn/completed" ||
method === "turn/aborted" ||
method === "turn/plan/updated" ||
method === "item/plan/delta"
);
}
private readObject(value: unknown, key?: string): Record<string, unknown> | undefined {
const target =
key === undefined
@@ -1522,6 +1507,20 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
return brandIfNonEmpty(value, (normalized) => normalized);
}
function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
readonly binaryPath?: string;
readonly homePath?: string;
} {
const options = input.providerOptions?.codex;
if (!options) {
return {};
}
return {
...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
...(options.homePath ? { homePath: options.homePath } : {}),
};
}
function assertSupportedCodexCliVersion(input: {
readonly binaryPath: string;
readonly cwd: string;
@@ -1575,11 +1574,7 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
}
function readResumeThreadId(input: {
readonly resumeCursor?: unknown;
readonly threadId?: ThreadId;
readonly runtimeMode?: RuntimeMode;
}): string | undefined {
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
return readResumeCursorThreadId(input.resumeCursor);
}
+11 -86
View File
@@ -6,41 +6,22 @@
*
* @module ServerConfig
*/
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
export type RuntimeMode = typeof RuntimeMode.Type;
/**
* ServerDerivedPaths - Derived paths from the base directory.
*/
export interface ServerDerivedPaths {
readonly stateDir: string;
readonly dbPath: string;
readonly keybindingsConfigPath: string;
readonly settingsPath: string;
readonly worktreesDir: string;
readonly attachmentsDir: string;
readonly logsDir: string;
readonly serverLogPath: string;
readonly providerLogsDir: string;
readonly providerEventLogPath: string;
readonly terminalLogsDir: string;
readonly anonymousIdPath: string;
}
export type RuntimeMode = "web" | "desktop";
/**
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape extends ServerDerivedPaths {
readonly logLevel: LogLevel.LogLevel;
export interface ServerConfigShape {
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
readonly cwd: string;
readonly baseDir: string;
readonly keybindingsConfigPath: string;
readonly stateDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
@@ -49,87 +30,31 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly logWebSocketEvents: boolean;
}
export const deriveServerPaths = Effect.fn(function* (
baseDir: ServerConfigShape["baseDir"],
devUrl: ServerConfigShape["devUrl"],
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
const { join } = yield* Path.Path;
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
const dbPath = join(stateDir, "state.sqlite");
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
const providerLogsDir = join(logsDir, "provider");
return {
stateDir,
dbPath,
keybindingsConfigPath: join(stateDir, "keybindings.json"),
settingsPath: join(stateDir, "settings.json"),
worktreesDir: join(baseDir, "worktrees"),
attachmentsDir,
logsDir,
serverLogPath: join(logsDir, "server.log"),
providerLogsDir,
providerEventLogPath: join(providerLogsDir, "events.log"),
terminalLogsDir: join(logsDir, "terminals"),
anonymousIdPath: join(stateDir, "anonymous-id"),
};
});
export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* Effect.all(
[
fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
],
{ concurrency: "unbounded" },
);
});
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
static readonly layerTest = (cwd: string, statedir: string) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const devUrl = undefined;
const fs = yield* FileSystem.FileSystem;
const baseDir =
typeof baseDirOrPrefix === "string"
? baseDirOrPrefix
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
const path = yield* Path.Path;
return {
logLevel: "Error",
cwd,
baseDir,
...derivedPaths,
stateDir: statedir,
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
port: 0,
host: undefined,
authToken: undefined,
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
staticDir: undefined,
devUrl,
devUrl: undefined,
noBrowser: false,
} satisfies ServerConfigShape;
};
}),
);
}
+67
View File
@@ -0,0 +1,67 @@
import { Schema } from "effect";
/**
* GitCommandError - Git command execution failed.
*/
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
}
}
/**
* GitHubCliError - GitHub CLI execution or authentication failed.
*/
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
/**
* TextGenerationError - Commit or PR text generation failed.
*/
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
"TextGenerationError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Text generation failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerError - Stacked Git workflow orchestration failed.
*/
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git manager failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
*/
export type GitManagerServiceError =
| GitManagerError
| GitCommandError
| GitHubCliError
| TextGenerationError;
@@ -1,309 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { sanitizeThreadTitle } from "../Utils.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeClaudeBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const claudePath = path.join(binDir, "claude");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* fs.writeFileString(
claudePath,
[
"#!/bin/sh",
'args="$*"',
'stdin_content="$(cat)"',
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "args missing expected content" >&2',
" exit 2",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "args contained forbidden content" >&2',
" exit 3",
" fi",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
"fi",
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(claudePath, 0o755);
return binDir;
});
}
function withFakeClaudeEnv<A, E, R>(
input: {
output: string;
exitCode?: number;
stderr?: string;
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
const binDir = yield* makeFakeClaudeBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CLAUDE_STDERR;
}
if (input.argsMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
}
if (input.argsMustNotContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousArgsMustContain,
previousArgsMustNotContain,
previousStdinMustContain,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
} else {
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
} else {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDERR;
} else {
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
}
if (previous.previousArgsMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
}
if (previous.previousArgsMustNotContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
}),
);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
subject: "Add important change",
body: "",
},
}),
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
argsMustNotContain: "--effort",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/claude-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
effort: "high",
},
},
});
expect(generated.subject).toBe("Add important change");
}),
),
);
it.effect("forwards Claude fast mode and supported effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: "Improve orchestration flow",
body: "Body",
},
}),
argsMustContain: '--effort max --settings {"fastMode":true}',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/claude-effect",
commitSummary: "Improve orchestration",
diffSummary: "1 file changed",
diffPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
fastMode: true,
},
},
});
expect(generated.title).toBe("Improve orchestration flow");
}),
),
);
it.effect("generates thread titles through the Claude provider", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title:
' "Reconnect failures after restart because the session state does not recover" ',
},
}),
stdinMustContain: "You write concise thread titles for coding conversations.",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate reconnect failures after restarting the session.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe(
sanitizeThreadTitle(
'"Reconnect failures after restart because the session state does not recover"',
),
);
}),
),
);
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: ' """ """ ',
},
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
});
expect(generated.title).toBe("New thread");
}),
),
);
});
@@ -1,345 +0,0 @@
/**
* ClaudeTextGeneration – Text generation layer using the Claude CLI.
*
* Implements the same TextGenerationShape contract as CodexTextGeneration but
* delegates to the `claude` CLI (`claude -p`) with structured JSON output
* instead of the `codex exec` CLI.
*
* @module ClaudeTextGeneration
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "@t3tools/contracts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
/**
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
* We only care about `structured_output`.
*/
const ClaudeOutputEnvelope = Schema.Struct({
structured_output: Schema.Unknown,
});
const makeClaudeTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to collect process output"),
),
);
/**
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
const runClaudeJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.gen(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError(
"claude",
operation,
cause,
"Failed to read Claude CLI exit code",
),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
return stdout;
});
const rawStdout = yield* runClaudeCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
onSome: (value) => Effect.succeed(value),
}),
),
);
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
),
);
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
),
);
});
// ---------------------------------------------------------------------------
// TextGenerationShape methods
// ---------------------------------------------------------------------------
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"ClaudeTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"ClaudeTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"ClaudeTextGeneration.generateBranchName",
)(function* (input) {
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"ClaudeTextGeneration.generateThreadTitle",
)(function* (input) {
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
};
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
@@ -1,43 +1,20 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Result } from "effect";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "codex" as const,
model: "gpt-5.4-mini",
};
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(
dir: string,
input: {
output: string;
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
) {
function makeFakeCodexBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -50,102 +27,49 @@ function makeFakeCodexBinary(
[
"#!/bin/sh",
'output_path=""',
'seen_image="0"',
'seen_fast_service_tier="0"',
'seen_reasoning_effort=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
" shift",
' if [ -n "$1" ]; then',
' seen_image="1"',
" fi",
" shift",
" continue",
" fi",
' if [ "$1" = "--config" ]; then',
" shift",
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
' seen_fast_service_tier="1"',
" fi",
' case "$1" in',
" model_reasoning_effort=*)",
' seen_reasoning_effort="$1"',
" ;;",
" esac",
" shift",
" continue",
" fi",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
" shift",
" continue",
" fi",
" shift",
"done",
'stdin_content="$(cat)"',
...(input.requireImage
? [
'if [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
` exit 2`,
"fi",
]
: []),
...(input.requireFastServiceTier
? [
'if [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
` exit 5`,
"fi",
]
: []),
...(input.requireReasoningEffort !== undefined
? [
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
` exit 6`,
"fi",
]
: []),
...(input.forbidReasoningEffort
? [
'if [ -n "$seen_reasoning_effort" ]; then',
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
` exit 7`,
"fi",
]
: []),
...(input.stdinMustContain !== undefined
? [
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
' printf "%s\\n" "stdin missing expected content" >&2',
` exit 3`,
"fi",
]
: []),
...(input.stdinMustNotContain !== undefined
? [
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
' printf "%s\\n" "stdin contained forbidden content" >&2',
` exit 4`,
"fi",
]
: []),
...(input.stderr !== undefined
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
: []),
'if [ -n "$output_path" ]; then',
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
input.output,
"__T3CODE_FAKE_CODEX_OUTPUT__",
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
" exit 2",
"fi",
`exit ${input.exitCode ?? 0}`,
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 3",
" }",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "stdin contained forbidden content" >&2',
" exit 4",
" fi",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
"fi",
'if [ -n "$output_path" ]; then',
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
"fi",
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(codexPath, 0o755);
return codexPath;
return binDir;
});
}
@@ -155,9 +79,6 @@ function withFakeCodexEnv<A, E, R>(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
@@ -167,32 +88,106 @@ function withFakeCodexEnv<A, E, R>(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: codexPath,
},
},
const binDir = yield* makeFakeCodexBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CODEX_STDERR;
}
if (input.requireImage) {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
}
if (input.stdinMustNotContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
}
});
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousRequireImage,
previousStdinMustContain,
previousStdinMustNotContain,
};
}),
() => effect,
({ serverSettings, previousBinaryPath }) =>
serverSettings
.updateSettings({
providers: {
codex: {
binaryPath: previousBinaryPath,
},
},
})
.pipe(Effect.asVoid),
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
} else {
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
} else {
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CODEX_STDERR;
} else {
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
}
if (previous.previousRequireImage === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
if (previous.previousStdinMustNotContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
}
}),
);
}
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
@@ -212,7 +207,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject.length).toBeLessThanOrEqual(72);
@@ -223,63 +217,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
),
);
it.effect(
"forwards codex fast mode and non-default reasoning effort into codex exec config",
() =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
requireFastServiceTier: true,
requireReasoningEffort: "xhigh",
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "xhigh",
fastMode: true,
},
},
});
}),
),
);
it.effect("defaults git text generation codex effort to low", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
requireReasoningEffort: "low",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
}),
),
);
it.effect("generates commit message with branch when includeBranch is true", () =>
withFakeCodexEnv(
{
@@ -299,7 +236,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject).toBe("Add important change");
@@ -326,7 +262,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
commitSummary: "feat: improve orchestration flow",
diffSummary: "2 files changed",
diffPatch: "diff --git a/a.ts b/a.ts",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Improve orchestration flow");
@@ -350,7 +285,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Please update session handling.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("feat/session");
@@ -358,70 +292,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
),
);
it.effect("generates thread titles and trims them for sidebar use", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
title:
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Please investigate websocket reconnect regressions after a worktree restore.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
}),
),
);
it.effect("falls back when thread title normalization becomes whitespace-only", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
title: ' """ """ ',
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("New thread");
}),
),
);
it.effect("trims whitespace exposed after quote removal in thread titles", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
title: ` "' hello world '" `,
}),
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateThreadTitle({
cwd: process.cwd(),
message: "Name this thread.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("hello world");
}),
),
);
it.effect("omits attachment metadata section when no attachments are provided", () =>
withFakeCodexEnv(
{
@@ -436,7 +306,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Fix timeout behavior.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("fix/session-timeout");
@@ -456,27 +325,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
const generated = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
expect(generated.branch).toBe("fix/ui-regression");
}),
@@ -494,16 +363,15 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const attachmentId =
`thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
@@ -524,7 +392,9 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
}),
),
),
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
Effect.ensuring(
fs.remove(imagePath).pipe(Effect.catch(() => Effect.void)),
),
);
expect(generated.branch).toBe("fix/ui-regression");
@@ -543,15 +413,13 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
@@ -564,12 +432,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
},
],
})
.pipe(Effect.result);
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("missing --image input");
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("missing --image input");
}
}),
),
@@ -591,14 +464,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
.generateBranchName({
cwd: process.cwd(),
message: "Fix websocket reconnect flake",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("Codex returned invalid structured output");
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("Codex returned invalid structured output");
}
}),
),
@@ -620,16 +497,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
branch: "feature/codex-error",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain(
"Codex CLI command failed: codex execution failed",
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
}
}),
),
+249 -200
View File
@@ -1,45 +1,105 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGenerationError } from "../Errors.ts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
type BranchNameGenerationResult,
type CommitMessageGenerationResult,
type PrContentGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_MODEL = "gpt-5.3-codex";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return {
...document.schema,
$defs: document.definitions,
};
}
return document.schema;
}
function normalizeCodexError(
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes("Command not found: codex") ||
lower.includes("spawn codex") ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: "Codex CLI (`codex`) is required but not available on PATH.",
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverSettingsService = yield* Effect.service(ServerSettingsService);
type MaterializedImageAttachments = {
readonly imagePaths: ReadonlyArray<string>;
@@ -49,48 +109,46 @@ const makeCodexTextGeneration = Effect.gen(function* () {
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to collect process output"),
),
);
Effect.gen(function* () {
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.sync(() => {
text += Buffer.from(chunk).toString("utf8");
}),
).pipe(
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to collect process output"),
),
);
return text;
});
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const writeTempFile = (
operation: string,
prefix: string,
content: string,
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
return fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
})
.pipe(
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file`,
cause,
}),
),
);
): Effect.Effect<string, TextGenerationError> => {
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
return fileSystem.writeFileString(filePath, content).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file at ${filePath}.`,
cause,
}),
),
Effect.as(filePath),
);
};
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = (
_operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
_operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName",
attachments: BranchNameGenerationInput["attachments"],
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
Effect.gen(function* () {
@@ -105,7 +163,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
}
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
@@ -129,52 +187,34 @@ const makeCodexTextGeneration = Effect.gen(function* () {
outputSchemaJson,
imagePaths = [],
cleanupPaths = [],
modelSelection,
}: {
operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle";
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
prompt: string;
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: CodexModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
modelSelection.model,
CODEX_MODEL,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
@@ -183,14 +223,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
"-",
],
{
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
stream: Stream.make(new TextEncoder().encode(prompt)),
},
},
);
@@ -199,7 +235,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
),
);
@@ -208,8 +244,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
@@ -275,143 +312,155 @@ const makeCodexTextGeneration = Effect.gen(function* () {
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CodexTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
const wantsBranch = input.includeBranch === true;
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const prompt = [
"You write concise git commit messages.",
wantsBranch
? "Return a JSON object with keys: subject, body, branch."
: "Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
...(wantsBranch
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
const generated = yield* runCodexJson({
const outputSchemaJson = wantsBranch
? Schema.Struct({
subject: Schema.String,
body: Schema.String,
branch: Schema.String,
})
: Schema.Struct({
subject: Schema.String,
body: Schema.String,
});
return runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
outputSchemaJson,
}).pipe(
Effect.map(
(generated) =>
({
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
}) satisfies CommitMessageGenerationResult,
),
);
};
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"CodexTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
return runCodexJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"CodexTextGeneration.generateBranchName",
)(function* (input) {
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
outputSchemaJson: Schema.Struct({
title: Schema.String,
body: Schema.String,
}),
}).pipe(
Effect.map(
(generated) =>
({
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
}) satisfies PrContentGenerationResult,
),
);
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
};
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
return Effect.gen(function* () {
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
);
const attachmentLines = (input.attachments ?? []).map(
(attachment) =>
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
const promptSections = [
"You generate concise git branch names.",
"Return a JSON object with key: branch.",
"Rules:",
"- Branch should describe the requested work from the user message.",
"- Keep it short and specific (2-6 words).",
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
"- If images are attached, use them as primary context for visual/UI issues.",
"",
"User message:",
limitSection(input.message, 8_000),
];
if (attachmentLines.length > 0) {
promptSections.push(
"",
"Attachment metadata:",
limitSection(attachmentLines.join("\n"), 4_000),
);
}
const prompt = promptSections.join("\n");
const generated = yield* runCodexJson({
operation: "generateBranchName",
detail: "Invalid model selection.",
cwd: input.cwd,
prompt,
outputSchemaJson: Schema.Struct({
branch: Schema.String,
}),
imagePaths,
});
}
const generated = yield* runCodexJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
imagePaths,
modelSelection: input.modelSelection,
return {
branch: sanitizeBranchFragment(generated.branch),
} satisfies BranchNameGenerationResult;
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
const generateThreadTitle: TextGenerationShape["generateThreadTitle"] = Effect.fn(
"CodexTextGeneration.generateThreadTitle",
)(function* (input) {
const { imagePaths } = yield* materializeImageAttachments(
"generateThreadTitle",
input.attachments,
);
const { prompt, outputSchema } = buildThreadTitlePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateThreadTitle",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
operation: "generateThreadTitle",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
imagePaths,
modelSelection: input.modelSelection,
});
return {
title: sanitizeThreadTitle(generated.title),
} satisfies ThreadTitleGenerationResult;
});
};
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
generateThreadTitle,
} satisfies TextGenerationShape;
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -1,128 +0,0 @@
import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import { afterEach, expect, vi } from "vitest";
vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { GitHubCliLive } from "./GitHubCli.ts";
const mockedRunProcess = vi.mocked(runProcess);
const layer = it.layer(GitHubCliLive);
afterEach(() => {
mockedRunProcess.mockReset();
});
layer("GitHubCliLive", (it) => {
it.effect("parses pull request view output", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
number: 42,
title: "Add PR thread creation",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/pr-threads",
state: "OPEN",
mergedAt: null,
isCrossRepository: true,
headRepository: {
nameWithOwner: "octocat/codething-mvp",
},
headRepositoryOwner: {
login: "octocat",
},
}),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "#42",
});
});
assert.deepStrictEqual(result, {
number: 42,
title: "Add PR thread creation",
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
baseRefName: "main",
headRefName: "feature/pr-threads",
state: "open",
isCrossRepository: true,
headRepositoryNameWithOwner: "octocat/codething-mvp",
headRepositoryOwnerLogin: "octocat",
});
expect(mockedRunProcess).toHaveBeenCalledWith(
"gh",
[
"pr",
"view",
"#42",
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
expect.objectContaining({ cwd: "/repo" }),
);
}),
);
it.effect("reads repository clone URLs", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: JSON.stringify({
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
}),
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
const result = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getRepositoryCloneUrls({
cwd: "/repo",
repository: "octocat/codething-mvp",
});
});
assert.deepStrictEqual(result, {
nameWithOwner: "octocat/codething-mvp",
url: "https://github.com/octocat/codething-mvp",
sshUrl: "[email protected]:octocat/codething-mvp.git",
});
}),
);
it.effect("surfaces a friendly error when the pull request is not found", () =>
Effect.gen(function* () {
mockedRunProcess.mockRejectedValueOnce(
new Error(
"GraphQL: Could not resolve to a PullRequest with the number of 4888. (repository.pullRequest)",
),
);
const error = yield* Effect.gen(function* () {
const gh = yield* GitHubCli;
return yield* gh.getPullRequest({
cwd: "/repo",
reference: "4888",
});
}).pipe(Effect.flip);
assert.equal(error.message.includes("Pull request not found"), true);
}),
);
});
+68 -170
View File
@@ -1,14 +1,8 @@
import { Effect, Layer, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { runProcess } from "../../processRunner";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
type GitHubCliShape,
type GitHubPullRequestSummary,
} from "../Services/GitHubCli.ts";
import { GitHubCliError } from "../Errors.ts";
import { GitHubCli, type GitHubCliShape } from "../Services/GitHubCli.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
@@ -36,19 +30,6 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
});
}
if (
lower.includes("could not resolve to a pullrequest") ||
lower.includes("repository.pullrequest") ||
lower.includes("no pull requests found for branch") ||
lower.includes("pull request not found")
) {
return new GitHubCliError({
operation,
detail: "Pull request not found. Check the PR number or URL and try again.",
cause: error,
});
}
return new GitHubCliError({
operation,
detail: `GitHub CLI command failed: ${error.message}`,
@@ -63,102 +44,59 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
});
}
function normalizePullRequestState(input: {
state?: string | null | undefined;
mergedAt?: string | null | undefined;
}): "open" | "closed" | "merged" {
const mergedAt = input.mergedAt;
const state = input.state;
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
return "merged";
function parseOpenPullRequests(raw: string): ReadonlyArray<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> {
const trimmed = raw.trim();
if (trimmed.length === 0) return [];
const parsed: unknown = JSON.parse(trimmed);
if (!Array.isArray(parsed)) {
throw new Error("GitHub CLI returned non-array JSON.");
}
if (state === "CLOSED") {
return "closed";
const result: Array<{
number: number;
title: string;
url: string;
baseRefName: string;
headRefName: string;
}> = [];
for (const entry of parsed) {
if (!entry || typeof entry !== "object") {
continue;
}
const record = entry as Record<string, unknown>;
const number = record.number;
const title = record.title;
const url = record.url;
const baseRefName = record.baseRefName;
const headRefName = record.headRefName;
if (
typeof number !== "number" ||
!Number.isInteger(number) ||
number <= 0 ||
typeof title !== "string" ||
typeof url !== "string" ||
typeof baseRefName !== "string" ||
typeof headRefName !== "string"
) {
continue;
}
result.push({
number,
title,
url,
baseRefName,
headRefName,
});
}
return "open";
}
const RawGitHubPullRequestSchema = Schema.Struct({
number: PositiveInt,
title: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
baseRefName: TrimmedNonEmptyString,
headRefName: TrimmedNonEmptyString,
state: Schema.optional(Schema.NullOr(Schema.String)),
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
isCrossRepository: Schema.optional(Schema.Boolean),
headRepository: Schema.optional(
Schema.NullOr(
Schema.Struct({
nameWithOwner: Schema.String,
}),
),
),
headRepositoryOwner: Schema.optional(
Schema.NullOr(
Schema.Struct({
login: Schema.String,
}),
),
),
});
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
nameWithOwner: TrimmedNonEmptyString,
url: TrimmedNonEmptyString,
sshUrl: TrimmedNonEmptyString,
});
function normalizePullRequestSummary(
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
): GitHubPullRequestSummary {
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
const headRepositoryOwnerLogin =
raw.headRepositoryOwner?.login ??
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
: null);
return {
number: raw.number,
title: raw.title,
url: raw.url,
baseRefName: raw.baseRefName,
headRefName: raw.headRefName,
state: normalizePullRequestState(raw),
...(typeof raw.isCrossRepository === "boolean"
? { isCrossRepository: raw.isCrossRepository }
: {}),
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
};
}
function normalizeRepositoryCloneUrls(
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
): GitHubRepositoryCloneUrls {
return {
nameWithOwner: raw.nameWithOwner,
url: raw.url,
sshUrl: raw.sshUrl,
};
}
function decodeGitHubJson<S extends Schema.Top>(
raw: string,
schema: S,
operation: "listOpenPullRequests" | "getPullRequest" | "getRepositoryCloneUrls",
invalidDetail: string,
): Effect.Effect<S["Type"], GitHubCliError, S["DecodingServices"]> {
return Schema.decodeEffect(Schema.fromJsonString(schema))(raw).pipe(
Effect.mapError(
(error) =>
new GitHubCliError({
operation,
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
cause: error,
}),
),
);
return result;
}
const makeGitHubCli = Effect.sync(() => {
@@ -181,7 +119,7 @@ const makeGitHubCli = Effect.sync(() => {
"pr",
"list",
"--head",
input.headSelector,
input.headBranch,
"--state",
"open",
"--limit",
@@ -190,56 +128,21 @@ const makeGitHubCli = Effect.sync(() => {
"number,title,url,baseRefName,headRefName",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.map((result) => result.stdout),
Effect.flatMap((raw) =>
raw.length === 0
? Effect.succeed([])
: decodeGitHubJson(
raw,
Schema.Array(RawGitHubPullRequestSchema),
"listOpenPullRequests",
"GitHub CLI returned invalid PR list JSON.",
),
Effect.try({
try: () => parseOpenPullRequests(raw),
catch: (error: unknown) =>
new GitHubCliError({
operation: "listOpenPullRequests",
detail:
error instanceof Error
? `GitHub CLI returned invalid PR list JSON: ${error.message}`
: "GitHub CLI returned invalid PR list JSON.",
...(error !== undefined ? { cause: error } : {}),
}),
}),
),
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
),
getPullRequest: (input) =>
execute({
cwd: input.cwd,
args: [
"pr",
"view",
input.reference,
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubPullRequestSchema,
"getPullRequest",
"GitHub CLI returned invalid pull request JSON.",
),
),
Effect.map(normalizePullRequestSummary),
),
getRepositoryCloneUrls: (input) =>
execute({
cwd: input.cwd,
args: ["repo", "view", input.repository, "--json", "nameWithOwner,url,sshUrl"],
}).pipe(
Effect.map((result) => result.stdout.trim()),
Effect.flatMap((raw) =>
decodeGitHubJson(
raw,
RawGitHubRepositoryCloneUrlsSchema,
"getRepositoryCloneUrls",
"GitHub CLI returned invalid repository JSON.",
),
),
Effect.map(normalizeRepositoryCloneUrls),
),
createPullRequest: (input) =>
execute({
@@ -250,7 +153,7 @@ const makeGitHubCli = Effect.sync(() => {
"--base",
input.baseBranch,
"--head",
input.headSelector,
input.headBranch,
"--title",
input.title,
"--body-file",
@@ -267,11 +170,6 @@ const makeGitHubCli = Effect.sync(() => {
return trimmed.length > 0 ? trimmed : null;
}),
),
checkoutPullRequest: (input) =>
execute({
cwd: input.cwd,
args: ["pr", "checkout", input.reference, ...(input.force ? ["--force"] : [])],
}).pipe(Effect.asVoid),
} satisfies GitHubCliShape;
return service;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,59 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
layer("GitServiceLive", (it) => {
it.effect("runGit executes successful git commands", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.version",
cwd: process.cwd(),
args: ["--version"],
});
assert.equal(result.code, 0);
assert.ok(result.stdout.toLowerCase().includes("git version"));
}),
);
it.effect("runGit can return non-zero exit codes when allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.allowNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
allowNonZeroExit: true,
});
assert.notEqual(result.code, 0);
}),
);
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* Effect.result(
gitService.execute({
operation: "GitProcess.test.failOnNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
}),
);
assert.equal(result._tag, "Failure");
if (result._tag === "Failure") {
assert.ok(Schema.is(GitCommandError)(result.failure));
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
}
}),
);
});
+144
View File
@@ -0,0 +1,144 @@
/**
* Git process helpers - Effect-native git execution with typed errors.
*
* Centralizes child-process git invocation for server modules. This module
* only executes git commands and reports structured failures.
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
ExecuteGitInput,
ExecuteGitResult,
GitService,
GitServiceShape,
} from "../Services/GitService.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: ReadonlyArray<string>): string {
return `git ${args.join(" ")}`;
}
function toGitCommandError(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
detail: string,
) {
return (cause: unknown) =>
Schema.is(GitCommandError)(cause)
? cause
: new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
...(cause !== undefined ? { cause } : {}),
});
}
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
bytes += chunk.byteLength;
if (bytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
text += decoder.decode();
return text;
});
const makeGitService = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
} as const;
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
],
{ concurrency: "unbounded" },
);
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
});
}
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
});
return yield* commandEffect.pipe(
Effect.scoped,
Effect.timeoutOption(timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
}),
),
onSome: Effect.succeed,
}),
),
);
});
return {
execute,
} satisfies GitServiceShape;
});
export const GitServiceLive = Layer.effect(GitService, makeGitService);
@@ -1,73 +0,0 @@
/**
* RoutingTextGeneration – Dispatches text generation requests to either the
* Codex CLI or Claude CLI implementation based on the provider in each
* request input.
*
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
* the Claude layer; for any other value (including the default `undefined`) it
* falls through to the Codex layer.
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, ServiceMap } from "effect";
import {
TextGeneration,
type TextGenerationProvider,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent" ? claude : codex;
return {
generateCommitMessage: (input) =>
route(input.modelSelection.provider).generateCommitMessage(input),
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
generateThreadTitle: (input) => route(input.modelSelection.provider).generateThreadTitle(input),
} satisfies TextGenerationShape;
});
const InternalCodexLayer = Layer.effect(
CodexTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CodexTextGenerationLive));
const InternalClaudeLayer = Layer.effect(
ClaudeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
-193
View File
@@ -1,193 +0,0 @@
import { describe, expect, it } from "vitest";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
buildThreadTitlePrompt,
} from "./Prompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
import { TextGenerationError } from "@t3tools/contracts";
describe("buildCommitMessagePrompt", () => {
it("includes staged patch and summary in the prompt", () => {
const result = buildCommitMessagePrompt({
branch: "main",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md\n+hello",
includeBranch: false,
});
expect(result.prompt).toContain("Staged files:");
expect(result.prompt).toContain("M README.md");
expect(result.prompt).toContain("Staged patch:");
expect(result.prompt).toContain("diff --git a/README.md b/README.md");
expect(result.prompt).toContain("Branch: main");
// Should NOT include the branch generation instruction
expect(result.prompt).not.toContain("branch must be a short semantic git branch fragment");
});
it("includes branch generation instruction when includeBranch is true", () => {
const result = buildCommitMessagePrompt({
branch: "feature/foo",
stagedSummary: "M README.md",
stagedPatch: "diff",
includeBranch: true,
});
expect(result.prompt).toContain("branch must be a short semantic git branch fragment");
expect(result.prompt).toContain("Return a JSON object with keys: subject, body, branch.");
});
it("shows (detached) when branch is null", () => {
const result = buildCommitMessagePrompt({
branch: null,
stagedSummary: "M a.ts",
stagedPatch: "diff",
includeBranch: false,
});
expect(result.prompt).toContain("Branch: (detached)");
});
});
describe("buildPrContentPrompt", () => {
it("includes branch names, commits, and diff in the prompt", () => {
const result = buildPrContentPrompt({
baseBranch: "main",
headBranch: "feature/auth",
commitSummary: "feat: add login page",
diffSummary: "3 files changed",
diffPatch: "diff --git a/auth.ts b/auth.ts\n+export function login()",
});
expect(result.prompt).toContain("Base branch: main");
expect(result.prompt).toContain("Head branch: feature/auth");
expect(result.prompt).toContain("Commits:");
expect(result.prompt).toContain("feat: add login page");
expect(result.prompt).toContain("Diff stat:");
expect(result.prompt).toContain("3 files changed");
expect(result.prompt).toContain("Diff patch:");
expect(result.prompt).toContain("export function login()");
});
});
describe("buildBranchNamePrompt", () => {
it("includes the user message in the prompt", () => {
const result = buildBranchNamePrompt({
message: "Fix the login timeout bug",
});
expect(result.prompt).toContain("User message:");
expect(result.prompt).toContain("Fix the login timeout bug");
expect(result.prompt).not.toContain("Attachment metadata:");
});
it("includes attachment metadata when attachments are provided", () => {
const result = buildBranchNamePrompt({
message: "Fix the layout from screenshot",
attachments: [
{
type: "image" as const,
id: "att-123",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 12345,
},
],
});
expect(result.prompt).toContain("Attachment metadata:");
expect(result.prompt).toContain("screenshot.png");
expect(result.prompt).toContain("image/png");
expect(result.prompt).toContain("12345 bytes");
});
});
describe("buildThreadTitlePrompt", () => {
it("includes the user message in the prompt", () => {
const result = buildThreadTitlePrompt({
message: "Investigate reconnect regressions after session restore",
});
expect(result.prompt).toContain("User message:");
expect(result.prompt).toContain("Investigate reconnect regressions after session restore");
expect(result.prompt).not.toContain("Attachment metadata:");
});
it("includes attachment metadata when attachments are provided", () => {
const result = buildThreadTitlePrompt({
message: "Name this thread from the screenshot",
attachments: [
{
type: "image" as const,
id: "att-456",
name: "thread.png",
mimeType: "image/png",
sizeBytes: 67890,
},
],
});
expect(result.prompt).toContain("Attachment metadata:");
expect(result.prompt).toContain("thread.png");
expect(result.prompt).toContain("image/png");
expect(result.prompt).toContain("67890 bytes");
});
});
describe("sanitizeThreadTitle", () => {
it("truncates long titles with the shared sidebar-safe limit", () => {
expect(
sanitizeThreadTitle(
' "Reconnect failures after restart because the session state does not recover" ',
),
).toBe("Reconnect failures after restart because the se...");
});
});
describe("normalizeCliError", () => {
it("detects 'Command not found' and includes CLI name in the message", () => {
const error = normalizeCliError(
"claude",
"generateCommitMessage",
new Error("Command not found: claude"),
"Something went wrong",
);
expect(error).toBeInstanceOf(TextGenerationError);
expect(error.detail).toContain("Claude CLI");
expect(error.detail).toContain("not available on PATH");
});
it("uses the CLI name from the first argument for codex", () => {
const error = normalizeCliError(
"codex",
"generateBranchName",
new Error("Command not found: codex"),
"Something went wrong",
);
expect(error).toBeInstanceOf(TextGenerationError);
expect(error.detail).toContain("Codex CLI");
expect(error.detail).toContain("not available on PATH");
});
it("returns the error as-is if it is already a TextGenerationError", () => {
const existing = new TextGenerationError({
operation: "generatePrContent",
detail: "Already wrapped",
});
const result = normalizeCliError("claude", "generatePrContent", existing, "fallback");
expect(result).toBe(existing);
});
it("wraps unknown non-Error values with the fallback message", () => {
const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback");
expect(result).toBeInstanceOf(TextGenerationError);
expect(result.detail).toBe("fallback");
});
});
-202
View File
@@ -1,202 +0,0 @@
/**
* Shared prompt builders for text generation providers.
*
* Extracts the prompt construction logic that is identical across
* Codex, Claude, and any future CLI-based text generation backends.
*
* @module textGenerationPrompts
*/
import { Schema } from "effect";
import type { ChatAttachment } from "@t3tools/contracts";
import { limitSection } from "./Utils.ts";
// ---------------------------------------------------------------------------
// Commit message
// ---------------------------------------------------------------------------
export interface CommitMessagePromptInput {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
includeBranch: boolean;
}
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
const wantsBranch = input.includeBranch;
const prompt = [
"You write concise git commit messages.",
wantsBranch
? "Return a JSON object with keys: subject, body, branch."
: "Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
...(wantsBranch
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
if (wantsBranch) {
return {
prompt,
outputSchema: Schema.Struct({
subject: Schema.String,
body: Schema.String,
branch: Schema.String,
}),
};
}
return {
prompt,
outputSchema: Schema.Struct({
subject: Schema.String,
body: Schema.String,
}),
};
}
// ---------------------------------------------------------------------------
// PR content
// ---------------------------------------------------------------------------
export interface PrContentPromptInput {
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export function buildPrContentPrompt(input: PrContentPromptInput) {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const outputSchema = Schema.Struct({
title: Schema.String,
body: Schema.String,
});
return { prompt, outputSchema };
}
// ---------------------------------------------------------------------------
// Branch name
// ---------------------------------------------------------------------------
export interface BranchNamePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
interface PromptFromMessageInput {
instruction: string;
responseShape: string;
rules: ReadonlyArray<string>;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
function buildPromptFromMessage(input: PromptFromMessageInput): string {
const attachmentLines = (input.attachments ?? []).map(
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
const promptSections = [
input.instruction,
input.responseShape,
"Rules:",
...input.rules.map((rule) => `- ${rule}`),
"",
"User message:",
limitSection(input.message, 8_000),
];
if (attachmentLines.length > 0) {
promptSections.push(
"",
"Attachment metadata:",
limitSection(attachmentLines.join("\n"), 4_000),
);
}
return promptSections.join("\n");
}
export function buildBranchNamePrompt(input: BranchNamePromptInput) {
const prompt = buildPromptFromMessage({
instruction: "You generate concise git branch names.",
responseShape: "Return a JSON object with key: branch.",
rules: [
"Branch should describe the requested work from the user message.",
"Keep it short and specific (2-6 words).",
"Use plain words only, no issue prefixes and no punctuation-heavy text.",
"If images are attached, use them as primary context for visual/UI issues.",
],
message: input.message,
attachments: input.attachments,
});
const outputSchema = Schema.Struct({
branch: Schema.String,
});
return { prompt, outputSchema };
}
// ---------------------------------------------------------------------------
// Thread title
// ---------------------------------------------------------------------------
export interface ThreadTitlePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
export function buildThreadTitlePrompt(input: ThreadTitlePromptInput) {
const prompt = buildPromptFromMessage({
instruction: "You write concise thread titles for coding conversations.",
responseShape: "Return a JSON object with key: title.",
rules: [
"Title should summarize the user's request, not restate it verbatim.",
"Keep it short and specific (3-8 words).",
"Avoid quotes, filler, prefixes, and trailing punctuation.",
"If images are attached, use them as primary context for visual/UI issues.",
],
message: input.message,
attachments: input.attachments,
});
const outputSchema = Schema.Struct({
title: Schema.String,
});
return { prompt, outputSchema };
}
+1 -135
View File
@@ -22,28 +22,7 @@ import type {
GitStatusResult,
} from "@t3tools/contracts";
import type { GitCommandError } from "@t3tools/contracts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly truncateOutputAtMaxBytes?: boolean;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
import type { GitCommandError } from "../Errors.ts";
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
@@ -54,35 +33,6 @@ export interface GitPreparedCommitContext {
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
@@ -96,11 +46,6 @@ export interface GitRangeContext {
diffPatch: string;
}
export interface GitListWorkspaceFilesResult {
readonly paths: ReadonlyArray<string>;
readonly truncated: boolean;
}
export interface GitRenameBranchInput {
cwd: string;
oldBranch: string;
@@ -111,41 +56,10 @@ export interface GitRenameBranchResult {
branch: string;
}
export interface GitFetchPullRequestBranchInput {
cwd: string;
prNumber: number;
branch: string;
}
export interface GitEnsureRemoteInput {
cwd: string;
preferredName: string;
url: string;
}
export interface GitFetchRemoteBranchInput {
cwd: string;
remoteName: string;
remoteBranch: string;
localBranch: string;
}
export interface GitSetBranchUpstreamInput {
cwd: string;
branch: string;
remoteName: string;
remoteBranch: string;
}
/**
* GitCoreShape - Service API for low-level Git repository interactions.
*/
export interface GitCoreShape {
/**
* Execute a raw Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
/**
* Read Git status for a repository.
*/
@@ -161,7 +75,6 @@ export interface GitCoreShape {
*/
readonly prepareCommitContext: (
cwd: string,
filePaths?: readonly string[],
) => Effect.Effect<GitPreparedCommitContext | null, GitCommandError>;
/**
@@ -171,7 +84,6 @@ export interface GitCoreShape {
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
@@ -198,26 +110,6 @@ export interface GitCoreShape {
key: string,
) => Effect.Effect<string | null, GitCommandError>;
/**
* Determine whether the provided cwd is inside a git work tree.
*/
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
/**
* List tracked and untracked workspace file paths relative to cwd.
*/
readonly listWorkspaceFiles: (
cwd: string,
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
/**
* Remove gitignored paths from a relative path list.
*/
readonly filterIgnoredPaths: (
cwd: string,
relativePaths: ReadonlyArray<string>,
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
/**
* List local + remote branches and branch metadata.
*/
@@ -237,32 +129,6 @@ export interface GitCoreShape {
input: GitCreateWorktreeInput,
) => Effect.Effect<GitCreateWorktreeResult, GitCommandError>;
/**
* Materialize a GitHub pull request head as a local branch without switching checkout.
*/
readonly fetchPullRequestBranch: (
input: GitFetchPullRequestBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Ensure a named remote exists for the provided URL, returning the reused or created remote name.
*/
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
/**
* Fetch a remote branch into a local branch without checkout.
*/
readonly fetchRemoteBranch: (
input: GitFetchRemoteBranchInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Set the upstream tracking branch for a local branch.
*/
readonly setBranchUpstream: (
input: GitSetBranchUpstreamInput,
) => Effect.Effect<void, GitCommandError>;
/**
* Remove an existing worktree.
*/
+3 -38
View File
@@ -9,7 +9,7 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner";
import type { GitHubCliError } from "@t3tools/contracts";
import type { GitHubCliError } from "../Errors.ts";
export interface GitHubPullRequestSummary {
readonly number: number;
@@ -17,16 +17,6 @@ export interface GitHubPullRequestSummary {
readonly url: string;
readonly baseRefName: string;
readonly headRefName: string;
readonly state?: "open" | "closed" | "merged";
readonly isCrossRepository?: boolean;
readonly headRepositoryNameWithOwner?: string | null;
readonly headRepositoryOwnerLogin?: string | null;
}
export interface GitHubRepositoryCloneUrls {
readonly nameWithOwner: string;
readonly url: string;
readonly sshUrl: string;
}
/**
@@ -47,33 +37,17 @@ export interface GitHubCliShape {
*/
readonly listOpenPullRequests: (input: {
readonly cwd: string;
readonly headSelector: string;
readonly headBranch: string;
readonly limit?: number;
}) => Effect.Effect<ReadonlyArray<GitHubPullRequestSummary>, GitHubCliError>;
/**
* Resolve a pull request by URL, number, or branch-ish identifier.
*/
readonly getPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
}) => Effect.Effect<GitHubPullRequestSummary, GitHubCliError>;
/**
* Resolve clone URLs for a GitHub repository.
*/
readonly getRepositoryCloneUrls: (input: {
readonly cwd: string;
readonly repository: string;
}) => Effect.Effect<GitHubRepositoryCloneUrls, GitHubCliError>;
/**
* Create a pull request from branch context and body file.
*/
readonly createPullRequest: (input: {
readonly cwd: string;
readonly baseBranch: string;
readonly headSelector: string;
readonly headBranch: string;
readonly title: string;
readonly bodyFile: string;
}) => Effect.Effect<void, GitHubCliError>;
@@ -84,15 +58,6 @@ export interface GitHubCliShape {
readonly getDefaultBranch: (input: {
readonly cwd: string;
}) => Effect.Effect<string | null, GitHubCliError>;
/**
* Checkout a pull request into the current repository worktree.
*/
readonly checkoutPullRequest: (input: {
readonly cwd: string;
readonly reference: string;
readonly force?: boolean;
}) => Effect.Effect<void, GitHubCliError>;
}
/**
+1 -30
View File
@@ -7,11 +7,6 @@
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
GitResolvePullRequestResult,
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStatusInput,
@@ -19,16 +14,7 @@ import {
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
import type { GitManagerServiceError } from "../Errors.ts";
/**
* GitManagerShape - Service API for high-level Git workflow actions.
@@ -41,27 +27,12 @@ export interface GitManagerShape {
input: GitStatusInput,
) => Effect.Effect<GitStatusResult, GitManagerServiceError>;
/**
* Resolve a pull request by URL/number against the current repository.
*/
readonly resolvePullRequest: (
input: GitPullRequestRefInput,
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
/**
* Prepare a new thread workspace from a pull request in local or worktree mode.
*/
readonly preparePullRequestThread: (
input: GitPreparePullRequestThreadInput,
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
@@ -0,0 +1,45 @@
/**
* GitService - Service for Git command execution.
*
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* domain errors for Git command execution.
*
* @module GitService
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
/**
* GitServiceShape - Service API for Git command execution.
*/
export interface GitServiceShape {
/**
* Execute a Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
}
/**
* GitService - Service for Git command execution.
*/
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
"t3/git/Services/GitService",
) {}
+2 -31
View File
@@ -8,12 +8,9 @@
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { ChatAttachment } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent";
import type { TextGenerationError } from "../Errors.ts";
export interface CommitMessageGenerationInput {
cwd: string;
@@ -22,8 +19,6 @@ export interface CommitMessageGenerationInput {
stagedPatch: string;
/** When true, the model also returns a semantic branch name for the change. */
includeBranch?: boolean;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface CommitMessageGenerationResult {
@@ -40,8 +35,6 @@ export interface PrContentGenerationInput {
commitSummary: string;
diffSummary: string;
diffPatch: string;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface PrContentGenerationResult {
@@ -53,33 +46,18 @@ export interface BranchNameGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface BranchNameGenerationResult {
branch: string;
}
export interface ThreadTitleGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
}
export interface ThreadTitleGenerationResult {
title: string;
}
export interface TextGenerationService {
generateCommitMessage(
input: CommitMessageGenerationInput,
): Promise<CommitMessageGenerationResult>;
generatePrContent(input: PrContentGenerationInput): Promise<PrContentGenerationResult>;
generateBranchName(input: BranchNameGenerationInput): Promise<BranchNameGenerationResult>;
generateThreadTitle(input: ThreadTitleGenerationInput): Promise<ThreadTitleGenerationResult>;
}
/**
@@ -106,13 +84,6 @@ export interface TextGenerationShape {
readonly generateBranchName: (
input: BranchNameGenerationInput,
) => Effect.Effect<BranchNameGenerationResult, TextGenerationError>;
/**
* Generate a concise thread title from a user's first message.
*/
readonly generateThreadTitle: (
input: ThreadTitleGenerationInput,
) => Effect.Effect<ThreadTitleGenerationResult, TextGenerationError>;
}
/**
-123
View File
@@ -1,123 +0,0 @@
/**
* Shared utilities for text generation layers (Codex, Claude, etc.).
*
* @module textGenerationUtils
*/
import { Schema } from "effect";
import { TextGenerationError } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** Normalise a raw thread title to a compact single-line sidebar-safe label. */
export function sanitizeThreadTitle(raw: string): string {
const normalized = raw
.trim()
.split(/\r?\n/g)[0]
?.trim()
.replace(/^['"`]+|['"`]+$/g, "")
.trim()
.replace(/\s+/g, " ");
if (!normalized || normalized.trim().length === 0) {
return "New thread";
}
if (normalized.length <= 50) {
return normalized;
}
return `${normalized.slice(0, 47).trimEnd()}...`;
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
Loaded 100 of 455 files, more files were not shown because too many files have changed in this diff. Show more