Compare commits
216
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3b41bce3a | ||
|
|
31f82efd2e | ||
|
|
24599aaeed | ||
|
|
f403b23e9a | ||
|
|
39c71a0394 | ||
|
|
d249e628ee | ||
|
|
40fcb6bdf8 | ||
|
|
d58ff5de26 | ||
|
|
e28ad18106 | ||
|
|
525411101d | ||
|
|
0f208447ed | ||
|
|
71e0573459 | ||
|
|
c63ea8d25b | ||
|
|
b9e529e0b5 | ||
|
|
0f702fcd62 | ||
|
|
13f2f9bc58 | ||
|
|
91cf202177 | ||
|
|
d21a8d597b | ||
|
|
14022f1d00 | ||
|
|
28c62f3efd | ||
|
|
268bb4bfa3 | ||
|
|
477b4f9d0e | ||
|
|
d5d88270f0 | ||
|
|
373725f96e | ||
|
|
fcb1a50ee4 | ||
|
|
ec3778bbf4 | ||
|
|
8c5b8d3b72 | ||
|
|
010ba70561 | ||
|
|
6ee057e25b | ||
|
|
551aebc604 | ||
|
|
9de85ea16e | ||
|
|
10dde452f9 | ||
|
|
116c8c5e8e | ||
|
|
f8886e874d | ||
|
|
2435a9cd58 | ||
|
|
78d53062d1 | ||
|
|
697d71d57d | ||
|
|
d74b086aaf | ||
|
|
6496aedc92 | ||
|
|
e972fad300 | ||
|
|
1bd4d6d953 | ||
|
|
e9655d43d5 | ||
|
|
f0a7ddaf80 | ||
|
|
ed6c12c709 | ||
|
|
a1b75fe17f | ||
|
|
2e5e75699e | ||
|
|
be308beacc | ||
|
|
2589176c82 | ||
|
|
adfd99bdec | ||
|
|
1683ee7b11 | ||
|
|
e6575c4149 | ||
|
|
ae7283e021 | ||
|
|
640a2cca9f | ||
|
|
12edc3455c | ||
|
|
26f631b638 | ||
|
|
981cf40561 | ||
|
|
689dda59e9 | ||
|
|
0a67f9dd39 | ||
|
|
df6bb188d4 | ||
|
|
03053d9ee0 | ||
|
|
9c4d7a83e2 | ||
|
|
7425a3c4b3 | ||
|
|
344e04b623 | ||
|
|
7b71e234e0 | ||
|
|
77f67d1766 | ||
|
|
1c2ed75937 | ||
|
|
17e6cad479 | ||
|
|
feff86638e | ||
|
|
ad28eaa86f | ||
|
|
d36bbc177d | ||
|
|
aeddb57594 | ||
|
|
f2253269dd | ||
|
|
d08cecf126 | ||
|
|
afad39d125 | ||
|
|
f97916f371 | ||
|
|
86e204439e | ||
|
|
04a931fc79 | ||
|
|
75354bbd96 | ||
|
|
6a10e97a97 | ||
|
|
1542b00db2 | ||
|
|
f79f8bac80 | ||
|
|
92f1a4aa3c | ||
|
|
11f929c397 | ||
|
|
0616338911 | ||
|
|
58427d565d | ||
|
|
9b3dbada17 | ||
|
|
4797f99cf8 | ||
|
|
50f35351a2 | ||
|
|
c7460bde16 | ||
|
|
2c110e8ce2 | ||
|
|
5707a6ee1d | ||
|
|
291411a45e | ||
|
|
87abc22f39 | ||
|
|
441582dbb8 | ||
|
|
1b1ede92ba | ||
|
|
4ec7ae33c5 | ||
|
|
317fcc659b | ||
|
|
ff7e084a33 | ||
|
|
c590beb4e3 | ||
|
|
e9ced44ac6 | ||
|
|
802cd127d1 | ||
|
|
931c56b2d0 | ||
|
|
484662b2d4 | ||
|
|
2cd04f08c1 | ||
|
|
4916dad78e | ||
|
|
d27c215014 | ||
|
|
d5c97faac5 | ||
|
|
531b12e192 | ||
|
|
b293b083fc | ||
|
|
b297e20f4e | ||
|
|
44be7f3ac3 | ||
|
|
ea5a100a74 | ||
|
|
6841fa17d4 | ||
|
|
5c03804bac | ||
|
|
d6ed393255 | ||
|
|
2d9139767a | ||
|
|
95fcc89074 | ||
|
|
eb59853596 | ||
|
|
a2682de421 | ||
|
|
325c0a3687 | ||
|
|
7c7fcf46c2 | ||
|
|
0c39733cbf | ||
|
|
a76413594e | ||
|
|
1100d5a6f7 | ||
|
|
9abf967700 | ||
|
|
cc83094bc6 | ||
|
|
f5bdc138f6 | ||
|
|
2d8ca48175 | ||
|
|
4ca4a1f99c | ||
|
|
5470801c4a | ||
|
|
2ad2d3e6f5 | ||
|
|
b175d6b2a3 | ||
|
|
c5c12aa738 | ||
|
|
7241400edd | ||
|
|
310fd0b187 | ||
|
|
db94743220 | ||
|
|
07aaf37fd4 | ||
|
|
65a808808f | ||
|
|
cca1aa1588 | ||
|
|
c9d4b773c9 | ||
|
|
e23f3102f4 | ||
|
|
ec89587c37 | ||
|
|
32d89806d7 | ||
|
|
2fd4e06b34 | ||
|
|
3cffdce1c1 | ||
|
|
6d2f4f4cdf | ||
|
|
865d7bd684 | ||
|
|
392d63231c | ||
|
|
7559f5ad70 | ||
|
|
605e8143e0 | ||
|
|
5b056cd337 | ||
|
|
6c350489b1 | ||
|
|
2ae63f4aa2 | ||
|
|
3d0233e3b0 | ||
|
|
64f2c3a465 | ||
|
|
0a12333448 | ||
|
|
9db54c9b19 | ||
|
|
34430e3514 | ||
|
|
99e44f2c23 | ||
|
|
7a0f2d9b30 | ||
|
|
4bf310f7ca | ||
|
|
8b9fbe701d | ||
|
|
0c5be023e4 | ||
|
|
86e87a8789 | ||
|
|
404e78a506 | ||
|
|
73563c7c25 | ||
|
|
326595b148 | ||
|
|
41a8468b08 | ||
|
|
ced2ecb6ba | ||
|
|
2d746b3a7e | ||
|
|
e6ac39de75 | ||
|
|
b76a0a6c91 | ||
|
|
9fdec3c2c8 | ||
|
|
760fe643e8 | ||
|
|
93af851dc5 | ||
|
|
fabb3e0734 | ||
|
|
9ca9a862a5 | ||
|
|
827dc9ff9f | ||
|
|
09b32ac9dd | ||
|
|
253684e280 | ||
|
|
f6d40ce841 | ||
|
|
36fb1bb7e4 | ||
|
|
4a82c1608f | ||
|
|
3efb3da007 | ||
|
|
11606fd9c6 | ||
|
|
a935db07ef | ||
|
|
98860a9549 | ||
|
|
7688742b2a | ||
|
|
b2efe4f83c | ||
|
|
f934b435fa | ||
|
|
3c121585da | ||
|
|
40acfbd2df | ||
|
|
0af61bf6ba | ||
|
|
7b2968f2ff | ||
|
|
a1c7b98f98 | ||
|
|
99ea16a969 | ||
|
|
ebe44d03a5 | ||
|
|
dcd2d50768 | ||
|
|
f11764c517 | ||
|
|
77c81b7468 | ||
|
|
7a5ccd3310 | ||
|
|
e4df6fcf8e | ||
|
|
b2be7f4e4f | ||
|
|
94beb21a43 | ||
|
|
30e05538b7 | ||
|
|
c884947ea8 | ||
|
|
61289a152d | ||
|
|
906550f9af | ||
|
|
c2aaa89b57 | ||
|
|
dde48e9414 | ||
|
|
b1608f41ad | ||
|
|
78d89e3d35 | ||
|
|
1309495218 | ||
|
|
c34a4c69e5 | ||
|
|
2f6cac0cf0 | ||
|
|
5c26df3a4f |
No files matched your search
@@ -0,0 +1,21 @@
|
||||
# Architecture
|
||||
|
||||
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Browser (React + Vite) │
|
||||
│ Connected via WebSocket │
|
||||
└──────────┬──────────────────────┘
|
||||
│ ws://localhost:3773
|
||||
┌──────────▼──────────────────────┐
|
||||
│ apps/server (Node.js) │
|
||||
│ WebSocket + HTTP static server │
|
||||
│ ProviderManager │
|
||||
│ CodexAppServerManager │
|
||||
└──────────┬──────────────────────┘
|
||||
│ JSON-RPC over stdio
|
||||
┌──────────▼──────────────────────┐
|
||||
│ codex app-server │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
# CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
@@ -0,0 +1,5 @@
|
||||
# Codex prerequisites
|
||||
|
||||
- Install Codex CLI so `codex` is on your PATH.
|
||||
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
|
||||
- T3 Code starts the server via `codex app-server` per session.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Provider architecture
|
||||
|
||||
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
|
||||
|
||||
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
|
||||
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
|
||||
|
||||
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
|
||||
|
||||
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
|
||||
- `providers.respondToRequest`, `providers.stopSession`
|
||||
- `shell.openInEditor`, `server.getConfig`
|
||||
|
||||
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
|
||||
@@ -0,0 +1,22 @@
|
||||
# Quick start
|
||||
|
||||
```bash
|
||||
# Development (with hot reload)
|
||||
bun run dev
|
||||
|
||||
# Desktop development
|
||||
bun run dev:desktop
|
||||
|
||||
# Desktop development on an isolated port set
|
||||
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
|
||||
# Production
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
```
|
||||
@@ -0,0 +1,6 @@
|
||||
# Runtime modes
|
||||
|
||||
T3 Code has a global runtime mode switch in the chat toolbar:
|
||||
|
||||
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
|
||||
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
|
||||
@@ -0,0 +1,42 @@
|
||||
# Scripts
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
||||
- `bun run 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.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
|
||||
## Desktop `.dmg` packaging notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
|
||||
## Running multiple dev instances
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
- Default ports: server `3773`, web `5733`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
|
||||
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
|
||||
@@ -0,0 +1,6 @@
|
||||
# Workspace layout
|
||||
|
||||
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
|
||||
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
|
||||
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
|
||||
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
@@ -8,7 +8,7 @@ on:
|
||||
|
||||
jobs:
|
||||
quality:
|
||||
name: Lint, Typecheck, Test, Build
|
||||
name: Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -34,6 +34,14 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -46,6 +54,14 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Install browser test runtime
|
||||
run: |
|
||||
cd apps/web
|
||||
bunx playwright install --with-deps chromium
|
||||
|
||||
- name: Browser test
|
||||
run: bun run --cwd apps/web test:browser
|
||||
|
||||
- name: Build desktop pipeline
|
||||
run: bun run build:desktop
|
||||
|
||||
|
||||
+141
-100
@@ -22,12 +22,10 @@ jobs:
|
||||
outputs:
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
ref: ${{ steps.release_ref.outputs.value }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
@@ -58,32 +56,6 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Update version strings
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
env:
|
||||
RELEASE_VERSION: ${{ steps.release_meta.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
}
|
||||
'
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
run: bun install
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
@@ -96,39 +68,6 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- name: Commit and push release version + tag
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ steps.release_meta.outputs.tag }}
|
||||
run: |
|
||||
if git ls-remote --exit-code --tags origin "$RELEASE_TAG" >/dev/null 2>&1; then
|
||||
echo "Tag $RELEASE_TAG already exists on origin." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
||||
|
||||
if ! git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
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" -m "Co-authored-by: codex <[email protected]>"
|
||||
fi
|
||||
|
||||
git tag "$RELEASE_TAG"
|
||||
git push origin "HEAD:${GITHUB_REF_NAME}"
|
||||
git push origin "refs/tags/$RELEASE_TAG"
|
||||
|
||||
- id: release_ref
|
||||
name: Resolve source ref
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
echo "value=refs/tags/${{ steps.release_meta.outputs.tag }}" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "value=${GITHUB_SHA}" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
@@ -198,6 +137,7 @@ jobs:
|
||||
--target "${{ matrix.target }}"
|
||||
--arch "${{ matrix.arch }}"
|
||||
--build-version "${{ needs.preflight.outputs.version }}"
|
||||
--verbose
|
||||
)
|
||||
|
||||
has_all() {
|
||||
@@ -239,57 +179,71 @@ jobs:
|
||||
|
||||
bun run dist:desktop:artifact -- "${args[@]}"
|
||||
|
||||
- name: Collect release assets
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p release-publish
|
||||
|
||||
shopt -s nullglob
|
||||
for pattern in \
|
||||
"release/*.dmg" \
|
||||
"release/*.zip" \
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/latest*.yml"; do
|
||||
for file in $pattern; do
|
||||
cp "$file" release-publish/
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: desktop-${{ matrix.platform }}-${{ matrix.arch }}
|
||||
path: release/*
|
||||
path: release-publish/*
|
||||
if-no-files-found: error
|
||||
|
||||
# publish_cli:
|
||||
# name: Publish CLI to npm
|
||||
# needs: [preflight, build]
|
||||
# runs-on: ubuntu-24.04
|
||||
# steps:
|
||||
# - name: Checkout
|
||||
# uses: actions/checkout@v4
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
# - name: Setup Bun
|
||||
# uses: oven-sh/setup-bun@v2
|
||||
# with:
|
||||
# bun-version-file: package.json
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
# - name: Setup Node
|
||||
# uses: actions/setup-node@v4
|
||||
# with:
|
||||
# node-version-file: package.json
|
||||
# registry-url: https://registry.npmjs.org
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
# - name: Install dependencies
|
||||
# run: bun install --frozen-lockfile
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
# - name: Set CLI package version from release tag
|
||||
# env:
|
||||
# RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
# run: |
|
||||
# node --input-type=module -e '
|
||||
# import { readFileSync, writeFileSync } from "node:fs";
|
||||
# const packagePath = "apps/server/package.json";
|
||||
# const packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
|
||||
# packageJson.version = process.env.RELEASE_VERSION;
|
||||
# writeFileSync(packagePath, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
# '
|
||||
- name: Build CLI package
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
# - name: Build CLI package
|
||||
# run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
# - name: Publish CLI package
|
||||
# run: bun --cwd apps/server publish --access public
|
||||
- name: Publish CLI package
|
||||
run: node apps/server/scripts/cli.ts publish --tag alpha --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build]
|
||||
# needs: [preflight, build, publish_cli]
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Download all desktop artifacts
|
||||
@@ -303,7 +257,94 @@ jobs:
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
files: release-assets/*
|
||||
make_latest: true
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
needs: [preflight, release]
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: main
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
RELEASE_VERSION: ${{ needs.preflight.outputs.version }}
|
||||
run: |
|
||||
node --input-type=module -e '
|
||||
import { appendFileSync, readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
const files = [
|
||||
"apps/server/package.json",
|
||||
"apps/desktop/package.json",
|
||||
"apps/web/package.json",
|
||||
"packages/contracts/package.json",
|
||||
];
|
||||
|
||||
let changed = false;
|
||||
for (const file of files) {
|
||||
const packageJson = JSON.parse(readFileSync(file, "utf8"));
|
||||
if (packageJson.version !== process.env.RELEASE_VERSION) {
|
||||
packageJson.version = process.env.RELEASE_VERSION;
|
||||
writeFileSync(file, `${JSON.stringify(packageJson, null, 2)}\n`);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!changed) {
|
||||
console.log("All package.json versions already match release version.");
|
||||
}
|
||||
|
||||
appendFileSync(process.env.GITHUB_OUTPUT, `changed=${changed}\n`);
|
||||
'
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bun install
|
||||
|
||||
- name: Commit and push version bump
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
shell: bash
|
||||
env:
|
||||
RELEASE_TAG: ${{ needs.preflight.outputs.tag }}
|
||||
run: |
|
||||
if git diff --quiet -- apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock; then
|
||||
echo "No version changes to commit."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
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"
|
||||
git push origin HEAD:main
|
||||
+5
-1
@@ -5,10 +5,14 @@ node_modules
|
||||
*.log
|
||||
*.tsbuildinfo
|
||||
apps/*/dist
|
||||
.astro
|
||||
packages/*/dist
|
||||
.env
|
||||
.env.local
|
||||
build/
|
||||
.logs/
|
||||
release/
|
||||
.t3
|
||||
.t3
|
||||
apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
@@ -1,546 +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
|
||||
|
||||
1. Provider runtime ingestion expects canonical `ProviderRuntimeEvent` shapes, not provider-native payloads.
|
||||
2. `ProviderService.startSession` currently defaults to `provider: "codex"` unless explicitly provided.
|
||||
3. `thread.turn.start` has no provider field today, so first-turn provider selection cannot be explicitly requested.
|
||||
4. `ProviderService` 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
|
||||
|
||||
Update `packages/contracts/src/provider.ts`:
|
||||
|
||||
1. Extend `ProviderSessionStartInput` with optional Claude-specific fields (for example `claudeBinaryPath`, `permissionMode`, `maxThinkingTokens`).
|
||||
2. Keep fields optional so current call sites remain valid.
|
||||
3. Continue using generic `resumeThreadId` + `resumeCursor` as the cross-provider recovery mechanism.
|
||||
|
||||
### 1.4 Contract tests
|
||||
|
||||
Update/add tests in `packages/contracts/src/*.test.ts` for:
|
||||
|
||||
1. New command payload shape.
|
||||
2. Provider-aware model resolution behavior.
|
||||
3. Backward compatibility of existing command/schema decoding.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Claude adapter implementation
|
||||
|
||||
### 2.1 Add adapter service + layer
|
||||
|
||||
Create:
|
||||
|
||||
1. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts`
|
||||
2. `apps/server/src/provider/Layers/ClaudeCodeAdapter.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 `claudeBinaryPath`)
|
||||
4. `permissionMode`
|
||||
5. `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 `resumeThreadId` / `resumeCursor`.
|
||||
|
||||
#### 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`.
|
||||
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 abortController = new AbortController();
|
||||
const result = query({
|
||||
prompt: makePromptAsyncIterable(input.sessionId),
|
||||
options: {
|
||||
cwd: input.cwd,
|
||||
model: input.model,
|
||||
permissionMode: input.permissionMode,
|
||||
maxThinkingTokens: input.maxThinkingTokens,
|
||||
pathToClaudeCodeExecutable: input.claudeBinaryPath,
|
||||
resume: input.resumeThreadId,
|
||||
resumeSessionAt: readResumeCursor(input.resumeCursor),
|
||||
signal: abortController.signal,
|
||||
includePartialMessages: true,
|
||||
canUseTool: makeCanUseTool(input.sessionId),
|
||||
hooks: makeClaudeHooks(input.sessionId),
|
||||
},
|
||||
});
|
||||
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 queue = yield* Queue.unbounded<ClaudeSdkMessage>();
|
||||
yield* Effect.forkScoped(
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
for await (const message of session.result) {
|
||||
Queue.offerAllUnsafe(queue, [message]);
|
||||
}
|
||||
},
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
detail: "Claude runtime stream pump failed.",
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
const sdkMessageStream = Stream.fromQueue(queue);
|
||||
```
|
||||
|
||||
#### 2.2.d Multi-turn prompt queue pattern (Effect)
|
||||
|
||||
Use an Effect queue as the single input boundary:
|
||||
|
||||
```ts
|
||||
const promptQueue = yield* Queue.unbounded<ClaudePromptEnvelope>();
|
||||
|
||||
const prompt: AsyncIterable<ClaudePromptEnvelope> = {
|
||||
[Symbol.asyncIterator]() {
|
||||
return {
|
||||
next: async () => {
|
||||
const item = await Effect.runPromise(Queue.take(promptQueue));
|
||||
if (item.type === "terminate") {
|
||||
return { done: true, value: undefined };
|
||||
}
|
||||
return { done: false, value: item };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
`sendTurn()` enqueues a user envelope, while `stopSession()` enqueues terminate and aborts.
|
||||
|
||||
#### 2.2.e Approval bridge with `canUseTool`
|
||||
|
||||
Map SDK approval checks to existing orchestration approval flows:
|
||||
|
||||
```ts
|
||||
const canUseTool = async (toolName: string, toolInput: Record<string, unknown>) => {
|
||||
if (approvalModeIsFullAccess(sessionId)) {
|
||||
return { behavior: "allow", updatedInput: toolInput };
|
||||
}
|
||||
|
||||
const requestId = ApprovalRequestId.makeUnsafe(crypto.randomUUID());
|
||||
emitRuntimeEvent({
|
||||
type: "approval.requested",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
requestId,
|
||||
requestKind: classifyTool(toolName),
|
||||
detail: summarizeToolRequest(toolName, toolInput),
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
|
||||
const decision = await waitForApprovalDecision(requestId);
|
||||
emitRuntimeEvent({
|
||||
type: "approval.resolved",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
requestId,
|
||||
decision,
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
|
||||
return decision === "accept" || decision === "acceptForSession"
|
||||
? { behavior: "allow", updatedInput: toolInput }
|
||||
: { behavior: "deny", message: "User declined tool execution." };
|
||||
};
|
||||
```
|
||||
|
||||
#### 2.2.f Hooks and checkpoint signals
|
||||
|
||||
If Claude hooks provide cleaner turn boundaries, convert them into canonical runtime events (`turn.completed` and optionally `checkpoint.captured`) so `CheckpointReactor` remains unchanged:
|
||||
|
||||
```ts
|
||||
hooks: {
|
||||
Stop: [
|
||||
{
|
||||
matcher: {},
|
||||
hooks: [
|
||||
async () => {
|
||||
emitRuntimeEvent({
|
||||
type: "checkpoint.captured",
|
||||
provider: "claudeCode",
|
||||
sessionId,
|
||||
threadId,
|
||||
turnId: activeTurnId,
|
||||
turnCount: nextTurnCount(),
|
||||
// ... eventId/createdAt
|
||||
});
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
#### 2.2.g Runtime control method wiring
|
||||
|
||||
Adapter should expose SDK controls through existing service methods and runtime payload updates:
|
||||
|
||||
1. `interruptTurn()` -> `result.interrupt()`
|
||||
2. Model override on send turn -> `result.setModel(model)` before enqueuing prompt
|
||||
3. Runtime mode changes -> `result.setPermissionMode(mode)` if we support live mode switching
|
||||
4. Thinking budget updates -> `result.setMaxThinkingTokens(tokens)` when configured
|
||||
|
||||
### 2.3 Canonical event mapping
|
||||
|
||||
Map Claude SDK events to `ProviderRuntimeEvent`:
|
||||
|
||||
1. `session.started` / `session.exited`
|
||||
2. `turn.started` / `turn.completed`
|
||||
3. `message.delta` / `message.completed`
|
||||
4. `tool.started` / `tool.completed`
|
||||
5. `approval.requested` / `approval.resolved`
|
||||
6. `runtime.error`
|
||||
|
||||
No provider-native event methods should leak beyond the adapter boundary.
|
||||
|
||||
Reference mapping table:
|
||||
|
||||
| Claude SDK message/callback | Canonical runtime event(s) | Notes |
|
||||
|---|---|---|
|
||||
| assistant partial text | `message.delta` | Emit deltas only (do not resend full content each chunk). |
|
||||
| assistant final message | `message.completed` | Must include stable `itemId` for dedupe/finalize behavior. |
|
||||
| result (success) | `turn.completed` (`status: "completed"`) | This is the main turn boundary for checkpointing. |
|
||||
| result (interrupted/cancelled) | `turn.completed` (`status: "interrupted"`/`"cancelled"`) | Preserve state semantics used by ingestion + UI. |
|
||||
| result (error) | `runtime.error` and `turn.completed` (`status: "failed"`) | Include concise error message. |
|
||||
| tool start | `tool.started` | Set `toolKind` using shared classifier (`command`, `file-change`, `other`). |
|
||||
| tool result | `tool.completed` | Include detail summary used by activity feed. |
|
||||
| canUseTool prompt | `approval.requested` | Source of request id shown in UI. |
|
||||
| approval decision returned | `approval.resolved` | Must correlate using same request id. |
|
||||
| session initialization | `session.started`, optional `thread.started` | Ensure `threadId` is emitted early and consistently. |
|
||||
| process exit/close | `session.exited` | Required for session status projection cleanup. |
|
||||
|
||||
### 2.4 Session/thread/resume identifiers
|
||||
|
||||
Define explicit adapter semantics:
|
||||
|
||||
1. `sessionId`: adapter-owned stable session id.
|
||||
2. `threadId`: Claude conversation/session identifier returned as `ProviderThreadId`.
|
||||
3. `resumeCursor`: provider-specific cursor (for example message id) needed for precise recovery/rollback.
|
||||
|
||||
### 2.5 Rollback/read strategy
|
||||
|
||||
Implement `readThread()` and `rollbackThread()` in a way compatible with `CheckpointReactor`.
|
||||
|
||||
Preferred:
|
||||
|
||||
1. Track per-turn resume cursors and reconstruct session state on rollback.
|
||||
2. Keep adapter `sessionId` stable across internal rehydration/restart.
|
||||
|
||||
Fallback (explicitly documented if chosen):
|
||||
|
||||
1. Filesystem revert succeeds even when conversation rewind is partial.
|
||||
2. Reactor behavior is updated to surface a clear warning activity instead of silent drift.
|
||||
|
||||
### 2.6 Adapter unit tests
|
||||
|
||||
Add tests mirroring Codex adapter coverage:
|
||||
|
||||
1. Provider validation (`provider === "claudeCode"`).
|
||||
2. Event mapping to canonical runtime events.
|
||||
3. Approval request lifecycle.
|
||||
4. Resume/recovery behavior.
|
||||
5. Rollback behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Register adapter in runtime composition
|
||||
|
||||
### 3.1 Adapter registry wiring
|
||||
|
||||
Update:
|
||||
|
||||
1. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
|
||||
|
||||
Register both Codex and Claude adapters.
|
||||
|
||||
### 3.2 Server layer composition
|
||||
|
||||
Update:
|
||||
|
||||
1. `apps/server/src/serverLayers.ts`
|
||||
|
||||
Provide `ClaudeCodeAdapterLive` alongside Codex in `makeServerProviderLayer()`.
|
||||
|
||||
### 3.3 Composition tests
|
||||
|
||||
Update integration tests to ensure:
|
||||
|
||||
1. Registry exposes Claude provider.
|
||||
2. Provider service can route Claude sessions.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Orchestration command/reactor updates
|
||||
|
||||
### 4.1 Decider propagation
|
||||
|
||||
Update `apps/server/src/orchestration/decider.ts`:
|
||||
|
||||
1. Carry optional `provider` from `thread.turn.start` command into `thread.turn-start-requested` event payload.
|
||||
|
||||
### 4.2 ProviderCommandReactor provider selection
|
||||
|
||||
Update `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`:
|
||||
|
||||
1. Prefer provider from turn-start event payload when starting a new session.
|
||||
2. Fallback to existing thread session provider when payload omitted.
|
||||
3. Fallback to default provider only when neither is present.
|
||||
|
||||
Switch behavior policy (explicit in implementation):
|
||||
|
||||
1. If active session provider differs from requested provider, stop and recreate session before sending turn.
|
||||
2. Keep current provider when request omits provider.
|
||||
|
||||
### 4.3 Reactor/invariant tests
|
||||
|
||||
Update/add tests in:
|
||||
|
||||
1. `apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts`
|
||||
2. `apps/server/src/orchestration/*.test.ts` as needed
|
||||
|
||||
Validate first-turn provider choice, provider switching semantics, and backward compatibility when provider is omitted.
|
||||
|
||||
---
|
||||
|
||||
## Phase 5: Web provider UX enablement
|
||||
|
||||
### 5.1 Enable Claude option
|
||||
|
||||
Update `apps/web/src/session-logic.ts`:
|
||||
|
||||
1. Mark Claude provider option as available.
|
||||
|
||||
### 5.2 Provider selection in composer
|
||||
|
||||
Update `apps/web/src/components/ChatView.tsx`:
|
||||
|
||||
1. Add provider picker near model/runtime controls.
|
||||
2. Include selected provider in `thread.turn.start` command payload.
|
||||
3. Keep selected provider sticky per thread in client state (or derive from active session provider when present).
|
||||
|
||||
### 5.3 Provider-aware model picker
|
||||
|
||||
Update model picker usage so model options reflect selected provider.
|
||||
|
||||
### 5.4 Web tests
|
||||
|
||||
Update/add tests for:
|
||||
|
||||
1. Provider picker interactions.
|
||||
2. Turn-start command includes provider.
|
||||
3. Model list switches by provider.
|
||||
|
||||
---
|
||||
|
||||
## Phase 6: Checkpoint and revert compatibility
|
||||
|
||||
### 6.1 Validate checkpoint reactor expectations
|
||||
|
||||
Exercise `apps/server/src/orchestration/Layers/CheckpointReactor.ts` flows with Claude:
|
||||
|
||||
1. Turn baseline capture.
|
||||
2. Turn completion checkpoint capture.
|
||||
3. Revert + provider rollback coordination.
|
||||
|
||||
### 6.2 Policy for partial rollback support
|
||||
|
||||
If Claude cannot support full conversation rewind at parity with Codex:
|
||||
|
||||
1. Document behavior clearly.
|
||||
2. Emit explicit thread activity for degraded rollback behavior.
|
||||
3. Ensure filesystem state remains correct and predictable.
|
||||
|
||||
### 6.3 Checkpoint tests
|
||||
|
||||
Add/update tests in checkpoint + provider service integration suites for Claude revert behavior.
|
||||
|
||||
---
|
||||
|
||||
## Phase 7: End-to-end hardening and observability
|
||||
|
||||
### 7.1 Integration tests
|
||||
|
||||
Add integration coverage for:
|
||||
|
||||
1. `thread.turn.start` with `provider: "claudeCode"` from fresh thread.
|
||||
2. Session recovery after restart (provider session alias/recovery path).
|
||||
3. Approval request/respond flow.
|
||||
4. Interrupt behavior.
|
||||
5. Revert flow with rollback.
|
||||
|
||||
### 7.2 WS behavior regression check
|
||||
|
||||
Ensure no contract regressions:
|
||||
|
||||
1. Client still consumes only `orchestration.domainEvent`.
|
||||
2. No new provider-specific WS channels introduced.
|
||||
|
||||
### 7.3 Logging
|
||||
|
||||
Confirm both native and canonical provider logs remain useful with multi-adapter setup:
|
||||
|
||||
1. `provider-native.ndjson`
|
||||
2. `provider-canonical.ndjson`
|
||||
|
||||
---
|
||||
|
||||
## File checklist
|
||||
|
||||
Likely files to touch:
|
||||
|
||||
1. `packages/contracts/src/model.ts`
|
||||
2. `packages/contracts/src/orchestration.ts`
|
||||
3. `packages/contracts/src/provider.ts`
|
||||
4. `apps/server/src/provider/Services/ClaudeCodeAdapter.ts` (new)
|
||||
5. `apps/server/src/provider/Layers/ClaudeCodeAdapter.ts` (new)
|
||||
6. `apps/server/src/provider/Layers/ProviderAdapterRegistry.ts`
|
||||
7. `apps/server/src/serverLayers.ts`
|
||||
8. `apps/server/src/orchestration/decider.ts`
|
||||
9. `apps/server/src/orchestration/Layers/ProviderCommandReactor.ts`
|
||||
10. `apps/web/src/session-logic.ts`
|
||||
11. `apps/web/src/components/ChatView.tsx`
|
||||
12. Related tests under `packages/contracts/src`, `apps/server/src/provider/Layers`, `apps/server/src/orchestration/Layers`, `apps/server/integration`, and `apps/web/src`.
|
||||
|
||||
---
|
||||
|
||||
## Delivery order
|
||||
|
||||
1. Contracts for provider selection + models.
|
||||
2. Claude adapter + unit tests.
|
||||
3. Registry/layer wiring.
|
||||
4. Reactor updates for provider-aware session start.
|
||||
5. Web provider picker + provider-aware models.
|
||||
6. Checkpoint/revert compatibility.
|
||||
7. End-to-end integration tests and stabilization.
|
||||
|
||||
This order keeps risk isolated and maintains a working orchestrated path at each stage.
|
||||
@@ -1,64 +0,0 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const FAVICON_CANDIDATES = [
|
||||
"favicon.svg", "favicon.ico", "favicon.png",
|
||||
"public/favicon.svg", "public/favicon.ico", "public/favicon.png",
|
||||
"app/favicon.ico", "app/favicon.png", "app/icon.svg", "app/icon.png", "app/icon.ico",
|
||||
"src/favicon.ico", "src/favicon.svg", "src/app/favicon.ico", "src/app/icon.svg", "src/app/icon.png",
|
||||
];
|
||||
|
||||
const ICON_SOURCE_FILES = [
|
||||
"index.html", "public/index.html",
|
||||
"app/routes/__root.tsx", "src/routes/__root.tsx",
|
||||
"app/root.tsx", "src/root.tsx", "src/index.html",
|
||||
];
|
||||
|
||||
const LINK_ICON_HTML_RE = /<link[^>]*rel=["'](?:icon|shortcut icon)["'][^>]*href=["']([^"'?]+)/i;
|
||||
const LINK_ICON_OBJ_RE = /rel:\s*["'](?:icon|shortcut icon)["'][^}]*href:\s*["']([^"'?]+)/i;
|
||||
|
||||
function test(projectCwd) {
|
||||
console.log("--- Testing:", projectCwd, "---");
|
||||
|
||||
for (const c of FAVICON_CANDIDATES) {
|
||||
const full = path.join(projectCwd, c);
|
||||
if (fs.existsSync(full) && fs.statSync(full).isFile()) {
|
||||
console.log(" Phase 1 FOUND:", c);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 1: no match");
|
||||
|
||||
for (const sf of ICON_SOURCE_FILES) {
|
||||
const full = path.join(projectCwd, sf);
|
||||
if (!fs.existsSync(full)) continue;
|
||||
const content = fs.readFileSync(full, "utf8");
|
||||
const href = content.match(LINK_ICON_HTML_RE)?.[1] || content.match(LINK_ICON_OBJ_RE)?.[1];
|
||||
if (href) {
|
||||
const clean = href.replace(/^\//, "");
|
||||
const tryPaths = [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
|
||||
for (const p of tryPaths) {
|
||||
if (fs.existsSync(p)) {
|
||||
console.log(" Phase 2 FOUND:", sf, "->", href, "->", p);
|
||||
return;
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2 href found but file missing:", href);
|
||||
}
|
||||
}
|
||||
console.log(" Phase 2: no match");
|
||||
}
|
||||
|
||||
function getTestPaths() {
|
||||
const cliPaths = process.argv.slice(2).map((p) => p.trim()).filter(Boolean);
|
||||
if (cliPaths.length > 0) return cliPaths;
|
||||
|
||||
const envPaths = process.env.TEST_PATHS?.split(path.delimiter).map((p) => p.trim()).filter(Boolean);
|
||||
if (envPaths?.length) return envPaths;
|
||||
|
||||
return [process.cwd()];
|
||||
}
|
||||
|
||||
for (const p of getTestPaths()) {
|
||||
test(path.resolve(p));
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
# CLAUDE.md
|
||||
# AGENTS.md
|
||||
|
||||
## Task Completion Requirements
|
||||
|
||||
- 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
|
||||
|
||||
@@ -18,11 +19,16 @@ This repository is a VERY EARLY WIP. Proposing sweeping changes that improve lon
|
||||
|
||||
If a tradeoff is required, choose correctness and robustness over short-term convenience.
|
||||
|
||||
## Maintainability
|
||||
|
||||
Long term maintainability is a core priority. If you add new functionality, first check if there are shared logic that can be extracted to a separate module. Duplicate logic across mulitple files is a code smell and should be avoided. Don't be afraid to change existing code. Don't take shortcuts by just adding local logic to solve a problem.
|
||||
|
||||
## Package Roles
|
||||
|
||||
- `apps/server`: Node.js WebSocket server. Wraps Codex app-server (JSON-RPC over stdio), serves the React web app, and manages provider sessions.
|
||||
- `apps/web`: React/Vite UI. Owns session UX, conversation/event rendering, and client-side state. Connects to the server via WebSocket.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
- `packages/contracts`: Shared effect/Schema schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types. Keep this package schema-only — no runtime logic.
|
||||
- `packages/shared`: Shared runtime utilities consumed by both server and web. Uses explicit subpath exports (e.g. `@t3tools/shared/git`) — no barrel index.
|
||||
|
||||
## Codex App Server (Important)
|
||||
|
||||
@@ -45,7 +51,3 @@ Docs:
|
||||
- Codex-Monitor (Tauri, feature-complete, strong reference implementation): https://github.com/Dimillian/CodexMonitor
|
||||
|
||||
Use these as implementation references when designing protocol handling, UX flows, and operational safeguards.
|
||||
|
||||
## Dummy Change
|
||||
|
||||
- This line is a no-op dummy edit.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 T3 Tools Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -2,135 +2,23 @@
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents. Currently Codex-first, with Claude Code support coming soon.
|
||||
|
||||
Run `npx t3` in any project directory to launch the web interface.
|
||||
Run `bun run dev:desktop` to launch the Electron desktop app in this monorepo.
|
||||
## How to use
|
||||
|
||||
## Architecture
|
||||
|
||||
T3 Code runs as a **Node.js WebSocket server** that wraps `codex app-server` (JSON-RPC over stdio) and serves a React web app.
|
||||
|
||||
```
|
||||
┌─────────────────────────────────┐
|
||||
│ Browser (React + Vite) │
|
||||
│ Connected via WebSocket │
|
||||
└──────────┬──────────────────────┘
|
||||
│ ws://localhost:3773
|
||||
┌──────────▼──────────────────────┐
|
||||
│ apps/server (Node.js) │
|
||||
│ WebSocket + HTTP static server │
|
||||
│ ProviderManager │
|
||||
│ CodexAppServerManager │
|
||||
└──────────┬──────────────────────┘
|
||||
│ JSON-RPC over stdio
|
||||
┌──────────▼──────────────────────┐
|
||||
│ codex app-server │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
## Workspace layout
|
||||
|
||||
- `/apps/server`: Node.js WebSocket server. Wraps Codex app-server, serves the built web app, and opens the browser on start.
|
||||
- `/apps/web`: React + Vite UI. Session control, conversation, and provider event rendering. Connects to the server via WebSocket.
|
||||
- `/apps/desktop`: Electron shell. Spawns a desktop-scoped `t3` backend process and loads the shared web app.
|
||||
- `/packages/contracts`: Shared Zod schemas and TypeScript contracts for provider events, WebSocket protocol, and model/session types.
|
||||
|
||||
## Codex prerequisites
|
||||
|
||||
- Install Codex CLI so `codex` is on your PATH.
|
||||
- Authenticate Codex before running T3 Code (for example via API key or ChatGPT auth supported by Codex).
|
||||
- T3 Code starts the server via `codex app-server` per session.
|
||||
|
||||
## Quick start
|
||||
> [!WARNING]
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
|
||||
```bash
|
||||
# Development (with hot reload)
|
||||
bun run dev
|
||||
|
||||
# Desktop development
|
||||
bun run dev:desktop
|
||||
|
||||
# Desktop development on an isolated port set
|
||||
T3CODE_DEV_INSTANCE=feature-xyz bun run dev:desktop
|
||||
|
||||
# Production
|
||||
bun run build
|
||||
bun run start
|
||||
|
||||
# Build a shareable macOS .dmg (arm64 by default)
|
||||
bun run dist:desktop:dmg
|
||||
|
||||
# Or from any project directory after publishing:
|
||||
npx t3
|
||||
npx t3@alpha
|
||||
```
|
||||
|
||||
## Scripts
|
||||
Use can also just install the desktop app (it's cooler).
|
||||
|
||||
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
|
||||
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
|
||||
- `bun run dev:web` — Starts just the Vite dev server for the web app.
|
||||
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
|
||||
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
|
||||
`bun run dev -- --state-dir ~/.t3/another-dev-state`
|
||||
- `bun run 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.
|
||||
- `bun run test` — Runs workspace tests.
|
||||
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
|
||||
- `bun run dist:desktop:dmg` — Builds a shareable macOS `.dmg` into `./release`.
|
||||
- `bun run dist:desktop:dmg:x64` — Builds an Intel macOS `.dmg`.
|
||||
- `bun run dist:desktop:linux` — Builds a Linux AppImage into `./release`.
|
||||
- `bun run dist:desktop:win` — Builds a Windows NSIS installer into `./release`.
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
|
||||
### Desktop `.dmg` packaging notes
|
||||
## Some notes
|
||||
|
||||
- Default build is unsigned/not notarized for local sharing.
|
||||
- The DMG build uses `assets/macos-icon-1024.png` as the production app icon source.
|
||||
- Desktop production windows load the bundled UI from `t3://app/index.html` (not a `127.0.0.1` document URL).
|
||||
- Desktop packaging includes `apps/server/dist` (the `t3` backend) and starts it on loopback with an auth token for WebSocket/API traffic.
|
||||
- Your tester can still open it on macOS by right-clicking the app and choosing **Open** on first launch.
|
||||
- To keep staging files for debugging package contents, run: `bun run dist:desktop:dmg -- --keep-stage`
|
||||
- To allow code-signing/notarization when configured in CI/secrets, add: `--signed`.
|
||||
- Windows `--signed` uses Azure Trusted Signing and expects:
|
||||
`AZURE_TRUSTED_SIGNING_ENDPOINT`, `AZURE_TRUSTED_SIGNING_ACCOUNT_NAME`,
|
||||
`AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME`, and `AZURE_TRUSTED_SIGNING_PUBLISHER_NAME`.
|
||||
- Azure authentication env vars are also required (for example service principal with secret):
|
||||
`AZURE_TENANT_ID`, `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`.
|
||||
We are very very early in this project. Expect bugs.
|
||||
|
||||
### Running multiple dev instances
|
||||
We are not accepting contributions yet.
|
||||
|
||||
Set `T3CODE_DEV_INSTANCE` to any value to deterministically shift all dev ports together.
|
||||
|
||||
- Default ports: server `3773`, web `5733`
|
||||
- Shifted ports: `base + offset` (offset is hashed from `T3CODE_DEV_INSTANCE`)
|
||||
- Example: `T3CODE_DEV_INSTANCE=branch-a bun run dev:desktop`
|
||||
|
||||
If you want full control instead of hashing, set `T3CODE_PORT_OFFSET` to a numeric offset.
|
||||
|
||||
## Runtime modes
|
||||
|
||||
T3 Code has a global runtime mode switch in the chat toolbar:
|
||||
|
||||
- **Full access** (default): starts sessions with `approvalPolicy: never` and `sandboxMode: danger-full-access`.
|
||||
- **Supervised**: starts sessions with `approvalPolicy: on-request` and `sandboxMode: workspace-write`, then prompts in-app for command/file approvals.
|
||||
|
||||
## Provider architecture
|
||||
|
||||
The web app communicates with the server via WebSocket using a simple JSON-RPC-style protocol:
|
||||
|
||||
- **Request/Response**: `{ id, method, params }` → `{ id, result }` or `{ id, error }`
|
||||
- **Push events**: `{ type: "push", channel, data }` for orchestration read-model updates
|
||||
|
||||
Methods mirror the `NativeApi` interface defined in `@t3tools/contracts`:
|
||||
|
||||
- `providers.startSession`, `providers.sendTurn`, `providers.interruptTurn`
|
||||
- `providers.respondToRequest`, `providers.stopSession`
|
||||
- `shell.openInEditor`, `server.getConfig`
|
||||
|
||||
Codex is the only implemented provider. `claudeCode` is reserved in contracts/UI.
|
||||
|
||||
## CI quality gates
|
||||
|
||||
- `.github/workflows/ci.yml` runs `bun run lint`, `bun run typecheck`, and `bun run test` on pull requests and pushes to `main`.
|
||||
- `.github/workflows/release.yml` builds macOS (`arm64` and `x64`), Linux (`x64`), and Windows (`x64`) desktop artifacts from a single `v*.*.*` tag and publishes one GitHub release.
|
||||
- The release workflow auto-enables signing only when secrets are present: Apple credentials for macOS and Azure Trusted Signing credentials for Windows. Without secrets, it still releases unsigned artifacts.
|
||||
- See `docs/release.md` for full release/signing setup checklist.
|
||||
Discord link coming soon.
|
||||
@@ -1,582 +0,0 @@
|
||||
# Orchestration Interface Spec (Required State)
|
||||
|
||||
Status: Required target architecture (not a description of current behavior).
|
||||
|
||||
## 1. Identifier Schema (Branded)
|
||||
|
||||
All identifiers are branded and never plain `string` in schema definitions.
|
||||
|
||||
```ts
|
||||
const ThreadId = Schema.String.pipe(Schema.brand("ThreadId"));
|
||||
const ProjectId = Schema.String.pipe(Schema.brand("ProjectId"));
|
||||
const CommandId = Schema.String.pipe(Schema.brand("CommandId"));
|
||||
const EventId = Schema.String.pipe(Schema.brand("EventId"));
|
||||
const MessageId = Schema.String.pipe(Schema.brand("MessageId"));
|
||||
const TurnId = Schema.String.pipe(Schema.brand("TurnId"));
|
||||
|
||||
const ProviderSessionId = Schema.String.pipe(Schema.brand("ProviderSessionId"));
|
||||
const ProviderThreadId = Schema.String.pipe(Schema.brand("ProviderThreadId"));
|
||||
const ProviderTurnId = Schema.String.pipe(Schema.brand("ProviderTurnId"));
|
||||
const ProviderItemId = Schema.String.pipe(Schema.brand("ProviderItemId"));
|
||||
const ApprovalRequestId = Schema.String.pipe(Schema.brand("ApprovalRequestId"));
|
||||
|
||||
const CheckpointRef = Schema.String.pipe(Schema.brand("CheckpointRef"));
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `ThreadId` is app/orchestration thread identity.
|
||||
- `ProviderThreadId` is provider runtime thread identity.
|
||||
- They are never assigned to each other.
|
||||
- `ProviderSessionId` is internal server/provider routing identity; clients do not send it.
|
||||
- use e.g. `ThreadId.make(randomUUID())` to create new entity ids at the source (e.g. client create thread id and send to server, provider adapter creates the provider thread id from the codex app server etc)
|
||||
|
||||
## 2. Client Commands (Domain Commands)
|
||||
|
||||
All commands are sent through one RPC: `orchestration.dispatchCommand`.
|
||||
|
||||
Output for every command: `DispatchResultSchema = { sequence: number }`.
|
||||
|
||||
### 2.1 Client-Dispatchable Commands
|
||||
|
||||
1. `project.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel?: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
2. `project.meta.update`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `projectId: ProjectId`
|
||||
- optional `{ title, workspaceRoot, defaultModel, scripts }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `project.delete`
|
||||
|
||||
- Input: `commandId`, `projectId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
4. `thread.create`
|
||||
|
||||
- Input:
|
||||
- `commandId: CommandId`
|
||||
- `threadId: ThreadId`
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
5. `thread.delete`
|
||||
|
||||
- Input: `commandId`, `threadId`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
6. `thread.meta.update`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `{ title, model, branch, worktreePath }`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
7. `thread.turn.start`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `message`:
|
||||
- `messageId: MessageId`
|
||||
- `role: "user"`
|
||||
- `text: string`
|
||||
- `attachments: ChatAttachment[]` (schema-shared)
|
||||
- `model?: string`
|
||||
- `effort?: string`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
8. `thread.turn.interrupt`
|
||||
|
||||
- Input: `commandId`, `threadId`, optional `turnId: TurnId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
9. `thread.approval.respond`
|
||||
|
||||
- Input:
|
||||
- `commandId`
|
||||
- `threadId`
|
||||
- `requestId: ApprovalRequestId`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel"`
|
||||
- `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
10. `thread.checkpoint.revert`
|
||||
|
||||
- Input: `commandId`, `threadId`, `turnCount: number`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
11. `thread.session.stop`
|
||||
|
||||
- Input: `commandId`, `threadId`, `createdAt`
|
||||
- Output: `DispatchResult`
|
||||
|
||||
### 2.2 Internal-Only Commands (Not Client Dispatchable)
|
||||
|
||||
1. `thread.session.set`
|
||||
|
||||
- Server-owned projection update for session lifecycle.
|
||||
|
||||
2. `thread.message.assistant.delta`
|
||||
|
||||
- Server-owned incremental assistant content append.
|
||||
|
||||
3. `thread.message.assistant.complete`
|
||||
|
||||
- Server-owned assistant message completion marker.
|
||||
|
||||
4. `thread.turn.diff.complete`
|
||||
|
||||
- Server-owned checkpoint diff summary write.
|
||||
|
||||
5. `thread.activity.append`
|
||||
|
||||
- Server-owned activity feed append.
|
||||
|
||||
## 3. Client RPC (Required)
|
||||
|
||||
These are the required client-facing RPC methods.
|
||||
|
||||
1. `orchestration.getSnapshot`
|
||||
|
||||
- Input: `{}`
|
||||
- Output: `OrchestrationReadModel`
|
||||
|
||||
2. `orchestration.dispatchCommand`
|
||||
|
||||
- Input: `ClientOrchestrationCommand` (`Schema.Union` of all client-dispatchable commands)
|
||||
- Output: `DispatchResult`
|
||||
|
||||
3. `orchestration.getTurnDiff`
|
||||
|
||||
- Input:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- Output:
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
|
||||
4. `orchestration.replayEvents` (optional operational/debug API)
|
||||
|
||||
- Input: `{ fromSequenceExclusive: number }`
|
||||
- Output: `OrchestrationEvent[]`
|
||||
|
||||
### 3.1 RPC To Remove
|
||||
|
||||
Remove from client boundary:
|
||||
|
||||
- `providers.startSession`
|
||||
- `providers.sendTurn`
|
||||
- `providers.interruptTurn`
|
||||
- `providers.respondToRequest`
|
||||
- `providers.stopSession`
|
||||
- `providers.listCheckpoints`
|
||||
- `providers.getCheckpointDiff`
|
||||
- `providers.revertToCheckpoint`
|
||||
|
||||
Rationale:
|
||||
|
||||
- Session/turn/checkpoint control belongs to orchestrator command path.
|
||||
- Snapshot already includes checkpoint summaries (`checkpoints`); only full textual diff needs explicit query RPC.
|
||||
|
||||
## 4. Server Orchestrator Command <-> Event Schemas
|
||||
|
||||
Each command deterministically yields one or more domain events that are persisted to the event store.
|
||||
|
||||
1. `project.create` -> `project.created`
|
||||
2. `project.meta.update` -> `project.meta-updated`
|
||||
3. `project.delete` -> `project.deleted`
|
||||
4. `thread.create` -> `thread.created`
|
||||
5. `thread.delete` -> `thread.deleted`
|
||||
6. `thread.meta.update` -> `thread.meta-updated`
|
||||
7. `thread.turn.start` ->
|
||||
|
||||
- `thread.message-sent` (user message append)
|
||||
- `thread.turn-start-requested`
|
||||
- then (async side effect success) `thread.session-set` + provider-driven message/turn events
|
||||
|
||||
8. `thread.turn.interrupt` -> `thread.turn-interrupt-requested`
|
||||
9. `thread.approval.respond` -> `thread.approval-response-requested`
|
||||
10. `thread.checkpoint.revert` -> `thread.checkpoint-revert-requested` then `thread.reverted`
|
||||
11. `thread.session.stop` -> `thread.session-stop-requested` then `thread.session-set`
|
||||
|
||||
Internal command/event path:
|
||||
|
||||
- `thread.session.set` -> `thread.session-set`
|
||||
- `thread.message.assistant.delta` -> `thread.message-sent` (assistant streaming)
|
||||
- `thread.message.assistant.complete` -> `thread.message-sent` (streaming false)
|
||||
- `thread.turn.diff.complete` -> `thread.turn-diff-completed`
|
||||
- `thread.activity.append` -> `thread.activity-appended`
|
||||
|
||||
## 5. Orchestration Events <-> Generic Provider Events <-> Raw Provider Events
|
||||
|
||||
Required mapping pipeline:
|
||||
|
||||
`Raw Provider Event (adapter-specific)`
|
||||
-> `GenericProviderRuntimeEvent` (provider-agnostic schema)
|
||||
-> `Internal Orchestration Command`
|
||||
-> `Orchestration Domain Event`
|
||||
|
||||
### 5.1 Mapping Table for Codex Adapter
|
||||
|
||||
1. Raw `thread/started`
|
||||
|
||||
- Generic: `thread.started`
|
||||
- Internal command: `thread.session.set` (attach `ProviderThreadId`, status `ready|running`)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
2. Raw `turn/started`
|
||||
|
||||
- Generic: `turn.started`
|
||||
- Internal command: `thread.session.set` (status `running`, active turn)
|
||||
- Domain event: `thread.session-set`
|
||||
|
||||
3. Raw `item/agentMessage/delta`
|
||||
|
||||
- Generic: `message.delta`
|
||||
- Internal command: `thread.message.assistant.delta`
|
||||
- Domain event: `thread.message-sent` (assistant, streaming)
|
||||
|
||||
4. Raw `item/completed` (agent message)
|
||||
|
||||
- Generic: `message.completed`
|
||||
- Internal command: `thread.message.assistant.complete`
|
||||
- Domain event: `thread.message-sent` (assistant, completed)
|
||||
|
||||
5. Raw `turn/completed`
|
||||
|
||||
- Generic: `turn.completed`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (ready/error)
|
||||
- `thread.activity.append` (optional summary)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
6. Raw approval request
|
||||
|
||||
- Generic: `approval.requested`
|
||||
- Internal command: `thread.activity.append` (typed `requestId`, `requestKind`)
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
7. Raw approval decision ack
|
||||
|
||||
- Generic: `approval.resolved`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
8. Raw tool start/complete
|
||||
|
||||
- Generic: `tool.started` / `tool.completed`
|
||||
- Internal command: `thread.activity.append`
|
||||
- Domain event: `thread.activity-appended`
|
||||
|
||||
9. Checkpoint capture (server-produced)
|
||||
|
||||
- Generic: `checkpoint.captured`
|
||||
- Internal command: `thread.turn.diff.complete`
|
||||
- Domain event: `thread.turn-diff-completed`
|
||||
|
||||
10. Raw/runtime error
|
||||
|
||||
- Generic: `runtime.error`
|
||||
- Internal commands:
|
||||
- `thread.session.set` (status `error`)
|
||||
- `thread.activity.append` (`tone=error`)
|
||||
- Domain events: `thread.session-set`, `thread.activity-appended`
|
||||
|
||||
## 6. Schema Section (Boundary + Reuse)
|
||||
|
||||
### 6.1 Shared Schemas (contracts package)
|
||||
|
||||
Expose to both web and server:
|
||||
|
||||
- `OrchestrationReadModelSchema`
|
||||
- `ClientOrchestrationCommandSchema`
|
||||
- `OrchestrationEventSchema`
|
||||
- `OrchestrationRpcSchemas` (`getSnapshot`, `dispatchCommand`, `getTurnDiff`, optional replay)
|
||||
- `GenericProviderRuntimeEventSchema` (used for diagnostics/ingestion tests)
|
||||
- Shared message/activity/checkpoint summary schemas used in snapshot
|
||||
|
||||
### 6.2 Server-Internal Schemas
|
||||
|
||||
Not exposed to web:
|
||||
|
||||
- `InternalOrchestrationCommandSchema`
|
||||
- Adapter raw-event schemas and provider-specific payload schemas
|
||||
- Provider session directory records and persistence-only row schemas
|
||||
- Git service cache/query schemas (non-orchestration read model)
|
||||
|
||||
### 6.3 Reuse Requirements
|
||||
|
||||
- Snapshot checkpoint summary schema is source of truth for checkpoint list UI.
|
||||
- `getTurnDiff` response reuses `ThreadId`/turn count brands and textual `diff` only.
|
||||
- Activity schemas are reused for approval/tool/runtime annotations; no separate UI-only structure.
|
||||
- Session schema must include both `threadId: ThreadId` and optional `providerThreadId: ProviderThreadId` (explicitly distinct).
|
||||
|
||||
## 7. Persistence Model (Required)
|
||||
|
||||
This section defines required persisted tables, the canonical persisted event envelope, and required projected/read tables.
|
||||
|
||||
### 7.1 Write-Side Persisted Tables
|
||||
|
||||
1. `orchestration_events` (append-only event store)
|
||||
|
||||
- `sequence: number` (global monotonic sequence, primary key)
|
||||
- `eventId: EventId` (unique)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `streamId: ProjectId | ThreadId` (aggregate stream id)
|
||||
- `streamVersion: number` (per-aggregate monotonic version)
|
||||
- `eventType: OrchestrationEventType`
|
||||
- `occurredAt: IsoDateTime`
|
||||
- `commandId: CommandId | null`
|
||||
- `causationEventId: EventId | null`
|
||||
- `correlationId: CommandId | null`
|
||||
- `actorKind: "client" | "server" | "provider"`
|
||||
- `payload: OrchestrationEventPayload` (type-validated by `eventType`)
|
||||
- `metadata: OrchestrationEventMetadata`
|
||||
|
||||
2. `orchestration_command_receipts` (idempotency + ack replay)
|
||||
|
||||
- `commandId: CommandId` (primary key)
|
||||
- `aggregateKind: "project" | "thread"`
|
||||
- `aggregateId: ProjectId | ThreadId`
|
||||
- `acceptedAt: IsoDateTime`
|
||||
- `resultSequence: number`
|
||||
- `status: "accepted" | "rejected"`
|
||||
- `error: string | null`
|
||||
|
||||
3. `checkpoint_diff_blobs` (large plaintext diffs; separate from summaries)
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `fromTurnCount: number`
|
||||
- `toTurnCount: number`
|
||||
- `diff: string`
|
||||
- `createdAt: IsoDateTime`
|
||||
- unique key: `(threadId, fromTurnCount, toTurnCount)`
|
||||
|
||||
4. `provider_session_runtime` (server-internal adapter resume state)
|
||||
|
||||
- `providerSessionId: ProviderSessionId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `providerName: string`
|
||||
- `adapterKey: string`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `status: "starting" | "running" | "stopped" | "error"`
|
||||
- `lastSeenAt: IsoDateTime`
|
||||
- `resumeCursor: JsonValue | null` (adapter-specific opaque state)
|
||||
- `runtimePayload: JsonValue | null` (adapter-specific opaque state)
|
||||
|
||||
### 7.2 Canonical Persisted Event Schema
|
||||
|
||||
`OrchestrationPersistedEventSchema` (full envelope):
|
||||
|
||||
```ts
|
||||
type OrchestrationPersistedEvent = {
|
||||
sequence: number;
|
||||
eventId: EventId;
|
||||
aggregateKind: "project" | "thread";
|
||||
streamId: ProjectId | ThreadId;
|
||||
streamVersion: number;
|
||||
eventType: OrchestrationEventType;
|
||||
occurredAt: IsoDateTime;
|
||||
commandId: CommandId | null;
|
||||
causationEventId: EventId | null;
|
||||
correlationId: CommandId | null;
|
||||
actorKind: "client" | "server" | "provider";
|
||||
payload: OrchestrationEventPayload;
|
||||
metadata: {
|
||||
providerSessionId?: ProviderSessionId;
|
||||
providerThreadId?: ProviderThreadId;
|
||||
providerTurnId?: ProviderTurnId;
|
||||
providerItemId?: ProviderItemId;
|
||||
adapterKey?: string;
|
||||
requestId?: ApprovalRequestId;
|
||||
ingestedAt?: IsoDateTime;
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `payload` must be schema-discriminated by `eventType`.
|
||||
- provider identifiers only appear in `metadata` and provider-specific payload sub-shapes; they do not replace `ThreadId`.
|
||||
- `streamVersion` is concurrency guard for aggregate writes.
|
||||
|
||||
### 7.3 Required Projected Tables (Read Models)
|
||||
|
||||
1. `projection_projects`
|
||||
|
||||
- `projectId: ProjectId` (primary key)
|
||||
- `title: string`
|
||||
- `workspaceRoot: string`
|
||||
- `defaultModel: string | null`
|
||||
- `scripts: ProjectScript[]`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
2. `projection_threads`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `projectId: ProjectId`
|
||||
- `title: string`
|
||||
- `model: string`
|
||||
- `branch: string | null`
|
||||
- `worktreePath: string | null`
|
||||
- `latestTurnId: TurnId | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
- `deletedAt: IsoDateTime | null`
|
||||
|
||||
3. `projection_thread_messages`
|
||||
|
||||
- `messageId: MessageId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `role: "user" | "assistant" | "system"`
|
||||
- `text: string`
|
||||
- `isStreaming: boolean`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
4. `projection_thread_activities`
|
||||
|
||||
- `activityId: EventId` (primary key; derived from source event)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `tone: "info" | "tool" | "approval" | "error"`
|
||||
- `kind: string`
|
||||
- `summary: string`
|
||||
- `payload: JsonValue`
|
||||
- `createdAt: IsoDateTime`
|
||||
|
||||
5. `projection_thread_sessions`
|
||||
|
||||
- `threadId: ThreadId` (primary key)
|
||||
- `status: "idle" | "starting" | "running" | "ready" | "interrupted" | "stopped" | "error"`
|
||||
- `providerName: string | null`
|
||||
- `providerSessionId: ProviderSessionId | null`
|
||||
- `providerThreadId: ProviderThreadId | null`
|
||||
- `activeTurnId: TurnId | null`
|
||||
- `lastError: string | null`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
6. `projection_thread_turns`
|
||||
|
||||
- `turnId: TurnId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnCount: number`
|
||||
- `status: "running" | "completed" | "interrupted" | "error"`
|
||||
- `userMessageId: MessageId | null`
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `startedAt: IsoDateTime`
|
||||
- `completedAt: IsoDateTime | null`
|
||||
|
||||
7. `projection_checkpoints`
|
||||
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId`
|
||||
- `checkpointTurnCount: number`
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `status: "ready" | "missing" | "error"`
|
||||
- `files: JsonArray` (typed as file diff summary schema)
|
||||
- `assistantMessageId: MessageId | null`
|
||||
- `completedAt: IsoDateTime`
|
||||
- unique key: `(threadId, checkpointTurnCount)`
|
||||
|
||||
8. `projection_pending_approvals`
|
||||
|
||||
- `requestId: ApprovalRequestId` (primary key)
|
||||
- `threadId: ThreadId`
|
||||
- `turnId: TurnId | null`
|
||||
- `status: "pending" | "resolved"`
|
||||
- `decision: "accept" | "acceptForSession" | "decline" | "cancel" | null`
|
||||
- `createdAt: IsoDateTime`
|
||||
- `resolvedAt: IsoDateTime | null`
|
||||
|
||||
9. `projection_state`
|
||||
|
||||
- `projector: string` (primary key; e.g. `threads`, `messages`, `sessions`)
|
||||
- `lastAppliedSequence: number`
|
||||
- `updatedAt: IsoDateTime`
|
||||
|
||||
Projection consistency rules:
|
||||
|
||||
- Every projector applies read-model row updates and `projection_state.lastAppliedSequence` in the same database transaction.
|
||||
- Optional debug field on projection rows: `lastEventSequence: number` (not required for correctness).
|
||||
|
||||
### 7.4 Snapshot and RPC Requirements
|
||||
|
||||
1. `orchestration.getSnapshot` is fully served from projection tables and returns `snapshotSequence: number`.
|
||||
2. Snapshot must include `projects[]` from `projection_projects`.
|
||||
3. Thread snapshot must include `checkpoints[]` from `projection_checkpoints`:
|
||||
|
||||
- `turnId: TurnId`
|
||||
- `completedAt: IsoDateTime`
|
||||
- `status`
|
||||
- `files[]` (`path`, `kind`, `additions`, `deletions`)
|
||||
- `checkpointRef: CheckpointRef`
|
||||
- `assistantMessageId?: MessageId`
|
||||
- `checkpointTurnCount: number`
|
||||
|
||||
4. Client does not require `listCheckpoints` RPC:
|
||||
|
||||
- checkpoint list comes from snapshot projections
|
||||
- full diff text comes from `orchestration.getTurnDiff` backed by `checkpoint_diff_blobs`
|
||||
|
||||
5. Provider session identity is not a client routing key:
|
||||
|
||||
- client acts on `ThreadId`
|
||||
- server resolves provider session internally via `projection_thread_sessions`
|
||||
|
||||
6. `snapshotSequence` is derived from `projection_state`:
|
||||
|
||||
- if snapshot depends on multiple projectors, use the minimum `lastAppliedSequence` across those projectors.
|
||||
|
||||
7. Event subscription handoff contract:
|
||||
|
||||
- client performs `getSnapshot` and reads `snapshotSequence`
|
||||
- client subscribes/replays with `fromSequenceExclusive = snapshotSequence`
|
||||
- server guarantees no gap between snapshot visibility and subsequent event stream from that sequence.
|
||||
|
||||
### 7.5 External Derived State (Non-Orchestration)
|
||||
|
||||
1. Current git/worktree state is not projected from orchestration events.
|
||||
2. If persisted, it belongs in a separate git cache/read model (for example `git_state_cache`) owned by a git service.
|
||||
3. Orchestration may embed git metadata only when captured as a domain fact (for example checkpoint metadata at turn completion).
|
||||
4. Any RPC for current git status should be outside orchestration RPC (for example `git.getThreadState`).
|
||||
|
||||
### 7.6 Existing Repository Placement
|
||||
|
||||
1. `ProjectsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_projects` plus orchestration command dispatch for writes.
|
||||
- Must not bypass command->event append path for mutations.
|
||||
|
||||
2. `CheckpointsRepository`
|
||||
|
||||
- Fits as projection/query access on top of `projection_checkpoints` plus `checkpoint_diff_blobs` (or git-service on-demand diff implementation).
|
||||
- Represents the same concept as prior `turn_diff_summary`; canonical naming is `checkpoint`.
|
||||
- Must not be an independent source of truth outside orchestration events.
|
||||
|
||||
3. `ProviderSessionsRepository`
|
||||
|
||||
- Fits as server-internal runtime persistence on top of `provider_session_runtime`, with domain-visible state projected into `projection_thread_sessions`.
|
||||
- Not part of client RPC/domain aggregate boundary.
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
@@ -14,15 +14,17 @@
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"electron": "40.6.0"
|
||||
"effect": "catalog:",
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@types/node": "^24.10.13",
|
||||
"electronmon": "^2.0.2",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:",
|
||||
"wait-on": "^8.0.2"
|
||||
},
|
||||
"productName": "T3 Code (Alpha)"
|
||||
|
||||
@@ -1,43 +1,171 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
|
||||
import electronmon from "electronmon";
|
||||
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";
|
||||
|
||||
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/index.mjs"];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
const restartDebounceMs = 120;
|
||||
const childTreeGracePeriodMs = 1_200;
|
||||
|
||||
await waitOn({
|
||||
resources: [
|
||||
`tcp:${port}`,
|
||||
"file:dist-electron/main.js",
|
||||
"file:dist-electron/preload.js",
|
||||
"file:../server/dist/index.mjs",
|
||||
],
|
||||
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
|
||||
});
|
||||
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const monitor = await electronmon({
|
||||
cwd: desktopDir,
|
||||
args: ["dist-electron/main.js"],
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
electronPath: resolveElectronPath(),
|
||||
});
|
||||
|
||||
let shuttingDown = false;
|
||||
let restartTimer = null;
|
||||
let currentApp = null;
|
||||
let restartQueue = Promise.resolve();
|
||||
const expectedExits = new WeakSet();
|
||||
const watchers = [];
|
||||
|
||||
function killChildTreeByPid(pid, signal) {
|
||||
if (process.platform === "win32" || typeof pid !== "number") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function cleanupStaleDevApps() {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
spawnSync("pkill", ["-f", "--", `--t3code-dev-root=${desktopDir}`], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
function startApp() {
|
||||
if (shuttingDown || currentApp !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: {
|
||||
...childEnv,
|
||||
VITE_DEV_SERVER_URL: devServerUrl,
|
||||
},
|
||||
stdio: "inherit",
|
||||
},
|
||||
);
|
||||
|
||||
currentApp = app;
|
||||
|
||||
app.once("error", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
|
||||
app.once("exit", () => {
|
||||
if (currentApp === app) {
|
||||
currentApp = null;
|
||||
}
|
||||
|
||||
if (!shuttingDown && !expectedExits.has(app)) {
|
||||
scheduleRestart();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function stopApp() {
|
||||
const app = currentApp;
|
||||
if (!app) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentApp = null;
|
||||
expectedExits.add(app);
|
||||
|
||||
await new Promise((resolve) => {
|
||||
let settled = false;
|
||||
|
||||
const finish = () => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
settled = true;
|
||||
resolve();
|
||||
};
|
||||
|
||||
app.once("exit", finish);
|
||||
app.kill("SIGTERM");
|
||||
killChildTreeByPid(app.pid, "TERM");
|
||||
|
||||
setTimeout(() => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
app.kill("SIGKILL");
|
||||
killChildTreeByPid(app.pid, "KILL");
|
||||
finish();
|
||||
}, forcedShutdownTimeoutMs).unref();
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleRestart() {
|
||||
if (shuttingDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
}
|
||||
|
||||
restartTimer = setTimeout(() => {
|
||||
restartTimer = null;
|
||||
restartQueue = restartQueue
|
||||
.catch(() => undefined)
|
||||
.then(async () => {
|
||||
await stopApp();
|
||||
if (!shuttingDown) {
|
||||
startApp();
|
||||
}
|
||||
});
|
||||
}, restartDebounceMs);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
scheduleRestart();
|
||||
});
|
||||
|
||||
watchers.push(watcher);
|
||||
}
|
||||
}
|
||||
|
||||
function killChildTree(signal) {
|
||||
if (process.platform === "win32") {
|
||||
return;
|
||||
}
|
||||
|
||||
// electronmon may leave Electron orphaned when parent shutdown races; kill direct children as fallback.
|
||||
// Kill direct children as a final fallback in case normal shutdown leaves stragglers.
|
||||
spawnSync("pkill", [`-${signal}`, "-P", String(process.pid)], { stdio: "ignore" });
|
||||
}
|
||||
|
||||
@@ -45,20 +173,29 @@ async function shutdown(exitCode) {
|
||||
if (shuttingDown) return;
|
||||
shuttingDown = true;
|
||||
|
||||
try {
|
||||
await Promise.race([monitor.destroy(), new Promise((resolve) => setTimeout(resolve, 1_500))]);
|
||||
} catch {
|
||||
// Best effort only; fallback process kill below handles stubborn children.
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
}
|
||||
|
||||
for (const watcher of watchers) {
|
||||
watcher.close();
|
||||
}
|
||||
|
||||
await stopApp();
|
||||
killChildTree("TERM");
|
||||
setTimeout(() => {
|
||||
killChildTree("KILL");
|
||||
}, 1_200).unref();
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, childTreeGracePeriodMs);
|
||||
});
|
||||
killChildTree("KILL");
|
||||
|
||||
process.exit(exitCode);
|
||||
}
|
||||
|
||||
startWatchers();
|
||||
cleanupStaleDevApps();
|
||||
startApp();
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
void shutdown(130);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import * as ChildProcess from "node:child_process";
|
||||
|
||||
export function fixPath(): void {
|
||||
if (process.platform !== "darwin") return;
|
||||
|
||||
try {
|
||||
const shell = process.env.SHELL ?? "/bin/zsh";
|
||||
const result = execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
const result = ChildProcess.execFileSync(shell, ["-ilc", "echo -n $PATH"], {
|
||||
encoding: "utf8",
|
||||
timeout: 5000,
|
||||
});
|
||||
|
||||
+614
-66
@@ -1,16 +1,36 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import * as ChildProcess from "node:child_process";
|
||||
import * as Crypto from "node:crypto";
|
||||
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, protocol, shell } from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
import * as Effect from "effect/Effect";
|
||||
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 { fixPath } from "./fixPath";
|
||||
import {
|
||||
getAutoUpdateDisabledReason,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
reduceDesktopUpdateStateOnCheckStart,
|
||||
reduceDesktopUpdateStateOnDownloadComplete,
|
||||
reduceDesktopUpdateStateOnDownloadFailure,
|
||||
reduceDesktopUpdateStateOnDownloadProgress,
|
||||
reduceDesktopUpdateStateOnDownloadStart,
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
|
||||
fixPath();
|
||||
|
||||
@@ -19,18 +39,30 @@ const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
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_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const STATE_DIR =
|
||||
process.env.T3CODE_STATE_DIR?.trim() || path.join(os.homedir(), ".t3", "userdata");
|
||||
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = path.resolve(__dirname, "../../..");
|
||||
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 COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
|
||||
const COMMIT_HASH_DISPLAY_LENGTH = 12;
|
||||
const LOG_DIR = Path.join(STATE_DIR, "logs");
|
||||
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
|
||||
const LOG_FILE_MAX_FILES = 10;
|
||||
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
|
||||
let mainWindow: BrowserWindow | null = null;
|
||||
let backendProcess: ChildProcess | null = null;
|
||||
let backendProcess: ChildProcess.ChildProcess | null = null;
|
||||
let backendPort = 0;
|
||||
let backendAuthToken = "";
|
||||
let backendWsUrl = "";
|
||||
@@ -39,8 +71,133 @@ let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
let desktopProtocolRegistered = false;
|
||||
let aboutCommitHashCache: string | null | undefined;
|
||||
let desktopLogSink: RotatingFileSink | null = null;
|
||||
let backendLogSink: RotatingFileSink | null = null;
|
||||
let restoreStdIoCapture: (() => void) | null = null;
|
||||
|
||||
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
const initialUpdateState = (): DesktopUpdateState => createInitialDesktopUpdateState(app.getVersion());
|
||||
|
||||
function logTimestamp(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function logScope(scope: string): string {
|
||||
return `${scope} run=${APP_RUN_ID}`;
|
||||
}
|
||||
|
||||
function sanitizeLogValue(value: string): string {
|
||||
return value.replace(/\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
function writeDesktopLogHeader(message: string): void {
|
||||
if (!desktopLogSink) return;
|
||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
|
||||
}
|
||||
|
||||
function writeBackendSessionBoundary(phase: "START" | "END", details: string): void {
|
||||
if (!backendLogSink) return;
|
||||
const normalizedDetails = sanitizeLogValue(details);
|
||||
backendLogSink.write(
|
||||
`[${logTimestamp()}] ---- APP SESSION ${phase} run=${APP_RUN_ID} ${normalizedDetails} ----\n`,
|
||||
);
|
||||
}
|
||||
|
||||
function formatErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) {
|
||||
return error.message;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
encoding: BufferEncoding | undefined,
|
||||
): void {
|
||||
if (!desktopLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk)
|
||||
? chunk
|
||||
: Buffer.from(String(chunk), typeof chunk === "string" ? encoding : undefined);
|
||||
desktopLogSink.write(`[${logTimestamp()}] [${logScope(streamName)}] `);
|
||||
desktopLogSink.write(buffer);
|
||||
if (buffer.length === 0 || buffer[buffer.length - 1] !== 0x0a) {
|
||||
desktopLogSink.write("\n");
|
||||
}
|
||||
}
|
||||
|
||||
function installStdIoCapture(): void {
|
||||
if (!app.isPackaged || desktopLogSink === null || restoreStdIoCapture !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||
const originalStderrWrite = process.stderr.write.bind(process.stderr);
|
||||
|
||||
const patchWrite =
|
||||
(streamName: "stdout" | "stderr", originalWrite: typeof process.stdout.write) =>
|
||||
(
|
||||
chunk: string | Uint8Array,
|
||||
encodingOrCallback?: BufferEncoding | ((error?: Error | null) => void),
|
||||
callback?: (error?: Error | null) => void,
|
||||
): boolean => {
|
||||
const encoding = typeof encodingOrCallback === "string" ? encodingOrCallback : undefined;
|
||||
writeDesktopStreamChunk(streamName, chunk, encoding);
|
||||
if (typeof encodingOrCallback === "function") {
|
||||
return originalWrite(chunk, encodingOrCallback);
|
||||
}
|
||||
if (callback !== undefined) {
|
||||
return originalWrite(chunk, encoding, callback);
|
||||
}
|
||||
if (encoding !== undefined) {
|
||||
return originalWrite(chunk, encoding);
|
||||
}
|
||||
return originalWrite(chunk);
|
||||
};
|
||||
|
||||
process.stdout.write = patchWrite("stdout", originalStdoutWrite);
|
||||
process.stderr.write = patchWrite("stderr", originalStderrWrite);
|
||||
|
||||
restoreStdIoCapture = () => {
|
||||
process.stdout.write = originalStdoutWrite;
|
||||
process.stderr.write = originalStderrWrite;
|
||||
restoreStdIoCapture = null;
|
||||
};
|
||||
}
|
||||
|
||||
function initializePackagedLogging(): void {
|
||||
if (!app.isPackaged) return;
|
||||
try {
|
||||
desktopLogSink = new RotatingFileSink({
|
||||
filePath: Path.join(LOG_DIR, "desktop-main.log"),
|
||||
maxBytes: LOG_FILE_MAX_BYTES,
|
||||
maxFiles: LOG_FILE_MAX_FILES,
|
||||
});
|
||||
backendLogSink = new RotatingFileSink({
|
||||
filePath: Path.join(LOG_DIR, "server-child.log"),
|
||||
maxBytes: LOG_FILE_MAX_BYTES,
|
||||
maxFiles: LOG_FILE_MAX_FILES,
|
||||
});
|
||||
installStdIoCapture();
|
||||
writeDesktopLogHeader(`runtime log capture enabled logDir=${LOG_DIR}`);
|
||||
} catch (error) {
|
||||
// Logging setup should never block app startup.
|
||||
console.error("[desktop] failed to initialize packaged logging", error);
|
||||
}
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
if (!app.isPackaged || backendLogSink === null) return;
|
||||
const writeChunk = (chunk: unknown): void => {
|
||||
if (!backendLogSink) return;
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink.write(buffer);
|
||||
};
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
|
||||
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||
if (process.platform !== "darwin") return undefined;
|
||||
@@ -64,6 +221,18 @@ function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
let updatePollTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let updateStartupTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let updateCheckInFlight = false;
|
||||
let updateDownloadInFlight = false;
|
||||
let updaterConfigured = false;
|
||||
let updateState: DesktopUpdateState = initialUpdateState();
|
||||
|
||||
function resolveUpdaterErrorContext(): DesktopUpdateErrorContext {
|
||||
if (updateDownloadInFlight) return "download";
|
||||
if (updateCheckInFlight) return "check";
|
||||
return updateState.errorContext;
|
||||
}
|
||||
|
||||
protocol.registerSchemesAsPrivileged([
|
||||
{
|
||||
@@ -84,6 +253,28 @@ function resolveAppRoot(): string {
|
||||
return app.getAppPath();
|
||||
}
|
||||
|
||||
/** Read the baked-in app-update.yml config (if applicable). */
|
||||
function readAppUpdateYml(): Record<string, string> | null {
|
||||
try {
|
||||
// electron-updater reads from process.resourcesPath in packaged builds,
|
||||
// or dev-app-update.yml via app.getAppPath() in dev.
|
||||
const ymlPath = app.isPackaged
|
||||
? Path.join(process.resourcesPath, "app-update.yml")
|
||||
: Path.join(app.getAppPath(), "dev-app-update.yml");
|
||||
const raw = FS.readFileSync(ymlPath, "utf-8");
|
||||
// The YAML is simple key-value pairs — avoid pulling in a YAML parser by
|
||||
// doing a line-based parse (fields: provider, owner, repo, releaseType, …).
|
||||
const entries: Record<string, string> = {};
|
||||
for (const line of raw.split("\n")) {
|
||||
const match = line.match(/^(\w+):\s*(.+)$/);
|
||||
if (match?.[1] && match[2]) entries[match[1]] = match[2].trim();
|
||||
}
|
||||
return entries.provider ? entries : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeCommitHash(value: unknown): string | null {
|
||||
if (typeof value !== "string") {
|
||||
return null;
|
||||
@@ -96,13 +287,13 @@ function normalizeCommitHash(value: unknown): string | null {
|
||||
}
|
||||
|
||||
function resolveEmbeddedCommitHash(): string | null {
|
||||
const packageJsonPath = path.join(resolveAppRoot(), "package.json");
|
||||
if (!fs.existsSync(packageJsonPath)) {
|
||||
const packageJsonPath = Path.join(resolveAppRoot(), "package.json");
|
||||
if (!FS.existsSync(packageJsonPath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(packageJsonPath, "utf8");
|
||||
const raw = FS.readFileSync(packageJsonPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as { t3codeCommitHash?: unknown };
|
||||
return normalizeCommitHash(parsed.t3codeCommitHash);
|
||||
} catch {
|
||||
@@ -133,25 +324,25 @@ function resolveAboutCommitHash(): string | null {
|
||||
}
|
||||
|
||||
function resolveBackendEntry(): string {
|
||||
return path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
|
||||
}
|
||||
|
||||
function resolveBackendCwd(): string {
|
||||
if (!app.isPackaged) {
|
||||
return resolveAppRoot();
|
||||
}
|
||||
return os.homedir();
|
||||
return OS.homedir();
|
||||
}
|
||||
|
||||
function resolveDesktopStaticDir(): string | null {
|
||||
const appRoot = resolveAppRoot();
|
||||
const candidates = [
|
||||
path.join(appRoot, "apps/server/dist/client"),
|
||||
path.join(appRoot, "apps/web/dist"),
|
||||
Path.join(appRoot, "apps/server/dist/client"),
|
||||
Path.join(appRoot, "apps/web/dist"),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(path.join(candidate, "index.html"))) {
|
||||
if (FS.existsSync(Path.join(candidate, "index.html"))) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
@@ -162,35 +353,50 @@ function resolveDesktopStaticDir(): string | null {
|
||||
function resolveDesktopStaticPath(staticRoot: string, requestUrl: string): string {
|
||||
const url = new URL(requestUrl);
|
||||
const rawPath = decodeURIComponent(url.pathname);
|
||||
const normalizedPath = path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
const normalizedPath = Path.posix.normalize(rawPath).replace(/^\/+/, "");
|
||||
if (normalizedPath.includes("..")) {
|
||||
return path.join(staticRoot, "index.html");
|
||||
return Path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
const requestedPath = normalizedPath.length > 0 ? normalizedPath : "index.html";
|
||||
const resolvedPath = path.join(staticRoot, requestedPath);
|
||||
const resolvedPath = Path.join(staticRoot, requestedPath);
|
||||
|
||||
if (path.extname(resolvedPath)) {
|
||||
if (Path.extname(resolvedPath)) {
|
||||
return resolvedPath;
|
||||
}
|
||||
|
||||
const nestedIndex = path.join(resolvedPath, "index.html");
|
||||
if (fs.existsSync(nestedIndex)) {
|
||||
const nestedIndex = Path.join(resolvedPath, "index.html");
|
||||
if (FS.existsSync(nestedIndex)) {
|
||||
return nestedIndex;
|
||||
}
|
||||
|
||||
return path.join(staticRoot, "index.html");
|
||||
return Path.join(staticRoot, "index.html");
|
||||
}
|
||||
|
||||
function isStaticAssetRequest(requestUrl: string): boolean {
|
||||
try {
|
||||
const url = new URL(requestUrl);
|
||||
return path.extname(url.pathname).length > 0;
|
||||
return Path.extname(url.pathname).length > 0;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function handleFatalStartupError(stage: string, error: unknown): void {
|
||||
const message = formatErrorMessage(error);
|
||||
const detail =
|
||||
error instanceof Error && typeof error.stack === "string" ? `\n${error.stack}` : "";
|
||||
writeDesktopLogHeader(`fatal startup error stage=${stage} message=${message}`);
|
||||
console.error(`[desktop] fatal startup error (${stage})`, error);
|
||||
if (!isQuitting) {
|
||||
isQuitting = true;
|
||||
dialog.showErrorBox("T3 Code failed to start", `Stage: ${stage}\n${message}${detail}`);
|
||||
}
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
}
|
||||
|
||||
function registerDesktopProtocol(): void {
|
||||
if (isDevelopment || desktopProtocolRegistered) return;
|
||||
|
||||
@@ -201,19 +407,19 @@ function registerDesktopProtocol(): void {
|
||||
);
|
||||
}
|
||||
|
||||
const staticRootResolved = path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${path.sep}`;
|
||||
const fallbackIndex = path.join(staticRootResolved, "index.html");
|
||||
const staticRootResolved = Path.resolve(staticRoot);
|
||||
const staticRootPrefix = `${staticRootResolved}${Path.sep}`;
|
||||
const fallbackIndex = Path.join(staticRootResolved, "index.html");
|
||||
|
||||
protocol.registerFileProtocol(DESKTOP_SCHEME, (request, callback) => {
|
||||
try {
|
||||
const candidate = resolveDesktopStaticPath(staticRootResolved, request.url);
|
||||
const resolvedCandidate = path.resolve(candidate);
|
||||
const resolvedCandidate = Path.resolve(candidate);
|
||||
const isInRoot =
|
||||
resolvedCandidate === fallbackIndex || resolvedCandidate.startsWith(staticRootPrefix);
|
||||
const isAssetRequest = isStaticAssetRequest(request.url);
|
||||
|
||||
if (!isInRoot || !fs.existsSync(resolvedCandidate)) {
|
||||
if (!isInRoot || !FS.existsSync(resolvedCandidate)) {
|
||||
if (isAssetRequest) {
|
||||
callback({ error: -6 });
|
||||
return;
|
||||
@@ -256,6 +462,32 @@ function dispatchMenuAction(action: string): void {
|
||||
send();
|
||||
}
|
||||
|
||||
function handleCheckForUpdatesMenuClick(): void {
|
||||
const disabledReason = getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
isPackaged: app.isPackaged,
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
});
|
||||
if (disabledReason) {
|
||||
console.info("[desktop-updater] Manual update check requested, but updates are disabled.");
|
||||
void dialog.showMessageBox({
|
||||
type: "info",
|
||||
title: "Updates unavailable",
|
||||
message: "Automatic updates are not available right now.",
|
||||
detail: disabledReason,
|
||||
buttons: ["OK"],
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!BrowserWindow.getAllWindows().length) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
void checkForUpdates("menu");
|
||||
}
|
||||
|
||||
function configureApplicationMenu(): void {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
|
||||
@@ -264,6 +496,11 @@ function configureApplicationMenu(): void {
|
||||
label: app.name,
|
||||
submenu: [
|
||||
{ role: "about" },
|
||||
{
|
||||
label: "Check for Updates...",
|
||||
click: () => handleCheckForUpdatesMenuClick(),
|
||||
},
|
||||
{ type: "separator" },
|
||||
{
|
||||
label: "Settings...",
|
||||
accelerator: "CmdOrCtrl+,",
|
||||
@@ -301,6 +538,15 @@ function configureApplicationMenu(): void {
|
||||
{ role: "editMenu" },
|
||||
{ role: "viewMenu" },
|
||||
{ role: "windowMenu" },
|
||||
{
|
||||
role: "help",
|
||||
submenu: [
|
||||
{
|
||||
label: "Check for Updates...",
|
||||
click: () => handleCheckForUpdatesMenuClick(),
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
Menu.setApplicationMenu(Menu.buildFromTemplate(template));
|
||||
@@ -308,13 +554,13 @@ function configureApplicationMenu(): void {
|
||||
|
||||
function resolveResourcePath(fileName: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, "../resources", fileName),
|
||||
path.join(process.resourcesPath, "resources", fileName),
|
||||
path.join(process.resourcesPath, fileName),
|
||||
Path.join(__dirname, "../resources", fileName),
|
||||
Path.join(process.resourcesPath, "resources", fileName),
|
||||
Path.join(process.resourcesPath, fileName),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) {
|
||||
if (FS.existsSync(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
@@ -347,24 +593,200 @@ function configureAppIdentity(): void {
|
||||
}
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const probe = net.createServer();
|
||||
probe.listen(0, "127.0.0.1", () => {
|
||||
const address = probe.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
probe.close(() => {
|
||||
if (port > 0) {
|
||||
resolve(port);
|
||||
return;
|
||||
}
|
||||
reject(new Error("Failed to reserve backend port"));
|
||||
});
|
||||
});
|
||||
probe.on("error", reject);
|
||||
});
|
||||
function clearUpdatePollTimer(): void {
|
||||
if (updateStartupTimer) {
|
||||
clearTimeout(updateStartupTimer);
|
||||
updateStartupTimer = null;
|
||||
}
|
||||
if (updatePollTimer) {
|
||||
clearInterval(updatePollTimer);
|
||||
updatePollTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function emitUpdateState(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
if (window.isDestroyed()) continue;
|
||||
window.webContents.send(UPDATE_STATE_CHANNEL, updateState);
|
||||
}
|
||||
}
|
||||
|
||||
function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
||||
updateState = { ...updateState, ...patch };
|
||||
emitUpdateState();
|
||||
}
|
||||
|
||||
function shouldEnableAutoUpdates(): boolean {
|
||||
return (
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment,
|
||||
isPackaged: app.isPackaged,
|
||||
platform: process.platform,
|
||||
appImage: process.env.APPIMAGE,
|
||||
disabledByEnv: process.env.T3CODE_DISABLE_AUTO_UPDATE === "1",
|
||||
}) === null
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
updateCheckInFlight = true;
|
||||
setUpdateState(reduceDesktopUpdateStateOnCheckStart(updateState, new Date().toISOString()));
|
||||
console.info(`[desktop-updater] Checking for updates (${reason})...`);
|
||||
|
||||
try {
|
||||
await autoUpdater.checkForUpdates();
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setUpdateState(reduceDesktopUpdateStateOnCheckFailure(updateState, message, new Date().toISOString()));
|
||||
console.error(`[desktop-updater] Failed to check for updates: ${message}`);
|
||||
} finally {
|
||||
updateCheckInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function downloadAvailableUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||
if (!updaterConfigured || updateDownloadInFlight || updateState.status !== "available") {
|
||||
return { accepted: false, completed: false };
|
||||
}
|
||||
updateDownloadInFlight = true;
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadStart(updateState));
|
||||
console.info("[desktop-updater] Downloading update...");
|
||||
|
||||
try {
|
||||
await autoUpdater.downloadUpdate();
|
||||
return { accepted: true, completed: true };
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to download update: ${message}`);
|
||||
return { accepted: true, completed: false };
|
||||
} finally {
|
||||
updateDownloadInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function installDownloadedUpdate(): Promise<{ accepted: boolean; completed: boolean }> {
|
||||
if (isQuitting || !updaterConfigured || updateState.status !== "downloaded") {
|
||||
return { accepted: false, completed: false };
|
||||
}
|
||||
|
||||
isQuitting = true;
|
||||
clearUpdatePollTimer();
|
||||
try {
|
||||
await stopBackendAndWaitForExit();
|
||||
autoUpdater.quitAndInstall();
|
||||
return { accepted: true, completed: true };
|
||||
} catch (error: unknown) {
|
||||
const message = formatErrorMessage(error);
|
||||
isQuitting = false;
|
||||
setUpdateState(reduceDesktopUpdateStateOnInstallFailure(updateState, message));
|
||||
console.error(`[desktop-updater] Failed to install update: ${message}`);
|
||||
return { accepted: true, completed: false };
|
||||
}
|
||||
}
|
||||
|
||||
function configureAutoUpdater(): void {
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState({
|
||||
...createInitialDesktopUpdateState(app.getVersion()),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
});
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
updaterConfigured = true;
|
||||
|
||||
const githubToken =
|
||||
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
|
||||
// public Atom feed (github.com/…/releases.atom) which rejects Bearer auth.
|
||||
const appUpdateYml = readAppUpdateYml();
|
||||
if (appUpdateYml?.provider === "github") {
|
||||
autoUpdater.setFeedURL({
|
||||
...appUpdateYml,
|
||||
provider: "github" as const,
|
||||
private: true,
|
||||
token: githubToken,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
autoUpdater.allowPrerelease = app.getVersion().includes("-");
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
|
||||
autoUpdater.on("checking-for-update", () => {
|
||||
console.info("[desktop-updater] Looking for updates...");
|
||||
});
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
setUpdateState(reduceDesktopUpdateStateOnUpdateAvailable(updateState, info.version, new Date().toISOString()));
|
||||
lastLoggedDownloadMilestone = -1;
|
||||
console.info(`[desktop-updater] Update available: ${info.version}`);
|
||||
});
|
||||
autoUpdater.on("update-not-available", () => {
|
||||
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
|
||||
lastLoggedDownloadMilestone = -1;
|
||||
console.info("[desktop-updater] No updates available.");
|
||||
});
|
||||
autoUpdater.on("error", (error) => {
|
||||
const message = formatErrorMessage(error);
|
||||
if (!updateCheckInFlight && !updateDownloadInFlight) {
|
||||
setUpdateState({
|
||||
status: "error",
|
||||
message,
|
||||
checkedAt: new Date().toISOString(),
|
||||
downloadPercent: null,
|
||||
errorContext: resolveUpdaterErrorContext(),
|
||||
canRetry: updateState.availableVersion !== null || updateState.downloadedVersion !== null,
|
||||
});
|
||||
}
|
||||
console.error(`[desktop-updater] Updater error: ${message}`);
|
||||
});
|
||||
autoUpdater.on("download-progress", (progress) => {
|
||||
const percent = Math.floor(progress.percent);
|
||||
if (
|
||||
shouldBroadcastDownloadProgress(updateState, progress.percent) ||
|
||||
updateState.message !== null
|
||||
) {
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadProgress(updateState, progress.percent));
|
||||
}
|
||||
const milestone = percent - (percent % 10);
|
||||
if (milestone > lastLoggedDownloadMilestone) {
|
||||
lastLoggedDownloadMilestone = milestone;
|
||||
console.info(`[desktop-updater] Download progress: ${percent}%`);
|
||||
}
|
||||
});
|
||||
autoUpdater.on("update-downloaded", (info) => {
|
||||
setUpdateState(reduceDesktopUpdateStateOnDownloadComplete(updateState, info.version));
|
||||
console.info(`[desktop-updater] Update downloaded: ${info.version}`);
|
||||
});
|
||||
|
||||
clearUpdatePollTimer();
|
||||
|
||||
updateStartupTimer = setTimeout(() => {
|
||||
updateStartupTimer = null;
|
||||
void checkForUpdates("startup");
|
||||
}, AUTO_UPDATE_STARTUP_DELAY_MS);
|
||||
updateStartupTimer.unref();
|
||||
|
||||
updatePollTimer = setInterval(() => {
|
||||
void checkForUpdates("poll");
|
||||
}, AUTO_UPDATE_POLL_INTERVAL_MS);
|
||||
updatePollTimer.unref();
|
||||
}
|
||||
function backendEnv(): NodeJS.ProcessEnv {
|
||||
return {
|
||||
...process.env,
|
||||
@@ -393,12 +815,13 @@ function startBackend(): void {
|
||||
if (isQuitting || backendProcess) return;
|
||||
|
||||
const backendEntry = resolveBackendEntry();
|
||||
if (!fs.existsSync(backendEntry)) {
|
||||
if (!FS.existsSync(backendEntry)) {
|
||||
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const child = spawn(process.execPath, [backendEntry], {
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
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.
|
||||
@@ -406,9 +829,20 @@ function startBackend(): void {
|
||||
...backendEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
stdio: "inherit",
|
||||
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||
});
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
if (backendSessionClosed) return;
|
||||
backendSessionClosed = true;
|
||||
writeBackendSessionBoundary("END", details);
|
||||
};
|
||||
writeBackendSessionBoundary(
|
||||
"START",
|
||||
`pid=${child.pid ?? "unknown"} port=${backendPort} cwd=${resolveBackendCwd()}`,
|
||||
);
|
||||
captureBackendOutput(child);
|
||||
|
||||
child.once("spawn", () => {
|
||||
restartAttempt = 0;
|
||||
@@ -418,6 +852,7 @@ function startBackend(): void {
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
|
||||
scheduleBackendRestart(error.message);
|
||||
});
|
||||
|
||||
@@ -425,6 +860,9 @@ function startBackend(): void {
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
}
|
||||
closeBackendSession(
|
||||
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
|
||||
);
|
||||
if (isQuitting) return;
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
@@ -451,6 +889,57 @@ function stopBackend(): void {
|
||||
}
|
||||
}
|
||||
|
||||
async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
}
|
||||
|
||||
const child = backendProcess;
|
||||
backendProcess = null;
|
||||
if (!child) return;
|
||||
const backendChild = child;
|
||||
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
let settled = false;
|
||||
let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let exitTimeoutTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
function settle(): void {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
backendChild.off("exit", onExit);
|
||||
if (forceKillTimer) {
|
||||
clearTimeout(forceKillTimer);
|
||||
}
|
||||
if (exitTimeoutTimer) {
|
||||
clearTimeout(exitTimeoutTimer);
|
||||
}
|
||||
resolve();
|
||||
}
|
||||
|
||||
function onExit(): void {
|
||||
settle();
|
||||
}
|
||||
|
||||
backendChild.once("exit", onExit);
|
||||
backendChild.kill("SIGTERM");
|
||||
|
||||
forceKillTimer = setTimeout(() => {
|
||||
if (backendChild.exitCode === null && backendChild.signalCode === null) {
|
||||
backendChild.kill("SIGKILL");
|
||||
}
|
||||
}, 2_000);
|
||||
forceKillTimer.unref();
|
||||
|
||||
exitTimeoutTimer = setTimeout(() => {
|
||||
settle();
|
||||
}, timeoutMs);
|
||||
exitTimeoutTimer.unref();
|
||||
});
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||
@@ -561,6 +1050,36 @@ function registerIpcHandlers(): void {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
|
||||
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
|
||||
|
||||
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
|
||||
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
|
||||
const result = await downloadAvailableUpdate();
|
||||
return {
|
||||
accepted: result.accepted,
|
||||
completed: result.completed,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_INSTALL_CHANNEL);
|
||||
ipcMain.handle(UPDATE_INSTALL_CHANNEL, async () => {
|
||||
if (isQuitting) {
|
||||
return {
|
||||
accepted: false,
|
||||
completed: false,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
}
|
||||
const result = await installDownloadedUpdate();
|
||||
return {
|
||||
accepted: result.accepted,
|
||||
completed: result.completed,
|
||||
state: updateState,
|
||||
} satisfies DesktopUpdateActionResult;
|
||||
});
|
||||
}
|
||||
|
||||
function getIconOption(): { icon: string } | Record<string, never> {
|
||||
@@ -583,7 +1102,7 @@ function createWindow(): BrowserWindow {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
preload: path.join(__dirname, "preload.js"),
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
@@ -597,6 +1116,7 @@ function createWindow(): BrowserWindow {
|
||||
});
|
||||
window.webContents.on("did-finish-load", () => {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
window.once("ready-to-show", () => {
|
||||
window.show();
|
||||
@@ -621,33 +1141,55 @@ function createWindow(): BrowserWindow {
|
||||
configureAppIdentity();
|
||||
|
||||
async function bootstrap(): Promise<void> {
|
||||
backendPort = await reserveLoopbackPort();
|
||||
backendAuthToken = randomBytes(24).toString("hex");
|
||||
writeDesktopLogHeader("bootstrap start");
|
||||
backendPort = await Effect.service(NetService).pipe(
|
||||
Effect.flatMap((net) => net.reserveLoopbackPort()),
|
||||
Effect.provide(NetService.layer),
|
||||
Effect.runPromise,
|
||||
);
|
||||
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
||||
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
||||
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
|
||||
|
||||
registerIpcHandlers();
|
||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||
startBackend();
|
||||
writeDesktopLogHeader("bootstrap backend start requested");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("before-quit received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
});
|
||||
|
||||
app.whenReady().then(() => {
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
void bootstrap();
|
||||
app
|
||||
.whenReady()
|
||||
.then(() => {
|
||||
writeDesktopLogHeader("app ready");
|
||||
configureAppIdentity();
|
||||
configureApplicationMenu();
|
||||
registerDesktopProtocol();
|
||||
configureAutoUpdater();
|
||||
void bootstrap().catch((error) => {
|
||||
handleFatalStartupError("bootstrap", error);
|
||||
});
|
||||
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
app.on("activate", () => {
|
||||
if (BrowserWindow.getAllWindows().length === 0) {
|
||||
mainWindow = createWindow();
|
||||
}
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
handleFatalStartupError("whenReady", error);
|
||||
});
|
||||
});
|
||||
|
||||
app.on("window-all-closed", () => {
|
||||
if (process.platform !== "darwin") {
|
||||
@@ -659,14 +1201,20 @@ if (process.platform !== "win32") {
|
||||
process.on("SIGINT", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("SIGINT received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
});
|
||||
|
||||
process.on("SIGTERM", () => {
|
||||
if (isQuitting) return;
|
||||
isQuitting = true;
|
||||
writeDesktopLogHeader("SIGTERM received");
|
||||
clearUpdatePollTimer();
|
||||
stopBackend();
|
||||
restoreStdIoCapture?.();
|
||||
app.quit();
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,10 @@ const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
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_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
@@ -25,4 +29,18 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.removeListener(MENU_ACTION_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
onUpdateState: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
|
||||
if (typeof state !== "object" || state === null) return;
|
||||
listener(state as Parameters<typeof listener>[0]);
|
||||
};
|
||||
|
||||
ipcRenderer.on(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(UPDATE_STATE_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
} satisfies DesktopBridge);
|
||||
@@ -0,0 +1,74 @@
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
const tempRoots: string[] = [];
|
||||
|
||||
function makeTempDir(): string {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-rotating-log-"));
|
||||
tempRoots.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const dir of tempRoots.splice(0)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe("RotatingFileSink", () => {
|
||||
it("rotates when writes exceed max bytes", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 10,
|
||||
maxFiles: 3,
|
||||
});
|
||||
|
||||
sink.write("12345");
|
||||
sink.write("67890");
|
||||
sink.write("abc");
|
||||
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log"), "utf8")).toBe("abc");
|
||||
expect(fs.readFileSync(path.join(dir, "desktop-main.log.1"), "utf8")).toBe("1234567890");
|
||||
});
|
||||
|
||||
it("retains only maxFiles backups", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "server-child.log");
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 4,
|
||||
maxFiles: 2,
|
||||
});
|
||||
|
||||
sink.write("aaaa");
|
||||
sink.write("bbbb");
|
||||
sink.write("cccc");
|
||||
sink.write("dddd");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.1"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.2"))).toBe(true);
|
||||
expect(fs.existsSync(path.join(dir, "server-child.log.3"))).toBe(false);
|
||||
});
|
||||
|
||||
it("prunes stale backups above maxFiles on startup", () => {
|
||||
const dir = makeTempDir();
|
||||
const logPath = path.join(dir, "desktop-main.log");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.1"), "first");
|
||||
fs.writeFileSync(path.join(dir, "desktop-main.log.4"), "stale");
|
||||
|
||||
const sink = new RotatingFileSink({
|
||||
filePath: logPath,
|
||||
maxBytes: 16,
|
||||
maxFiles: 2,
|
||||
});
|
||||
sink.write("hello");
|
||||
|
||||
expect(fs.existsSync(path.join(dir, "desktop-main.log.4"))).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
reduceDesktopUpdateStateOnCheckStart,
|
||||
reduceDesktopUpdateStateOnDownloadComplete,
|
||||
reduceDesktopUpdateStateOnDownloadFailure,
|
||||
reduceDesktopUpdateStateOnDownloadProgress,
|
||||
reduceDesktopUpdateStateOnDownloadStart,
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine";
|
||||
|
||||
describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("checking");
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
expect(state.canRetry).toBe(false);
|
||||
});
|
||||
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"network unavailable",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("error");
|
||||
expect(state.errorContext).toBe("check");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
downloadPercent: 43,
|
||||
},
|
||||
"checksum mismatch",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("available");
|
||||
expect(state.availableVersion).toBe("1.1.0");
|
||||
expect(state.errorContext).toBe("download");
|
||||
expect(state.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
},
|
||||
"1.1.0",
|
||||
);
|
||||
const failedInstall = reduceDesktopUpdateStateOnInstallFailure(downloaded, "backend shutdown timed out");
|
||||
|
||||
expect(downloaded.status).toBe("downloaded");
|
||||
expect(downloaded.downloadedVersion).toBe("1.1.0");
|
||||
expect(failedInstall.status).toBe("downloaded");
|
||||
expect(failedInstall.errorContext).toBe("install");
|
||||
expect(failedInstall.canRetry).toBe(true);
|
||||
});
|
||||
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
downloadedVersion: "1.1.0",
|
||||
message: "old failure",
|
||||
errorContext: "download",
|
||||
canRetry: true,
|
||||
},
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
|
||||
expect(state.status).toBe("up-to-date");
|
||||
expect(state.availableVersion).toBeNull();
|
||||
expect(state.downloadedVersion).toBeNull();
|
||||
expect(state.message).toBeNull();
|
||||
expect(state.errorContext).toBeNull();
|
||||
});
|
||||
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0"),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
"1.1.0",
|
||||
"2026-03-04T00:00:00.000Z",
|
||||
);
|
||||
const downloading = reduceDesktopUpdateStateOnDownloadStart(available);
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
expect(progress.errorContext).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
|
||||
export function createInitialDesktopUpdateState(currentVersion: string): DesktopUpdateState {
|
||||
return {
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
currentVersion,
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckStart(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "checking",
|
||||
checkedAt,
|
||||
message: null,
|
||||
downloadPercent: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnCheckFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "error",
|
||||
message,
|
||||
checkedAt,
|
||||
downloadPercent: null,
|
||||
errorContext: "check",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "available",
|
||||
availableVersion: version,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnNoUpdate(
|
||||
state: DesktopUpdateState,
|
||||
checkedAt: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "up-to-date",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadStart(
|
||||
state: DesktopUpdateState,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: 0,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: nextStatusAfterDownloadFailure(state),
|
||||
message,
|
||||
downloadPercent: null,
|
||||
errorContext: "download",
|
||||
canRetry: getCanRetryAfterDownloadFailure(state),
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadProgress(
|
||||
state: DesktopUpdateState,
|
||||
percent: number,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloading",
|
||||
downloadPercent: percent,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnDownloadComplete(
|
||||
state: DesktopUpdateState,
|
||||
version: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
availableVersion: version,
|
||||
downloadedVersion: version,
|
||||
downloadPercent: 100,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function reduceDesktopUpdateStateOnInstallFailure(
|
||||
state: DesktopUpdateState,
|
||||
message: string,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...state,
|
||||
status: "downloaded",
|
||||
message,
|
||||
errorContext: "install",
|
||||
canRetry: true,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
getCanRetryAfterDownloadFailure,
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
currentVersion: "1.0.0",
|
||||
availableVersion: null,
|
||||
downloadedVersion: null,
|
||||
downloadPercent: null,
|
||||
checkedAt: null,
|
||||
message: null,
|
||||
errorContext: null,
|
||||
canRetry: false,
|
||||
};
|
||||
|
||||
describe("shouldBroadcastDownloadProgress", () => {
|
||||
it("broadcasts the first downloading progress update", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: null },
|
||||
1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("skips progress updates within the same 10% bucket", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 11.2 },
|
||||
18.7,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a new 10% bucket is reached", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 19.9 },
|
||||
20.1,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("broadcasts progress updates when a retry resets the download percentage", () => {
|
||||
expect(
|
||||
shouldBroadcastDownloadProgress(
|
||||
{ ...baseState, status: "downloading", downloadPercent: 50.4 },
|
||||
0.2,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAutoUpdateDisabledReason", () => {
|
||||
it("reports development builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: true,
|
||||
isPackaged: false,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("packaged production builds");
|
||||
});
|
||||
|
||||
it("reports env-disabled auto updates", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "darwin",
|
||||
appImage: undefined,
|
||||
disabledByEnv: true,
|
||||
}),
|
||||
).toContain("T3CODE_DISABLE_AUTO_UPDATE");
|
||||
});
|
||||
|
||||
it("reports linux non-AppImage builds as disabled", () => {
|
||||
expect(
|
||||
getAutoUpdateDisabledReason({
|
||||
isDevelopment: false,
|
||||
isPackaged: true,
|
||||
platform: "linux",
|
||||
appImage: undefined,
|
||||
disabledByEnv: false,
|
||||
}),
|
||||
).toContain("AppImage");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextStatusAfterDownloadFailure", () => {
|
||||
it("returns available when an update version is still known", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe("available");
|
||||
});
|
||||
|
||||
it("returns error when no update version can be retried", () => {
|
||||
expect(
|
||||
nextStatusAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe("error");
|
||||
});
|
||||
});
|
||||
|
||||
describe("getCanRetryAfterDownloadFailure", () => {
|
||||
it("returns true when an available version is still present", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("returns false when no version is available to retry", () => {
|
||||
expect(
|
||||
getCanRetryAfterDownloadFailure({
|
||||
...baseState,
|
||||
status: "downloading",
|
||||
availableVersion: null,
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
export function shouldBroadcastDownloadProgress(
|
||||
currentState: DesktopUpdateState,
|
||||
nextPercent: number,
|
||||
): boolean {
|
||||
if (currentState.status !== "downloading") {
|
||||
return true;
|
||||
}
|
||||
|
||||
const currentPercent = currentState.downloadPercent;
|
||||
if (currentPercent === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const previousStep = Math.floor(currentPercent / 10);
|
||||
const nextStep = Math.floor(nextPercent / 10);
|
||||
return nextStep !== previousStep || nextPercent === 100;
|
||||
}
|
||||
|
||||
export function nextStatusAfterDownloadFailure(
|
||||
currentState: DesktopUpdateState,
|
||||
): DesktopUpdateState["status"] {
|
||||
return currentState.availableVersion ? "available" : "error";
|
||||
}
|
||||
|
||||
export function getCanRetryAfterDownloadFailure(currentState: DesktopUpdateState): boolean {
|
||||
return currentState.availableVersion !== null;
|
||||
}
|
||||
|
||||
export function getAutoUpdateDisabledReason(args: {
|
||||
isDevelopment: boolean;
|
||||
isPackaged: boolean;
|
||||
platform: NodeJS.Platform;
|
||||
appImage?: string | undefined;
|
||||
disabledByEnv: boolean;
|
||||
}): string | null {
|
||||
if (args.isDevelopment || !args.isPackaged) {
|
||||
return "Automatic updates are only available in packaged production builds.";
|
||||
}
|
||||
if (args.disabledByEnv) {
|
||||
return "Automatic updates are disabled by the T3CODE_DISABLE_AUTO_UPDATE setting.";
|
||||
}
|
||||
if (args.platform === "linux" && !args.appImage) {
|
||||
return "Automatic updates on Linux require running the AppImage build.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: ["@t3tools/contracts"],
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineConfig } from "astro/config";
|
||||
|
||||
export default defineConfig({
|
||||
server: {
|
||||
port: Number(process.env.PORT ?? 4173),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "@t3tools/marketing",
|
||||
"version": "0.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"build": "astro build",
|
||||
"preview": "astro preview",
|
||||
"typecheck": "astro check"
|
||||
},
|
||||
"dependencies": {
|
||||
"astro": "^5.7.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.4",
|
||||
"typescript": "catalog:"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 279 KiB |
File renamed without changes.
|
Before Width: | Height: | Size: 1.1 MiB After Width: | Height: | Size: 1.1 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 652 KiB |
@@ -0,0 +1,326 @@
|
||||
---
|
||||
---
|
||||
|
||||
<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" />
|
||||
<link rel="icon" type="image/png" href="/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">↗</span>
|
||||
</a>
|
||||
</nav>
|
||||
|
||||
<main class="main">
|
||||
<h1 class="tagline">T3 Code is the best way to code with AI.</h1>
|
||||
|
||||
<a
|
||||
href="https://github.com/pingdotgg/t3code/releases"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="hero-button"
|
||||
>
|
||||
Download now
|
||||
</a>
|
||||
|
||||
<div class="screenshot-wrap">
|
||||
<img src="/screenshot.jpeg" alt="T3 Code" class="screenshot" />
|
||||
</div>
|
||||
|
||||
</main>
|
||||
|
||||
<footer class="footer">
|
||||
<span class="footer-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>
|
||||
: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;
|
||||
}
|
||||
|
||||
/* ── Tagline ── */
|
||||
|
||||
.tagline {
|
||||
font-weight: 500;
|
||||
font-size: clamp(2rem, 5vw, 3.5rem);
|
||||
letter-spacing: -0.035em;
|
||||
line-height: 1.15;
|
||||
text-align: center;
|
||||
margin: 0 0 6vh;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out forwards;
|
||||
}
|
||||
|
||||
/* ── Hero button ── */
|
||||
|
||||
.hero-button {
|
||||
display: inline-block;
|
||||
background: #fafafa;
|
||||
color: #09090b;
|
||||
padding: 0.75rem 2rem;
|
||||
border-radius: 999px;
|
||||
font-weight: 600;
|
||||
font-size: 0.9rem;
|
||||
margin-bottom: 5vh;
|
||||
opacity: 0;
|
||||
animation: fade-in 1s ease-out 0.15s forwards;
|
||||
transition: transform 0.25s ease, box-shadow 0.25s ease;
|
||||
}
|
||||
|
||||
.hero-button:hover {
|
||||
transform: scale(1.03);
|
||||
box-shadow: 0 0 24px rgba(255, 255, 255, 0.08);
|
||||
}
|
||||
|
||||
.hero-button:active {
|
||||
transform: scale(0.98);
|
||||
}
|
||||
|
||||
/* ── Screenshot ── */
|
||||
|
||||
.screenshot-wrap {
|
||||
margin: 0 auto;
|
||||
width: min(95vw, 1400px);
|
||||
opacity: 0;
|
||||
transform: scale(0.98);
|
||||
animation: screenshot-in 1s ease-out 0.15s forwards;
|
||||
}
|
||||
|
||||
.screenshot {
|
||||
width: 100%;
|
||||
display: block;
|
||||
border-radius: 16px;
|
||||
border: 1px solid rgba(255, 255, 255, 0.06);
|
||||
mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
|
||||
-webkit-mask-image: linear-gradient(to bottom, black 80%, transparent 100%);
|
||||
}
|
||||
|
||||
.screenshot-wrap::after {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 120px;
|
||||
background: inherit;
|
||||
margin-top: -1px;
|
||||
opacity: 0.04;
|
||||
transform: scaleY(-1);
|
||||
mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
|
||||
-webkit-mask-image: linear-gradient(to bottom, black 0%, transparent 60%);
|
||||
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;
|
||||
transform: scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Mobile ── */
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.nav {
|
||||
padding: 1.25rem 1.25rem;
|
||||
}
|
||||
|
||||
.main {
|
||||
padding-top: 7vh;
|
||||
}
|
||||
|
||||
.tagline {
|
||||
margin-bottom: 4vh;
|
||||
}
|
||||
|
||||
.screenshot-wrap {
|
||||
width: 95vw;
|
||||
}
|
||||
|
||||
.footer {
|
||||
padding: 1.25rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "astro/tsconfigs/strict"
|
||||
}
|
||||
@@ -37,7 +37,10 @@ import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.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";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
@@ -150,7 +153,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly rootDir: string;
|
||||
readonly workspaceDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly adapterHarness: TestProviderAdapterHarness;
|
||||
readonly adapterHarness: TestProviderAdapterHarness | null;
|
||||
readonly engine: OrchestrationEngineShape;
|
||||
readonly snapshotQuery: ProjectionSnapshotQuery["Service"];
|
||||
readonly providerService: ProviderService["Service"];
|
||||
@@ -185,229 +188,261 @@ export interface OrchestrationIntegrationHarness {
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export const makeOrchestrationIntegrationHarness = Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const adapterHarness = yield* makeTestProviderAdapterHarness;
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: "codex";
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const stateDir = path.join(rootDir, "state");
|
||||
const dbPath = path.join(stateDir, "state.sqlite");
|
||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
initializeGitWorkspace(workspaceDir);
|
||||
export const makeOrchestrationIntegrationHarness = (
|
||||
options?: MakeOrchestrationIntegrationHarnessOptions,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const sleep = (ms: number) => Effect.sleep(ms);
|
||||
const provider = options?.provider ?? "codex";
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
? null
|
||||
: yield* makeTestProviderAdapterHarness({
|
||||
provider,
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === adapterHarness.provider
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
: null;
|
||||
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
|
||||
const workspaceDir = path.join(rootDir, "workspace");
|
||||
const stateDir = path.join(rootDir, "state");
|
||||
const dbPath = path.join(stateDir, "state.sqlite");
|
||||
fs.mkdirSync(workspaceDir, { recursive: true });
|
||||
fs.mkdirSync(stateDir, { recursive: true });
|
||||
initializeGitWorkspace(workspaceDir);
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexAdapter = yield* CodexAdapter;
|
||||
return {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === "codex"
|
||||
? Effect.succeed(codexAdapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed(["codex"] as const),
|
||||
} as typeof ProviderAdapterRegistry.Service;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerLayer = useRealCodex
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
)
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
Layer.provide(OrchestrationEventStoreLive),
|
||||
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
|
||||
);
|
||||
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
);
|
||||
const providerLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
|
||||
);
|
||||
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
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: null }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
yield* sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
),
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
orchestrationLayer,
|
||||
OrchestrationProjectionSnapshotQueryLive,
|
||||
ProjectionCheckpointRepositoryLive,
|
||||
ProjectionPendingApprovalRepositoryLive,
|
||||
CheckpointStoreLive,
|
||||
providerLayer,
|
||||
);
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
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: null }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
);
|
||||
const layer = orchestrationReactorLayer.pipe(
|
||||
Layer.provide(persistenceLayer),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
const runtime = ManagedRuntime.make(layer);
|
||||
const engine = yield* tryRuntimePromise("load OrchestrationEngine service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationEngineService)),
|
||||
).pipe(Effect.orDie);
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerService = yield* tryRuntimePromise("load ProviderService service", () =>
|
||||
runtime.runPromise(Effect.service(ProviderService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointStore = yield* tryRuntimePromise("load CheckpointStore service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointStore)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionCheckpointRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionCheckpointRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
const pendingApprovalRepository = yield* tryRuntimePromise(
|
||||
"load ProjectionPendingApprovalRepository service",
|
||||
() => runtime.runPromise(Effect.service(ProjectionPendingApprovalRepository)),
|
||||
).pipe(Effect.orDie);
|
||||
|
||||
const scope = yield* Scope.make("sequential");
|
||||
yield* tryRuntimePromise("start OrchestrationReactor", () =>
|
||||
runtime.runPromise(reactor.start.pipe(Scope.provide(scope))),
|
||||
).pipe(Effect.orDie);
|
||||
yield* sleep(10);
|
||||
|
||||
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
|
||||
threadId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
) =>
|
||||
waitFor(
|
||||
snapshotQuery
|
||||
.getSnapshot()
|
||||
.pipe(
|
||||
Effect.map(
|
||||
(snapshot) => snapshot.threads.find((thread) => thread.id === threadId) ?? null,
|
||||
),
|
||||
),
|
||||
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
|
||||
`projected thread '${threadId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<OrchestrationThread, never>;
|
||||
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const stopAllExit = yield* Effect.exit(
|
||||
Effect.promise(() => runtime.runPromise(providerService.stopAll())),
|
||||
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): ReadonlyArray<OrchestrationEvent> => Array.from(chunk)),
|
||||
),
|
||||
(events) => events.some(predicate),
|
||||
"domain event",
|
||||
timeoutMs,
|
||||
);
|
||||
const closeScopeExit = yield* Effect.exit(
|
||||
Effect.promise(() => Effect.runPromise(Scope.close(scope, Exit.void))),
|
||||
);
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
|
||||
const failureCause = Exit.isFailure(stopAllExit)
|
||||
? stopAllExit.cause
|
||||
: Exit.isFailure(closeScopeExit)
|
||||
const waitForPendingApproval: OrchestrationIntegrationHarness["waitForPendingApproval"] = (
|
||||
requestId,
|
||||
predicate,
|
||||
timeoutMs,
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
onNone: () => null,
|
||||
onSome: (value) => ({
|
||||
status: value.status,
|
||||
decision: value.decision,
|
||||
resolvedAt: value.resolvedAt,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
(
|
||||
row,
|
||||
): row is {
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
} => row !== null && predicate(row),
|
||||
`pending approval '${requestId}'`,
|
||||
timeoutMs,
|
||||
) as Effect.Effect<
|
||||
{
|
||||
readonly status: "pending" | "resolved";
|
||||
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
|
||||
readonly resolvedAt: string | null;
|
||||
},
|
||||
never
|
||||
>;
|
||||
|
||||
let disposed = false;
|
||||
const dispose = Effect.gen(function* () {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
disposed = true;
|
||||
|
||||
const shutdown = Effect.gen(function* () {
|
||||
const closeScopeExit = yield* Effect.exit(Scope.close(scope, Exit.void));
|
||||
const disposeRuntimeExit = yield* Effect.exit(Effect.promise(() => runtime.dispose()));
|
||||
|
||||
const failureCause = Exit.isFailure(closeScopeExit)
|
||||
? closeScopeExit.cause
|
||||
: Exit.isFailure(disposeRuntimeExit)
|
||||
? disposeRuntimeExit.cause
|
||||
: null;
|
||||
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
if (failureCause) {
|
||||
return yield* Effect.failCause(failureCause);
|
||||
}
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
yield* shutdown.pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
fs.rmSync(rootDir, { recursive: true, force: true });
|
||||
}),
|
||||
),
|
||||
);
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
|
||||
return {
|
||||
rootDir,
|
||||
workspaceDir,
|
||||
dbPath,
|
||||
adapterHarness,
|
||||
engine,
|
||||
snapshotQuery,
|
||||
providerService,
|
||||
checkpointStore,
|
||||
checkpointRepository,
|
||||
pendingApprovalRepository,
|
||||
waitForThread,
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -5,11 +5,11 @@ import {
|
||||
EventId,
|
||||
ProviderApprovalDecision,
|
||||
ProviderRuntimeEvent,
|
||||
RuntimeSessionId,
|
||||
ProviderSession,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -25,13 +25,29 @@ import type {
|
||||
} from "../src/provider/Services/ProviderAdapter.ts";
|
||||
|
||||
export interface TestTurnResponse {
|
||||
readonly events: ReadonlyArray<ProviderRuntimeEvent>;
|
||||
readonly events: ReadonlyArray<FixtureProviderRuntimeEvent>;
|
||||
readonly mutateWorkspace?: (input: {
|
||||
readonly cwd: string;
|
||||
readonly turnCount: number;
|
||||
}) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
// Temporary alias while fixtures migrate to the new name.
|
||||
export type LegacyProviderRuntimeEvent = FixtureProviderRuntimeEvent;
|
||||
|
||||
interface SessionState {
|
||||
readonly session: ProviderSession;
|
||||
snapshot: ProviderThreadSnapshot;
|
||||
@@ -40,82 +56,217 @@ interface SessionState {
|
||||
readonly rollbackCalls: Array<number>;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function normalizeTurnState(value: unknown): "completed" | "failed" | "interrupted" | "cancelled" {
|
||||
if (
|
||||
value === "completed" ||
|
||||
value === "failed" ||
|
||||
value === "interrupted" ||
|
||||
value === "cancelled"
|
||||
) {
|
||||
return value;
|
||||
}
|
||||
return "completed";
|
||||
}
|
||||
|
||||
function mapRequestType(requestKind: unknown):
|
||||
| "command_execution_approval"
|
||||
| "file_change_approval"
|
||||
| "unknown" {
|
||||
if (requestKind === "command") {
|
||||
return "command_execution_approval";
|
||||
}
|
||||
if (requestKind === "file-change") {
|
||||
return "file_change_approval";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function mapItemType(toolKind: unknown): "command_execution" | "file_change" | "unknown" {
|
||||
if (toolKind === "command") {
|
||||
return "command_execution";
|
||||
}
|
||||
if (toolKind === "file-change") {
|
||||
return "file_change";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRuntimeEvent {
|
||||
const type = typeof rawEvent.type === "string" ? rawEvent.type : "";
|
||||
switch (type) {
|
||||
case "turn.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.started",
|
||||
payload: isRecord(rawEvent.payload) ? rawEvent.payload : {},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "turn.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "turn.completed",
|
||||
payload: isRecord(rawEvent.payload)
|
||||
? rawEvent.payload
|
||||
: {
|
||||
state: normalizeTurnState(rawEvent.status),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.delta":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "content.delta",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: typeof rawEvent.delta === "string" ? rawEvent.delta : "",
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "message.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: "assistant_message",
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.started":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.started",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "tool.completed":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "item.completed",
|
||||
payload: {
|
||||
itemType: mapItemType(rawEvent.toolKind),
|
||||
status: "completed",
|
||||
...(typeof rawEvent.title === "string" ? { title: rawEvent.title } : {}),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.requested":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.opened",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.detail === "string" ? { detail: rawEvent.detail } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
case "approval.resolved":
|
||||
return {
|
||||
...rawEvent,
|
||||
type: "request.resolved",
|
||||
payload: {
|
||||
requestType: mapRequestType(rawEvent.requestKind),
|
||||
...(typeof rawEvent.decision === "string" ? { decision: rawEvent.decision } : {}),
|
||||
},
|
||||
} as ProviderRuntimeEvent;
|
||||
default:
|
||||
return rawEvent as ProviderRuntimeEvent;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: "codex";
|
||||
readonly queueTurnResponse: (
|
||||
sessionId: string,
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
|
||||
readonly queueTurnResponseForNextSession: (
|
||||
response: TestTurnResponse,
|
||||
) => Effect.Effect<void, never>;
|
||||
readonly getRollbackCalls: (sessionId: string) => ReadonlyArray<number>;
|
||||
readonly getApprovalResponses: (sessionId: string) => ReadonlyArray<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly getStartCount: () => number;
|
||||
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
|
||||
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
|
||||
readonly listActiveSessionIds: () => ReadonlyArray<ThreadId>;
|
||||
readonly getApprovalResponses: (threadId: ThreadId) => ReadonlyArray<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>;
|
||||
}
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: "codex";
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
function sessionNotFound(sessionId: string): ProviderAdapterSessionNotFoundError {
|
||||
function sessionNotFound(
|
||||
provider: "codex",
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
provider: PROVIDER,
|
||||
sessionId,
|
||||
provider,
|
||||
threadId: String(threadId),
|
||||
});
|
||||
}
|
||||
|
||||
function missingSessionEffect(sessionId: string): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(sessionId));
|
||||
function missingSessionEffect(
|
||||
provider: "codex",
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
}
|
||||
|
||||
export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<string, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const approvalResponsesBySession = new Map<
|
||||
string,
|
||||
Array<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? "codex";
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
|
||||
const approvalResponsesBySession = new Map<
|
||||
ThreadId,
|
||||
Array<{
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}>
|
||||
>();
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
if (input.provider !== undefined && input.provider !== provider) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
provider,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
issue: `Expected provider '${provider}' but received '${input.provider}'.`,
|
||||
});
|
||||
}
|
||||
|
||||
sessionCount += 1;
|
||||
const sessionId = ProviderSessionId.makeUnsafe(`test-session-${sessionCount}`);
|
||||
const threadId = ProviderThreadId.makeUnsafe(`test-thread-${sessionCount}`);
|
||||
const threadId = input.threadId;
|
||||
const createdAt = nowIso();
|
||||
|
||||
const session: ProviderSession = {
|
||||
sessionId,
|
||||
provider: PROVIDER,
|
||||
provider,
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId,
|
||||
cwd: input.cwd,
|
||||
resumeCursor: input.resumeCursor ?? { threadId: String(threadId), seed: sessionCount },
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
};
|
||||
|
||||
sessions.set(sessionId, {
|
||||
sessions.set(threadId, {
|
||||
session,
|
||||
snapshot: {
|
||||
threadId,
|
||||
@@ -131,21 +282,21 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
|
||||
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const state = sessions.get(input.sessionId);
|
||||
const state = sessions.get(input.threadId);
|
||||
if (!state) {
|
||||
return yield* missingSessionEffect(input.sessionId);
|
||||
return yield* missingSessionEffect(provider, input.threadId);
|
||||
}
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = ProviderTurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
return yield* new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
provider,
|
||||
operation: "sendTurn",
|
||||
issue: `No queued turn response for session ${input.sessionId}.`,
|
||||
issue: `No queued turn response for thread ${input.threadId}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -155,20 +306,27 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
if (Object.hasOwn(rawEvent, "threadId")) {
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
}
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
if (Object.hasOwn(rawEvent, "turnId")) {
|
||||
rawEvent.turnId = turnId;
|
||||
}
|
||||
|
||||
const runtimeEvent = rawEvent as ProviderRuntimeEvent;
|
||||
if (runtimeEvent.type === "message.delta") {
|
||||
assistantDeltas.push(runtimeEvent.delta);
|
||||
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);
|
||||
@@ -206,12 +364,13 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
provider: PROVIDER,
|
||||
sessionId: input.sessionId,
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
turnId,
|
||||
status: "completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
});
|
||||
} else {
|
||||
for (const completedEvent of deferredTurnCompletedEvents) {
|
||||
@@ -226,58 +385,71 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
|
||||
sessionId,
|
||||
_turnId,
|
||||
) => (sessions.has(sessionId) ? Effect.void : missingSessionEffect(sessionId));
|
||||
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"] = (
|
||||
sessionId,
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
) =>
|
||||
sessions.has(sessionId)
|
||||
sessions.has(threadId)
|
||||
? Effect.sync(() => {
|
||||
const existing = approvalResponsesBySession.get(sessionId) ?? [];
|
||||
const existing = approvalResponsesBySession.get(threadId) ?? [];
|
||||
existing.push({
|
||||
sessionId,
|
||||
threadId,
|
||||
requestId,
|
||||
decision,
|
||||
});
|
||||
approvalResponsesBySession.set(sessionId, existing);
|
||||
approvalResponsesBySession.set(threadId, existing);
|
||||
})
|
||||
: missingSessionEffect(sessionId);
|
||||
: missingSessionEffect(provider, threadId);
|
||||
|
||||
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (sessionId) =>
|
||||
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(sessionId);
|
||||
sessions.delete(threadId);
|
||||
});
|
||||
|
||||
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
|
||||
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
|
||||
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (sessionId) =>
|
||||
Effect.succeed(sessions.has(sessionId));
|
||||
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
|
||||
Effect.succeed(sessions.has(threadId));
|
||||
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (sessionId) => {
|
||||
const state = sessions.get(sessionId);
|
||||
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(sessionId);
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
return Effect.succeed(state.snapshot);
|
||||
};
|
||||
|
||||
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
|
||||
sessionId,
|
||||
threadId,
|
||||
numTurns,
|
||||
) => {
|
||||
const state = sessions.get(sessionId);
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return missingSessionEffect(sessionId);
|
||||
return missingSessionEffect(provider, threadId);
|
||||
}
|
||||
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
provider,
|
||||
operation: "rollbackThread",
|
||||
issue: "numTurns must be an integer between 0 and current turn count.",
|
||||
}),
|
||||
@@ -301,11 +473,15 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider: PROVIDER,
|
||||
provider,
|
||||
capabilities: {
|
||||
sessionModelSwitch: "in-session",
|
||||
},
|
||||
startSession,
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
listSessions,
|
||||
hasSession,
|
||||
@@ -316,16 +492,16 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
};
|
||||
|
||||
const queueTurnResponse = (
|
||||
sessionId: string,
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
): Effect.Effect<void, ProviderAdapterSessionNotFoundError> =>
|
||||
Effect.sync(() => sessions.get(sessionId)).pipe(
|
||||
Effect.sync(() => sessions.get(threadId)).pipe(
|
||||
Effect.flatMap((state) =>
|
||||
state
|
||||
? Effect.sync(() => {
|
||||
state.queuedResponses.push(response);
|
||||
})
|
||||
: Effect.fail(sessionNotFound(sessionId)),
|
||||
: Effect.fail(sessionNotFound(provider, threadId)),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -336,22 +512,35 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
queuedResponsesForNextSession.push(response);
|
||||
});
|
||||
|
||||
const getRollbackCalls = (sessionId: string): ReadonlyArray<number> => {
|
||||
const state = sessions.get(sessionId);
|
||||
const getRollbackCalls = (threadId: ThreadId): ReadonlyArray<number> => {
|
||||
const state = sessions.get(threadId);
|
||||
if (!state) {
|
||||
return [];
|
||||
}
|
||||
return [...state.rollbackCalls];
|
||||
};
|
||||
|
||||
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 = (
|
||||
sessionId: string,
|
||||
threadId: ThreadId,
|
||||
): ReadonlyArray<{
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: ApprovalRequestId;
|
||||
readonly decision: ProviderApprovalDecision;
|
||||
}> => {
|
||||
const responses = approvalResponsesBySession.get(sessionId);
|
||||
const responses = approvalResponsesBySession.get(threadId);
|
||||
if (!responses) {
|
||||
return [];
|
||||
}
|
||||
@@ -360,9 +549,13 @@ export const makeTestProviderAdapterHarness = Effect.gen(function* () {
|
||||
|
||||
return {
|
||||
adapter,
|
||||
provider,
|
||||
queueTurnResponse,
|
||||
queueTurnResponseForNextSession,
|
||||
getStartCount,
|
||||
getRollbackCalls,
|
||||
getInterruptCalls,
|
||||
listActiveSessionIds,
|
||||
getApprovalResponses,
|
||||
} satisfies TestProviderAdapterHarness;
|
||||
});
|
||||
@@ -1,22 +1,16 @@
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
EventId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = ProviderSessionId.makeUnsafe("fixture-session");
|
||||
const THREAD_ID = ProviderThreadId.makeUnsafe("fixture-thread");
|
||||
const TURN_ID = ProviderTurnId.makeUnsafe("fixture-turn");
|
||||
const REQUEST_ID = ApprovalRequestId.makeUnsafe("req-1");
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<ProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
provider: PROVIDER,
|
||||
@@ -31,29 +25,38 @@ export const codexTurnTextFixture = [
|
||||
...baseEvent("evt-1", "2026-02-23T00:00:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-2", "2026-02-23T00:00:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "I will make a small update.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "I will make a small update.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-3", "2026-02-23T00:00:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Done.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Done.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-4", "2026-02-23T00:00:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnToolFixture = [
|
||||
{
|
||||
@@ -61,40 +64,51 @@ export const codexTurnToolFixture = [
|
||||
...baseEvent("evt-11", "2026-02-23T00:01:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
type: "item.started",
|
||||
...baseEvent("evt-12", "2026-02-23T00:01:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "tool.completed",
|
||||
type: "item.completed",
|
||||
...baseEvent("evt-13", "2026-02-23T00:01:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: "Command run",
|
||||
detail: "echo integration",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-14", "2026-02-23T00:01:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Applied the requested edit.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Applied the requested edit.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-15", "2026-02-23T00:01:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
|
||||
export const codexTurnApprovalFixture = [
|
||||
{
|
||||
@@ -102,37 +116,47 @@ export const codexTurnApprovalFixture = [
|
||||
...baseEvent("evt-21", "2026-02-23T00:02:00.000Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
payload: {},
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
type: "request.opened",
|
||||
...baseEvent("evt-22", "2026-02-23T00:02:00.100Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
detail: "Please approve command",
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
detail: "Please approve command",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "approval.resolved",
|
||||
type: "request.resolved",
|
||||
...baseEvent("evt-23", "2026-02-23T00:02:00.200Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
requestId: REQUEST_ID,
|
||||
requestKind: "command",
|
||||
decision: "accept",
|
||||
payload: {
|
||||
requestType: "command_execution_approval",
|
||||
decision: "accept",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...baseEvent("evt-24", "2026-02-23T00:02:00.300Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
delta: "Approval received and command executed.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Approval received and command executed.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent("evt-25", "2026-02-23T00:02:00.400Z"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: TURN_ID,
|
||||
status: "completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
},
|
||||
},
|
||||
] satisfies ReadonlyArray<ProviderRuntimeEvent>;
|
||||
] satisfies ReadonlyArray<LegacyProviderRuntimeEvent>;
|
||||
@@ -4,12 +4,10 @@ import path from "node:path";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
@@ -27,19 +25,14 @@ import { checkpointRefForThreadTurn } from "../src/checkpointing/Utils.ts";
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_SESSION_ID = asProviderSessionId("fixture-session");
|
||||
const FIXTURE_THREAD_ID = asProviderThreadId("fixture-thread");
|
||||
const FIXTURE_TURN_ID = asProviderTurnId("fixture-turn");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = "codex";
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -76,18 +69,30 @@ function waitForSync<A>(
|
||||
});
|
||||
}
|
||||
|
||||
function runtimeBase(eventId: string, createdAt: string) {
|
||||
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
|
||||
return {
|
||||
eventId: asEventId(eventId),
|
||||
provider: "codex" as const,
|
||||
sessionId: FIXTURE_SESSION_ID,
|
||||
provider,
|
||||
createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
function withHarness<A, E>(use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>) {
|
||||
function withHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
provider: IntegrationProvider = "codex",
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness,
|
||||
makeOrchestrationIntegrationHarness({ provider }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
}
|
||||
|
||||
function withRealCodexHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
);
|
||||
@@ -114,6 +119,8 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: harness.workspaceDir,
|
||||
createdAt,
|
||||
@@ -125,6 +132,7 @@ const startTurn = (input: {
|
||||
readonly commandId: string;
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
readonly provider?: IntegrationProvider;
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -136,8 +144,9 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
@@ -151,27 +160,27 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-single-1", "2026-02-24T10:00:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-single-2", "2026-02-24T10:00:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Single turn response.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-single-3", "2026-02-24T10:00:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession(turnResponse);
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession(turnResponse);
|
||||
yield* startTurn({
|
||||
harness,
|
||||
commandId: "cmd-turn-start-single",
|
||||
@@ -211,23 +220,112 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
|
||||
),
|
||||
);
|
||||
|
||||
it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
"keeps the same Codex provider thread across runtime mode switches",
|
||||
() =>
|
||||
withRealCodexHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = nowIso();
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: harness.workspaceDir,
|
||||
createdAt,
|
||||
});
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-1"),
|
||||
role: "user",
|
||||
text: "Reply with exactly ALPHA.",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const firstThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session.providerName === "codex" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.streaming === false,
|
||||
),
|
||||
180_000,
|
||||
);
|
||||
assert.equal(firstThread.session?.threadId, "thread-1");
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-2"),
|
||||
role: "user",
|
||||
text: "Reply with exactly BETA.",
|
||||
attachments: [],
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
|
||||
const secondThread = yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) =>
|
||||
entry.session?.status === "ready" &&
|
||||
entry.session.providerName === "codex" &&
|
||||
entry.session.runtimeMode === "approval-required" &&
|
||||
entry.messages.some(
|
||||
(message) => message.role === "assistant" && message.text.includes("BETA"),
|
||||
),
|
||||
180_000,
|
||||
);
|
||||
assert.equal(secondThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
withHarness((harness) =>
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-multi-1", "2026-02-24T10:01:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-multi-2", "2026-02-24T10:01:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -236,7 +334,7 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-multi-3", "2026-02-24T10:01:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -245,14 +343,14 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-multi-4", "2026-02-24T10:01:00.300Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-5", "2026-02-24T10:01:00.400Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -270,35 +368,30 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
text: "Make first edit",
|
||||
});
|
||||
|
||||
const firstTurnThread = yield* harness.waitForThread(
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.checkpoints.length === 1 && entry.session?.providerSessionId !== null,
|
||||
(entry) => entry.checkpoints.length === 1 && entry.session?.threadId === "thread-1",
|
||||
);
|
||||
const sessionId = firstTurnThread.session?.providerSessionId;
|
||||
assert.equal(sessionId !== null, true);
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
|
||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-multi-6", "2026-02-24T10:02:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-multi-7", "2026-02-24T10:02:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-multi-8", "2026-02-24T10:02:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -380,18 +473,18 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-approval-1", "2026-02-24T10:03:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase("evt-approval-2", "2026-02-24T10:03:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
requestKind: "command",
|
||||
@@ -400,7 +493,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-approval-3", "2026-02-24T10:03:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -444,9 +537,8 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
assert.equal(resolvedRow.status, "resolved");
|
||||
assert.equal(resolvedRow.decision, "accept");
|
||||
|
||||
const providerSessionId = thread.session?.providerSessionId ?? "test-session-1";
|
||||
const approvalResponses = yield* waitForSync(
|
||||
() => harness.adapterHarness.getApprovalResponses(providerSessionId),
|
||||
() => harness.adapterHarness!.getApprovalResponses(THREAD_ID),
|
||||
(responses) => responses.length === 1,
|
||||
"provider approval response",
|
||||
);
|
||||
@@ -462,35 +554,42 @@ it.live("records failed turn runtime state and checkpoint status as error", () =
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-failure-1", "2026-02-24T10:04:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
type: "content.delta",
|
||||
...runtimeBase("evt-failure-2", "2026-02-24T10:04:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Partial output before failure.\n",
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta: "Partial output before failure.\n",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "runtime.error",
|
||||
...runtimeBase("evt-failure-3", "2026-02-24T10:04:00.200Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
message: "Sandbox command failed.",
|
||||
payload: {
|
||||
message: "Sandbox command failed.",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-failure-4", "2026-02-24T10:04:00.300Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "failed",
|
||||
errorMessage: "Sandbox command failed.",
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: "Sandbox command failed.",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
@@ -534,18 +633,18 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
Effect.gen(function* () {
|
||||
yield* seedProjectAndThread(harness);
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession({
|
||||
yield* harness.adapterHarness!.queueTurnResponseForNextSession({
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-revert-1", "2026-02-24T10:05:00.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-revert-1-tool-started", "2026-02-24T10:05:00.025Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -554,7 +653,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-revert-1-tool-completed", "2026-02-24T10:05:00.035Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -563,14 +662,14 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-revert-1a", "2026-02-24T10:05:00.050Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v2.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-2", "2026-02-24T10:05:00.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -587,28 +686,23 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
text: "First edit",
|
||||
});
|
||||
|
||||
const firstTurnThread = yield* harness.waitForThread(
|
||||
yield* harness.waitForThread(
|
||||
THREAD_ID,
|
||||
(entry) => entry.session?.providerSessionId !== null && entry.checkpoints.length === 1,
|
||||
(entry) => entry.session?.threadId === "thread-1" && entry.checkpoints.length === 1,
|
||||
);
|
||||
const sessionId = firstTurnThread.session?.providerSessionId;
|
||||
assert.equal(sessionId !== null, true);
|
||||
if (!sessionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* harness.adapterHarness.queueTurnResponse(sessionId, {
|
||||
yield* harness.adapterHarness!.queueTurnResponse(THREAD_ID, {
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase("evt-revert-3", "2026-02-24T10:05:01.000Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "tool.started",
|
||||
...runtimeBase("evt-revert-3-tool-started", "2026-02-24T10:05:01.025Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -617,7 +711,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "tool.completed",
|
||||
...runtimeBase("evt-revert-3-tool-completed", "2026-02-24T10:05:01.035Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
toolKind: "command",
|
||||
title: "Edit file",
|
||||
@@ -626,14 +720,14 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase("evt-revert-3a", "2026-02-24T10:05:01.050Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Updated README to v3.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase("evt-revert-4", "2026-02-24T10:05:01.100Z"),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
},
|
||||
@@ -702,7 +796,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
gitRefExists(harness.workspaceDir, checkpointRefForThreadTurn(THREAD_ID, 2)),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness.getRollbackCalls(sessionId), [1]);
|
||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||
|
||||
const checkpointRows = yield* harness.checkpointRepository.listByThreadId({
|
||||
threadId: THREAD_ID,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ProviderRuntimeEvent, ProviderSessionId } from "@t3tools/contracts";
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
ProviderService,
|
||||
type ProviderServiceShape,
|
||||
} from "../src/provider/Services/ProviderService.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";
|
||||
|
||||
@@ -42,7 +43,7 @@ interface IntegrationFixture {
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
@@ -59,6 +60,7 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
AnalyticsService.layerTest,
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
@@ -93,18 +95,18 @@ const collectEventsDuring = <A, E, R>(
|
||||
const runTurn = (input: {
|
||||
readonly provider: ProviderServiceShape;
|
||||
readonly harness: TestProviderAdapterHarness;
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly userText: string;
|
||||
readonly response: TestTurnResponse;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* input.harness.queueTurnResponse(input.sessionId, input.response);
|
||||
yield* input.harness.queueTurnResponse(input.threadId, input.response);
|
||||
|
||||
return yield* collectEventsDuring(
|
||||
input.provider.streamEvents,
|
||||
input.response.events.length,
|
||||
input.provider.sendTurn({
|
||||
sessionId: input.sessionId,
|
||||
threadId: input.threadId,
|
||||
input: input.userText,
|
||||
attachments: [],
|
||||
}),
|
||||
@@ -120,8 +122,10 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -129,7 +133,7 @@ it.effect("replays typed runtime fixture events", () =>
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "hello",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
@@ -153,8 +157,10 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -162,7 +168,7 @@ it.effect("replays file-changing fixture turn events", () =>
|
||||
const observedEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "make a small change",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -190,8 +196,10 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -199,7 +207,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -215,7 +223,7 @@ it.effect("runs multi-turn tool/approval flow", () =>
|
||||
const secondTurnEvents = yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
@@ -242,8 +250,10 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
const session = yield* provider.startSession(
|
||||
ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
{
|
||||
threadId: ThreadId.makeUnsafe("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
},
|
||||
);
|
||||
assert.equal((session.threadId ?? "").length > 0, true);
|
||||
@@ -251,7 +261,7 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 1",
|
||||
response: {
|
||||
events: codexTurnToolFixture,
|
||||
@@ -263,7 +273,7 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
userText: "turn 2 approval",
|
||||
response: {
|
||||
events: codexTurnApprovalFixture,
|
||||
@@ -273,11 +283,11 @@ it.effect("rolls back provider conversation state only", () =>
|
||||
});
|
||||
|
||||
yield* provider.rollbackConversation({
|
||||
sessionId: session.sessionId,
|
||||
threadId: session.threadId,
|
||||
numTurns: 1,
|
||||
});
|
||||
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.sessionId);
|
||||
const rollbackCalls = fixture.harness.getRollbackCalls(session.threadId);
|
||||
assert.deepEqual(rollbackCalls, [1]);
|
||||
|
||||
const readme = yield* readFileString(join(fixture.cwd, "README.md"));
|
||||
|
||||
+18
-10
@@ -1,6 +1,11 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.0-alpha.4",
|
||||
"version": "0.0.0-alpha.22",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/pingdotgg/t3code",
|
||||
"directory": "apps/server"
|
||||
},
|
||||
"bin": {
|
||||
"t3": "./dist/index.mjs"
|
||||
},
|
||||
@@ -8,10 +13,9 @@
|
||||
"dist"
|
||||
],
|
||||
"type": "module",
|
||||
"main": "./dist/index.mjs",
|
||||
"scripts": {
|
||||
"dev": "VITE_DEV_SERVER_URL=${VITE_DEV_SERVER_URL:-http://localhost:5733} bun run src/index.ts",
|
||||
"build": "tsdown && node scripts/bundle-client.ts",
|
||||
"dev": "bun run src/index.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"start": "node dist/index.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
@@ -27,15 +31,19 @@
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@effect/language-service": "0.75.1",
|
||||
"@effect/language-service": "catalog:",
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "^1.3.9",
|
||||
"@types/node": "^24.10.13",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"@types/ws": "^8.5.13",
|
||||
"tsdown": "^0.20.3",
|
||||
"typescript": "^5.7.3",
|
||||
"vitest": "^4.0.0"
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.13 || ^23.4 || >=24.10"
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
/**
|
||||
* Copies the built web app into dist/client/ so the published npm package
|
||||
* includes the web UI. This runs as a post-build step.
|
||||
*/
|
||||
import * as fs from "node:fs";
|
||||
import * as path from "node:path";
|
||||
|
||||
const webDist = path.resolve(import.meta.dirname, "../../web/dist");
|
||||
const target = path.resolve(import.meta.dirname, "../dist/client");
|
||||
|
||||
if (!fs.existsSync(webDist)) {
|
||||
console.log(
|
||||
"⚠ Web dist not found — skipping client bundle. Run `bun run --cwd apps/web build` first.",
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
fs.cpSync(webDist, target, { recursive: true });
|
||||
console.log("✓ Bundled web app into dist/client");
|
||||
@@ -0,0 +1,261 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
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 { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
const RepoRoot = Effect.service(Path.Path).pipe(
|
||||
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
|
||||
);
|
||||
|
||||
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(command);
|
||||
const exitCode = yield* child.exitCode;
|
||||
|
||||
if (exitCode !== 0) {
|
||||
return yield* new CliError({
|
||||
message: `Command exited with non-zero exit code (${exitCode})`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
interface PublishIconBackup {
|
||||
readonly targetPath: string;
|
||||
readonly backupPath: string;
|
||||
}
|
||||
|
||||
const applyPublishIconOverrides = Effect.fn("applyPublishIconOverrides")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const backups: PublishIconBackup[] = [];
|
||||
|
||||
for (const override of PUBLISH_ICON_OVERRIDES) {
|
||||
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
const backupPath = `${targetPath}.publish-bak`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing publish icon target: ${targetPath}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(targetPath, backupPath);
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
backups.push({ targetPath, backupPath });
|
||||
}
|
||||
|
||||
yield* Effect.log("[cli] Applied publish icon overrides to dist/client");
|
||||
return backups as ReadonlyArray<PublishIconBackup>;
|
||||
});
|
||||
|
||||
const restorePublishIconOverrides = Effect.fn("restorePublishIconOverrides")(function* (
|
||||
backups: ReadonlyArray<PublishIconBackup>,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const backup of backups) {
|
||||
if (!(yield* fs.exists(backup.backupPath))) {
|
||||
continue;
|
||||
}
|
||||
yield* fs.rename(backup.backupPath, backup.targetPath);
|
||||
}
|
||||
});
|
||||
|
||||
const applyDevelopmentIconOverrides = Effect.fn("applyDevelopmentIconOverrides")(function* (
|
||||
repoRoot: string,
|
||||
serverDir: string,
|
||||
) {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
|
||||
for (const override of DEVELOPMENT_ICON_OVERRIDES) {
|
||||
const sourcePath = path.join(repoRoot, override.sourceRelativePath);
|
||||
const targetPath = path.join(serverDir, override.targetRelativePath);
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon source: ${sourcePath}`,
|
||||
});
|
||||
}
|
||||
if (!(yield* fs.exists(targetPath))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing development icon target: ${targetPath}. Build web first.`,
|
||||
});
|
||||
}
|
||||
|
||||
yield* fs.copyFile(sourcePath, targetPath);
|
||||
}
|
||||
|
||||
yield* Effect.log("[cli] Applied development icon overrides to dist/client");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// build subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const buildCmd = Command.make(
|
||||
"build",
|
||||
{
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
const clientTarget = path.join(serverDir, "dist/client");
|
||||
|
||||
if (yield* fs.exists(webDist)) {
|
||||
yield* fs.copy(webDist, clientTarget);
|
||||
yield* applyDevelopmentIconOverrides(repoRoot, serverDir);
|
||||
yield* Effect.log("[cli] Bundled web app into dist/client");
|
||||
} else {
|
||||
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
|
||||
}
|
||||
}),
|
||||
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// publish subcommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const publishCmd = Command.make(
|
||||
"publish",
|
||||
{
|
||||
tag: Flag.string("tag").pipe(Flag.withDefault("latest")),
|
||||
access: Flag.string("access").pipe(Flag.withDefault("public")),
|
||||
appVersion: Flag.string("app-version").pipe(Flag.optional),
|
||||
provenance: Flag.boolean("provenance").pipe(Flag.withDefault(false)),
|
||||
dryRun: Flag.boolean("dry-run").pipe(Flag.withDefault(false)),
|
||||
verbose: Flag.boolean("verbose").pipe(Flag.withDefault(false)),
|
||||
},
|
||||
(config) =>
|
||||
Effect.gen(function* () {
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const repoRoot = yield* RepoRoot;
|
||||
const serverDir = path.join(repoRoot, "apps/server");
|
||||
const packageJsonPath = path.join(serverDir, "package.json");
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/index.mjs", "dist/client/index.html"]) {
|
||||
const abs = path.join(serverDir, relPath);
|
||||
if (!(yield* fs.exists(abs))) {
|
||||
return yield* new CliError({
|
||||
message: `Missing build asset: ${abs}. Run the build subcommand first.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog: deps, strip devDependencies/scripts
|
||||
Effect.gen(function* () {
|
||||
// Resolve catalog dependencies before any file mutations. If this throws,
|
||||
// acquire fails and no release hook runs, so filesystem must still be untouched.
|
||||
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
type: serverPackageJson.type,
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: serverPackageJson.dependencies as Record<string, unknown>,
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
|
||||
const original = yield* fs.readFileString(packageJsonPath);
|
||||
yield* fs.writeFileString(backupPath, original);
|
||||
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
}),
|
||||
// Use: npm publish
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["publish", "--access", config.access, "--tag", config.tag];
|
||||
if (config.provenance) args.push("--provenance");
|
||||
if (config.dryRun) args.push("--dry-run");
|
||||
|
||||
yield* Effect.log(`[cli] Running: npm ${args.join(" ")}`);
|
||||
yield* runCommand(
|
||||
ChildProcess.make("npm", [...args], {
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
}),
|
||||
);
|
||||
}),
|
||||
// Release: restore
|
||||
(resource: { readonly iconBackups: ReadonlyArray<PublishIconBackup> }) =>
|
||||
Effect.gen(function* () {
|
||||
yield* restorePublishIconOverrides(resource.iconBackups).pipe(
|
||||
Effect.catch((error) =>
|
||||
Effect.logError(
|
||||
`[cli] Failed to restore publish icon overrides: ${String(error)}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* fs.rename(backupPath, packageJsonPath);
|
||||
if (config.verbose) yield* Effect.log("[cli] Restored original package.json");
|
||||
}),
|
||||
);
|
||||
}),
|
||||
).pipe(Command.withDescription("Publish the server package to npm."));
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// root command
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const cli = Command.make("cli").pipe(
|
||||
Command.withDescription("T3 server build & publish CLI."),
|
||||
Command.withSubcommands([buildCmd, publishCmd]),
|
||||
);
|
||||
|
||||
Command.run(cli, { version: "0.0.0" }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide([Logger.layer([Logger.consolePretty()]), NodeServices.layer]),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -43,6 +44,8 @@ function makeSnapshot(input: {
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: input.worktreePath,
|
||||
latestTurn: {
|
||||
@@ -58,6 +61,7 @@ function makeSnapshot(input: {
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
|
||||
@@ -1,26 +1,42 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { ApprovalRequestId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
buildCodexInitializeParams,
|
||||
CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
CodexAppServerManager,
|
||||
classifyCodexStderrLine,
|
||||
isRecoverableThreadResumeError,
|
||||
normalizeCodexModelSlug,
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
runtimeMode: "full-access",
|
||||
model: "gpt-5.3-codex",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
account: {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
},
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
@@ -50,10 +66,12 @@ function createThreadControlHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
runtimeMode: "full-access",
|
||||
model: "gpt-5.3-codex",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
@@ -76,6 +94,47 @@ function createThreadControlHarness() {
|
||||
return { manager, context, requireSession, sendRequest, updateSession };
|
||||
}
|
||||
|
||||
function createPendingUserInputHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: "thread_1",
|
||||
runtimeMode: "full-access",
|
||||
model: "gpt-5.3-codex",
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
pendingUserInputs: new Map([
|
||||
[
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
jsonRpcId: 42,
|
||||
threadId: asThreadId("thread_1"),
|
||||
},
|
||||
],
|
||||
]),
|
||||
};
|
||||
|
||||
const requireSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as { requireSession: (sessionId: string) => unknown },
|
||||
"requireSession",
|
||||
)
|
||||
.mockReturnValue(context);
|
||||
const writeMessage = vi
|
||||
.spyOn(manager as unknown as { writeMessage: (...args: unknown[]) => void }, "writeMessage")
|
||||
.mockImplementation(() => {});
|
||||
const emitEvent = vi
|
||||
.spyOn(manager as unknown as { emitEvent: (...args: unknown[]) => void }, "emitEvent")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
return { manager, context, requireSession, writeMessage, emitEvent };
|
||||
}
|
||||
|
||||
describe("classifyCodexStderrLine", () => {
|
||||
it("ignores empty lines", () => {
|
||||
expect(classifyCodexStderrLine(" ")).toBeNull();
|
||||
@@ -146,7 +205,84 @@ describe("isRecoverableThreadResumeError", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("readCodexAccountSnapshot", () => {
|
||||
it("disables spark for chatgpt plus accounts", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "chatgpt",
|
||||
email: "[email protected]",
|
||||
planType: "plus",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "chatgpt",
|
||||
planType: "plus",
|
||||
sparkEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps spark enabled for chatgpt pro accounts", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "chatgpt",
|
||||
email: "[email protected]",
|
||||
planType: "pro",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "chatgpt",
|
||||
planType: "pro",
|
||||
sparkEnabled: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps spark enabled for api key accounts", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "apiKey",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCodexModelForAccount", () => {
|
||||
it("falls back from spark to default for unsupported chatgpt plans", () => {
|
||||
expect(
|
||||
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
||||
type: "chatgpt",
|
||||
planType: "plus",
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
).toBe("gpt-5.3-codex");
|
||||
});
|
||||
|
||||
it("keeps spark for supported plans", () => {
|
||||
expect(
|
||||
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
||||
type: "chatgpt",
|
||||
planType: "pro",
|
||||
sparkEnabled: true,
|
||||
}),
|
||||
).toBe("gpt-5.3-codex-spark");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
it("enables Codex experimental api capabilities during initialize", () => {
|
||||
expect(buildCodexInitializeParams()).toEqual({
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("emits session/startFailed when resolving cwd throws before process launch", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const events: Array<{ method: string; kind: string; message?: string }> = [];
|
||||
@@ -164,7 +300,9 @@ describe("startSession", () => {
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
expect(events).toHaveLength(1);
|
||||
@@ -186,7 +324,7 @@ describe("sendTurn", () => {
|
||||
createSendTurnHarness();
|
||||
|
||||
const result = await manager.sendTurn({
|
||||
sessionId: asSessionId("sess_1"),
|
||||
threadId: asThreadId("thread_1"),
|
||||
input: "Inspect this image",
|
||||
attachments: [
|
||||
{
|
||||
@@ -195,17 +333,16 @@ describe("sendTurn", () => {
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3",
|
||||
serviceTier: "fast",
|
||||
effort: "high",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
threadId: "thread_1",
|
||||
turnId: "turn_1",
|
||||
resumeCursor: {
|
||||
threadId: "thread_1",
|
||||
},
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
});
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
@@ -220,14 +357,13 @@ describe("sendTurn", () => {
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
serviceTier: "fast",
|
||||
effort: "high",
|
||||
});
|
||||
expect(updateSession).toHaveBeenCalledWith(context, {
|
||||
status: "running",
|
||||
activeTurnId: "turn_1",
|
||||
resumeCursor: {
|
||||
threadId: "thread_1",
|
||||
},
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -235,7 +371,7 @@ describe("sendTurn", () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
sessionId: asSessionId("sess_1"),
|
||||
threadId: asThreadId("thread_1"),
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
@@ -252,6 +388,98 @@ describe("sendTurn", () => {
|
||||
url: "data:image/png;base64,BBBB",
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
});
|
||||
});
|
||||
|
||||
it("passes Codex plan mode as a collaboration preset on turn/start", async () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
input: "Plan the work",
|
||||
interactionMode: "plan",
|
||||
});
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Plan the work",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
collaborationMode: {
|
||||
mode: "plan",
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("passes Codex default mode as a collaboration preset on turn/start", async () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
input: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
|
||||
interactionMode: "default",
|
||||
});
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "PLEASE IMPLEMENT THIS PLAN:\n- step 1",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
model: "gpt-5.3-codex",
|
||||
collaborationMode: {
|
||||
mode: "default",
|
||||
settings: {
|
||||
model: "gpt-5.3-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_DEFAULT_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the session model when interaction mode is set without an explicit model", async () => {
|
||||
const { manager, context, sendRequest } = createSendTurnHarness();
|
||||
context.session.model = "gpt-5.2-codex";
|
||||
|
||||
await manager.sendTurn({
|
||||
threadId: asThreadId("thread_1"),
|
||||
input: "Plan this with my current session model",
|
||||
interactionMode: "plan",
|
||||
});
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "turn/start", {
|
||||
threadId: "thread_1",
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Plan this with my current session model",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
model: "gpt-5.2-codex",
|
||||
collaborationMode: {
|
||||
mode: "plan",
|
||||
settings: {
|
||||
model: "gpt-5.2-codex",
|
||||
reasoning_effort: "medium",
|
||||
developer_instructions: CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -260,7 +488,7 @@ describe("sendTurn", () => {
|
||||
|
||||
await expect(
|
||||
manager.sendTurn({
|
||||
sessionId: asSessionId("sess_1"),
|
||||
threadId: asThreadId("thread_1"),
|
||||
}),
|
||||
).rejects.toThrow("Turn input must include text or attachments.");
|
||||
});
|
||||
@@ -281,9 +509,9 @@ describe("thread checkpoint control", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asSessionId("sess_1"));
|
||||
const result = await manager.readThread(asThreadId("thread_1"));
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("sess_1");
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
includeTurns: true,
|
||||
@@ -311,7 +539,7 @@ describe("thread checkpoint control", () => {
|
||||
],
|
||||
});
|
||||
|
||||
const result = await manager.readThread(asSessionId("sess_1"));
|
||||
const result = await manager.readThread(asThreadId("thread_1"));
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/read", {
|
||||
threadId: "thread_1",
|
||||
@@ -337,7 +565,7 @@ describe("thread checkpoint control", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await manager.rollbackThread(asSessionId("sess_1"), 2);
|
||||
const result = await manager.rollbackThread(asThreadId("thread_1"), 2);
|
||||
|
||||
expect(sendRequest).toHaveBeenCalledWith(context, "thread/rollback", {
|
||||
threadId: "thread_1",
|
||||
@@ -353,3 +581,203 @@ describe("thread checkpoint control", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("respondToUserInput", () => {
|
||||
it("serializes canonical answers to Codex native answer objects", async () => {
|
||||
const { manager, context, requireSession, writeMessage, emitEvent } =
|
||||
createPendingUserInputHarness();
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
},
|
||||
);
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(writeMessage).toHaveBeenCalledWith(context, {
|
||||
id: 42,
|
||||
result: {
|
||||
answers: {
|
||||
scope: { answers: ["All request methods"] },
|
||||
compat: { answers: ["Keep current envelope"] },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "item/tool/requestUserInput/answered",
|
||||
payload: {
|
||||
requestId: "req-user-input-1",
|
||||
answers: {
|
||||
scope: { answers: ["All request methods"] },
|
||||
compat: { answers: ["Keep current envelope"] },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves explicit empty multi-select answers", async () => {
|
||||
const { manager, context, requireSession, writeMessage, emitEvent } =
|
||||
createPendingUserInputHarness();
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: [],
|
||||
},
|
||||
);
|
||||
|
||||
expect(requireSession).toHaveBeenCalledWith("thread_1");
|
||||
expect(writeMessage).toHaveBeenCalledWith(context, {
|
||||
id: 42,
|
||||
result: {
|
||||
answers: {
|
||||
scope: { answers: [] },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(emitEvent).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
method: "item/tool/requestUserInput/answered",
|
||||
payload: {
|
||||
requestId: "req-user-input-1",
|
||||
answers: {
|
||||
scope: { answers: [] },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("tracks file-read approval requests with the correct method", () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const context = {
|
||||
session: {
|
||||
sessionId: "sess_1",
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: asThreadId("thread_1"),
|
||||
resumeCursor: { threadId: "thread_1" },
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
pendingApprovals: new Map(),
|
||||
pendingUserInputs: new Map(),
|
||||
};
|
||||
type ApprovalRequestContext = {
|
||||
session: typeof context.session;
|
||||
pendingApprovals: typeof context.pendingApprovals;
|
||||
pendingUserInputs: typeof context.pendingUserInputs;
|
||||
};
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
handleServerRequest: (
|
||||
context: ApprovalRequestContext,
|
||||
request: Record<string, unknown>,
|
||||
) => void;
|
||||
}
|
||||
).handleServerRequest(context, {
|
||||
jsonrpc: "2.0",
|
||||
id: 42,
|
||||
method: "item/fileRead/requestApproval",
|
||||
params: {},
|
||||
});
|
||||
|
||||
const request = Array.from(context.pendingApprovals.values())[0];
|
||||
expect(request?.requestKind).toBe("file-read");
|
||||
expect(request?.method).toBe("item/fileRead/requestApproval");
|
||||
});
|
||||
});
|
||||
|
||||
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");
|
||||
|
||||
const manager = new CodexAppServerManager();
|
||||
|
||||
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()}`,
|
||||
});
|
||||
|
||||
expect(firstTurn.threadId).toBe(firstSession.threadId);
|
||||
|
||||
await vi.waitFor(async () => {
|
||||
const snapshot = await manager.readThread(firstSession.threadId);
|
||||
expect(snapshot.turns.length).toBeGreaterThan(0);
|
||||
}, { timeout: 120_000, interval: 1_000 });
|
||||
|
||||
const firstSnapshot = await manager.readThread(firstSession.threadId);
|
||||
const originalThreadId = firstSnapshot.threadId;
|
||||
const originalTurnCount = firstSnapshot.turns.length;
|
||||
|
||||
manager.stopSession(firstSession.threadId);
|
||||
|
||||
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);
|
||||
|
||||
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 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,
|
||||
);
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,13 +1,12 @@
|
||||
/**
|
||||
* ServerConfig and NetService - Runtime configuration services.
|
||||
* ServerConfig - Runtime configuration services.
|
||||
*
|
||||
* Defines process-level server configuration and networking helpers used by
|
||||
* startup and runtime layers.
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import * as Net from "node:net";
|
||||
import { Data, Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
@@ -60,68 +59,6 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
|
||||
);
|
||||
}
|
||||
|
||||
// Helpers
|
||||
|
||||
export class NetError extends Data.TaggedError("NetError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
}> {}
|
||||
|
||||
/**
|
||||
* NetServiceShape - Networking helper operations used during startup.
|
||||
*/
|
||||
export interface NetServiceShape {
|
||||
/**
|
||||
* Resolve an available listening port, preferring the provided port first.
|
||||
*
|
||||
* Falls back to an ephemeral OS-assigned port when the preferred port is in use.
|
||||
*/
|
||||
readonly findAvailablePort: (preferred: number) => Effect.Effect<number, NetError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* NetService - Service tag for startup networking helpers.
|
||||
*/
|
||||
export class NetService extends ServiceMap.Service<NetService, NetServiceShape>()(
|
||||
"t3/config/NetService",
|
||||
) {
|
||||
static readonly layer = Layer.succeed(NetService, {
|
||||
findAvailablePort: (preferred) =>
|
||||
Effect.callback<number, NetError>((resume) => {
|
||||
let fallbackServer: Net.Server | null = null;
|
||||
const server = Net.createServer();
|
||||
server.listen(preferred, () => {
|
||||
server.close(() => resume(Effect.succeed(preferred)));
|
||||
});
|
||||
server.on("error", () => {
|
||||
const fallback = Net.createServer();
|
||||
fallback.listen(0, () => {
|
||||
const addr = fallback.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
fallback.close(() => {
|
||||
resume(
|
||||
port > 0
|
||||
? Effect.succeed(port)
|
||||
: Effect.fail(new NetError({ message: "Could not find an available port." })),
|
||||
);
|
||||
});
|
||||
});
|
||||
fallback.on("error", (cause) => {
|
||||
resume(
|
||||
Effect.fail(new NetError({ message: "Failed to find an available port", cause })),
|
||||
);
|
||||
});
|
||||
fallbackServer = fallback;
|
||||
});
|
||||
|
||||
return Effect.sync(() => {
|
||||
server.close();
|
||||
fallbackServer?.close();
|
||||
});
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
export const resolveStaticDir = Effect.fn(function* () {
|
||||
const { join, resolve } = yield* Path.Path;
|
||||
const { exists } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -189,7 +189,7 @@ function withFakeCodexEnv<A, E, R>(
|
||||
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages", () =>
|
||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
@@ -197,6 +197,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
" Add important change to the system with too much detail and a trailing period.\nsecondary line",
|
||||
body: "\n- added migration\n- updated tests\n",
|
||||
}),
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
@@ -211,6 +212,34 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||
expect(generated.subject.endsWith(".")).toBe(false);
|
||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||
expect(generated.branch).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates commit message with branch when includeBranch is true", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
branch: "fix/important-system-change",
|
||||
}),
|
||||
stdinMustContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
includeBranch: true,
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -3,6 +3,8 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
@@ -93,24 +95,6 @@ function sanitizePrTitle(raw: string): string {
|
||||
return "Update project changes";
|
||||
}
|
||||
|
||||
function sanitizeBranchName(raw: string): string {
|
||||
const normalized = raw
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/['"`]/g, "")
|
||||
.replace(/^[./\s_-]+|[./\s_-]+$/g, "");
|
||||
|
||||
const branchFragment = normalized
|
||||
.replace(/[^a-z0-9/_-]+/g, "-")
|
||||
.replace(/\/+/g, "/")
|
||||
.replace(/-+/g, "-")
|
||||
.replace(/^[./_-]+|[./_-]+$/g, "")
|
||||
.slice(0, 64)
|
||||
.replace(/[./_-]+$/g, "");
|
||||
|
||||
return branchFragment.length > 0 ? branchFragment : "update";
|
||||
}
|
||||
|
||||
const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -240,6 +224,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
],
|
||||
{
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
},
|
||||
@@ -328,12 +313,19 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
|
||||
const prompt = [
|
||||
"You write concise git commit messages.",
|
||||
"Return a JSON object with keys: subject, body.",
|
||||
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)"}`,
|
||||
@@ -345,20 +337,31 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
limitSection(input.stagedPatch, 40_000),
|
||||
].join("\n");
|
||||
|
||||
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: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
}),
|
||||
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,
|
||||
),
|
||||
);
|
||||
@@ -408,7 +411,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
|
||||
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
|
||||
return Effect.gen(function* () {
|
||||
const { imagePaths } = yield* materializeImageAttachments("generateBranchName", input.attachments);
|
||||
const { imagePaths } = yield* materializeImageAttachments(
|
||||
"generateBranchName",
|
||||
input.attachments,
|
||||
);
|
||||
const attachmentLines = (input.attachments ?? []).map(
|
||||
(attachment) =>
|
||||
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
|
||||
@@ -446,7 +452,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchName(generated.branch),
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -110,6 +110,7 @@ const makeIsolatedGitCore = (gitService: GitServiceShape) =>
|
||||
createBranch: (input) => core.createBranch(input),
|
||||
checkoutBranch: (input) => core.checkoutBranch(input),
|
||||
initRepo: (input) => core.initRepo(input),
|
||||
listLocalBranchNames: (cwd) => core.listLocalBranchNames(cwd),
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1172,6 +1172,20 @@ const makeGitCore = Effect.gen(function* () {
|
||||
fallbackErrorMessage: "git init failed",
|
||||
}).pipe(Effect.asVoid);
|
||||
|
||||
const listLocalBranchNames: GitCoreShape["listLocalBranchNames"] = (cwd) =>
|
||||
runGitStdout("GitCore.listLocalBranchNames", cwd, [
|
||||
"branch",
|
||||
"--list",
|
||||
"--format=%(refname:short)",
|
||||
]).pipe(
|
||||
Effect.map((stdout) =>
|
||||
stdout
|
||||
.split("\n")
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
status,
|
||||
statusDetails,
|
||||
@@ -1188,6 +1202,7 @@ const makeGitCore = Effect.gen(function* () {
|
||||
createBranch,
|
||||
checkoutBranch,
|
||||
initRepo,
|
||||
listLocalBranchNames,
|
||||
} satisfies GitCoreShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -32,7 +32,11 @@ interface FakeGitTextGeneration {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
}) => Effect.Effect<{ subject: string; body: string }, TextGenerationError>;
|
||||
includeBranch?: boolean;
|
||||
}) => Effect.Effect<
|
||||
{ subject: string; body: string; branch?: string | undefined },
|
||||
TextGenerationError
|
||||
>;
|
||||
generatePrContent: (input: {
|
||||
cwd: string;
|
||||
baseBranch: string;
|
||||
@@ -104,10 +108,13 @@ function createBareRemote(): Effect.Effect<
|
||||
|
||||
function createTextGeneration(overrides: Partial<FakeGitTextGeneration> = {}): TextGenerationShape {
|
||||
const implementation: FakeGitTextGeneration = {
|
||||
generateCommitMessage: () =>
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.succeed({
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
}),
|
||||
generatePrContent: () =>
|
||||
Effect.succeed({
|
||||
@@ -283,6 +290,7 @@ function runStackedAction(
|
||||
cwd: string;
|
||||
action: "commit" | "commit_push" | "commit_push_pr";
|
||||
commitMessage?: string;
|
||||
featureBranch?: boolean;
|
||||
},
|
||||
) {
|
||||
return manager.runStackedAction(input);
|
||||
@@ -475,6 +483,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
@@ -495,12 +504,13 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: () =>
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "this should not be used",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
@@ -511,6 +521,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
@@ -527,6 +538,101 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("creates feature branch, commits, and pushes with featureBranch option", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "main"]);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\nfeature-branch\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "Implement stacked git actions",
|
||||
body: "",
|
||||
...(input.includeBranch
|
||||
? { branch: "feature/implement-stacked-git-actions" }
|
||||
: {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit_push",
|
||||
featureBranch: true,
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/implement-stacked-git-actions");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(
|
||||
yield* runGit(repoDir, ["rev-parse", "--abbrev-ref", "HEAD"]).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
),
|
||||
).toBe("feature/implement-stacked-git-actions");
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", "HEAD"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
expect(generatedCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("featureBranch uses custom commit message and derives branch name", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
fs.writeFileSync(path.join(repoDir, "README.md"), "hello\ncustom-feature\n");
|
||||
let generatedCount = 0;
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
textGeneration: {
|
||||
generateCommitMessage: (input) =>
|
||||
Effect.sync(() => {
|
||||
generatedCount += 1;
|
||||
return {
|
||||
subject: "unused",
|
||||
body: "",
|
||||
...(input.includeBranch ? { branch: "feature/unused" } : {}),
|
||||
};
|
||||
}),
|
||||
},
|
||||
});
|
||||
const result = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
commitMessage: "feat: custom summary line\n\n- details from user",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("created");
|
||||
expect(result.branch.name).toBe("feature/feat-custom-summary-line");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.commit.subject).toBe("feat: custom summary line");
|
||||
expect(generatedCount).toBe(0);
|
||||
|
||||
const mainSha = yield* runGit(repoDir, ["rev-parse", "main"]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
const mergeBase = yield* runGit(repoDir, ["merge-base", "main", result.branch.name!]).pipe(
|
||||
Effect.map((r) => r.stdout.trim()),
|
||||
);
|
||||
expect(mergeBase).toBe(mainSha);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips commit when there are no uncommitted changes", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -538,12 +644,32 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("skipped_not_requested");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("featureBranch returns error when worktree is clean", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
|
||||
const { manager } = yield* makeManager();
|
||||
const errorMessage = yield* runStackedAction(manager, {
|
||||
cwd: repoDir,
|
||||
action: "commit",
|
||||
featureBranch: true,
|
||||
}).pipe(
|
||||
Effect.flip,
|
||||
Effect.map((error) => error.message),
|
||||
);
|
||||
|
||||
expect(errorMessage).toContain("no changes to commit");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("commits and pushes with upstream auto-setup when needed", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
@@ -559,6 +685,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
@@ -603,6 +730,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("created");
|
||||
expect(result.push.status).toBe("pushed");
|
||||
expect(result.push.setUpstream).toBe(true);
|
||||
@@ -635,6 +763,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.commit.status).toBe("skipped_no_changes");
|
||||
expect(result.push.status).toBe("skipped_up_to_date");
|
||||
}),
|
||||
@@ -669,6 +798,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("opened_existing");
|
||||
expect(result.pr.number).toBe(42);
|
||||
expect(ghCalls.some((call) => call.startsWith("pr view "))).toBe(false);
|
||||
@@ -709,6 +839,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
action: "commit_push_pr",
|
||||
});
|
||||
|
||||
expect(result.branch.status).toBe("skipped_not_requested");
|
||||
expect(result.pr.status).toBe("created");
|
||||
expect(result.pr.number).toBe(88);
|
||||
expect(
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { resolveAutoFeatureBranchName, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||
@@ -85,9 +86,14 @@ function limitContext(value: string, maxChars: number): string {
|
||||
return `${value.slice(0, maxChars)}\n\n[truncated]`;
|
||||
}
|
||||
|
||||
function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
||||
function sanitizeCommitMessage(generated: {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
}): {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
} {
|
||||
const rawSubject = generated.subject.trim().split(/\r?\n/g)[0]?.trim() ?? "";
|
||||
const subject = rawSubject.replace(/[.]+$/g, "").trim();
|
||||
@@ -95,9 +101,25 @@ function sanitizeCommitMessage(generated: { subject: string; body: string }): {
|
||||
return {
|
||||
subject: safeSubject,
|
||||
body: generated.body.trim(),
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
interface CommitAndBranchSuggestion {
|
||||
subject: string;
|
||||
body: string;
|
||||
branch?: string | undefined;
|
||||
commitMessage: string;
|
||||
}
|
||||
|
||||
function formatCommitMessage(subject: string, body: string): string {
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length === 0) {
|
||||
return subject;
|
||||
}
|
||||
return `${subject}\n\n${trimmedBody}`;
|
||||
}
|
||||
|
||||
function parseCustomCommitMessage(raw: string): { subject: string; body: string } | null {
|
||||
const normalized = raw.replace(/\r\n/g, "\n").trim();
|
||||
if (normalized.length === 0) {
|
||||
@@ -253,30 +275,72 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
return "main";
|
||||
});
|
||||
|
||||
const runCommitStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
const resolveCommitAndBranchSuggestion = (input: {
|
||||
cwd: string;
|
||||
branch: string | null;
|
||||
commitMessage?: string;
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(cwd);
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd);
|
||||
if (!context) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const customCommit = parseCustomCommitMessage(input.commitMessage ?? "");
|
||||
if (customCommit) {
|
||||
return {
|
||||
subject: customCommit.subject,
|
||||
body: customCommit.body,
|
||||
...(input.includeBranch
|
||||
? { branch: sanitizeFeatureBranchName(customCommit.subject) }
|
||||
: {}),
|
||||
commitMessage: formatCommitMessage(customCommit.subject, customCommit.body),
|
||||
};
|
||||
}
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: input.cwd,
|
||||
branch: input.branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
return {
|
||||
subject: generated.subject,
|
||||
body: generated.body,
|
||||
...(generated.branch !== undefined ? { branch: generated.branch } : {}),
|
||||
commitMessage: formatCommitMessage(generated.subject, generated.body),
|
||||
};
|
||||
});
|
||||
|
||||
const runCommitStep = (
|
||||
cwd: string,
|
||||
branch: string | null,
|
||||
commitMessage?: string,
|
||||
preResolvedSuggestion?: CommitAndBranchSuggestion,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
preResolvedSuggestion ??
|
||||
(yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
}));
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
let generated = parseCustomCommitMessage(commitMessage ?? "");
|
||||
if (!generated) {
|
||||
generated = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd,
|
||||
branch,
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, generated.subject, generated.body);
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
subject: generated.subject,
|
||||
subject: suggestion.subject,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -381,34 +445,88 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runFeatureBranchStep = (cwd: string, branch: string | null, commitMessage?: string) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion = yield* resolveCommitAndBranchSuggestion({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
includeBranch: true,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
"runFeatureBranchStep",
|
||||
"Cannot create a feature branch because there are no changes to commit.",
|
||||
);
|
||||
}
|
||||
|
||||
const preferredBranch = suggestion.branch ?? sanitizeFeatureBranchName(suggestion.subject);
|
||||
const existingBranchNames = yield* gitCore.listLocalBranchNames(cwd);
|
||||
const resolvedBranch = resolveAutoFeatureBranchName(existingBranchNames, preferredBranch);
|
||||
|
||||
yield* gitCore.createBranch({ cwd, branch: resolvedBranch });
|
||||
yield* Effect.scoped(gitCore.checkoutBranch({ cwd, branch: resolvedBranch }));
|
||||
|
||||
return {
|
||||
branchStep: { status: "created" as const, name: resolvedBranch },
|
||||
resolvedCommitMessage: suggestion.commitMessage,
|
||||
resolvedCommitSuggestion: suggestion,
|
||||
};
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
const initialStatus = yield* gitCore.statusDetails(input.cwd);
|
||||
if (wantsPush && !initialStatus.branch) {
|
||||
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
|
||||
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
|
||||
}
|
||||
if (wantsPr && !initialStatus.branch) {
|
||||
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
|
||||
return yield* gitManagerError(
|
||||
"runStackedAction",
|
||||
"Cannot create a pull request from detached HEAD.",
|
||||
);
|
||||
}
|
||||
|
||||
const commit = yield* runCommitStep(input.cwd, initialStatus.branch, input.commitMessage);
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
if (input.featureBranch) {
|
||||
const result = yield* runFeatureBranchStep(
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
);
|
||||
|
||||
const push = wantsPush
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, initialStatus.branch)
|
||||
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
const pr = wantsPr
|
||||
? yield* runPrStep(input.cwd, initialStatus.branch)
|
||||
? yield* runPrStep(input.cwd, currentBranch)
|
||||
: { status: "skipped_not_requested" as const };
|
||||
|
||||
return {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
|
||||
@@ -157,6 +157,11 @@ export interface GitCoreShape {
|
||||
* Initialize a repository in the provided directory.
|
||||
*/
|
||||
readonly initRepo: (input: GitInitInput) => Effect.Effect<void, GitCommandError>;
|
||||
|
||||
/**
|
||||
* List local branch names (short format).
|
||||
*/
|
||||
readonly listLocalBranchNames: (cwd: string) => Effect.Effect<string[], GitCommandError>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -29,6 +29,7 @@ export interface GitManagerShape {
|
||||
|
||||
/**
|
||||
* 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,
|
||||
|
||||
@@ -17,11 +17,15 @@ export interface CommitMessageGenerationInput {
|
||||
branch: string | null;
|
||||
stagedSummary: string;
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
subject: string;
|
||||
body: string;
|
||||
/** Only present when `includeBranch` was set on the input. */
|
||||
branch?: string | undefined;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationInput {
|
||||
|
||||
@@ -8,7 +8,8 @@ import { OpenLive } from "./open";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
import { ServerLive } from "./wsServer";
|
||||
import { NetService } from "./config";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
|
||||
const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(CliConfig.layer),
|
||||
@@ -16,6 +17,7 @@ const RuntimeLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(OpenLive),
|
||||
Layer.provideMerge(NetService.layer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
);
|
||||
|
||||
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
|
||||
@@ -1,15 +1,20 @@
|
||||
import * as Http from "node:http";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it, vi } from "@effect/vitest";
|
||||
import type { OrchestrationReadModel } from "@t3tools/contracts";
|
||||
import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { beforeEach } from "vitest";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
|
||||
import { CliConfig, t3Cli, type CliConfigShape } from "./main";
|
||||
import { NetService, ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
|
||||
const start = vi.fn(() => undefined);
|
||||
@@ -33,6 +38,9 @@ const testLayer = Layer.mergeAll(
|
||||
resolveStaticDir: Effect.undefined,
|
||||
} satisfies CliConfigShape),
|
||||
Layer.succeed(NetService, {
|
||||
canListenOnHost: () => Effect.succeed(true),
|
||||
isPortAvailableOnLoopback: () => Effect.succeed(true),
|
||||
reserveLoopbackPort: () => Effect.succeed(0),
|
||||
findAvailablePort,
|
||||
}),
|
||||
Layer.succeed(Server, {
|
||||
@@ -43,6 +51,8 @@ const testLayer = Layer.mergeAll(
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
NodeServices.layer,
|
||||
);
|
||||
|
||||
@@ -73,7 +83,7 @@ beforeEach(() => {
|
||||
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
|
||||
});
|
||||
|
||||
it.layer(testLayer)("server cli", (it) => {
|
||||
it.layer(testLayer)("server CLI command", (it) => {
|
||||
it.effect("parses all CLI flags and wires scoped start/stop", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([
|
||||
@@ -223,6 +233,43 @@ it.layer(testLayer)("server cli", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("records a startup heartbeat with thread/project counts", () =>
|
||||
Effect.gen(function* () {
|
||||
const recordTelemetry = vi.fn(
|
||||
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
|
||||
);
|
||||
const getSnapshot = vi.fn(() =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: 2,
|
||||
projects: [{} as OrchestrationReadModel["projects"][number]],
|
||||
threads: [
|
||||
{} as OrchestrationReadModel["threads"][number],
|
||||
{} as OrchestrationReadModel["threads"][number],
|
||||
],
|
||||
updatedAt: new Date(1).toISOString(),
|
||||
} satisfies OrchestrationReadModel),
|
||||
);
|
||||
|
||||
yield* recordStartupHeartbeat.pipe(
|
||||
Effect.provideService(ProjectionSnapshotQuery, {
|
||||
getSnapshot,
|
||||
}),
|
||||
Effect.provideService(AnalyticsService, {
|
||||
record: recordTelemetry,
|
||||
flush: Effect.void,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.deepEqual(recordTelemetry.mock.calls[0], [
|
||||
"server.boot.heartbeat",
|
||||
{
|
||||
threadCount: 2,
|
||||
projectCount: 1,
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not start server for invalid --mode values", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--mode", "invalid"]);
|
||||
|
||||
+54
-28
@@ -8,10 +8,9 @@
|
||||
*/
|
||||
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
NetService,
|
||||
resolveStaticDir,
|
||||
ServerConfig,
|
||||
type RuntimeMode,
|
||||
@@ -21,7 +20,12 @@ import { fixPath, resolveStateDir } from "./os-jank";
|
||||
import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
@@ -118,6 +122,9 @@ const CliEnvConfig = Config.all({
|
||||
),
|
||||
});
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const ServerConfigLive = (input: CliInput) =>
|
||||
Layer.effect(
|
||||
ServerConfig,
|
||||
@@ -149,25 +156,16 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
|
||||
);
|
||||
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||
const noBrowser = Option.match(input.noBrowser, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.noBrowser ?? mode === "desktop")),
|
||||
onNone: () => env.noBrowser ?? mode === "desktop",
|
||||
});
|
||||
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const autoBootstrapProjectFromCwd = Option.match(input.autoBootstrapProjectFromCwd, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/mode fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.autoBootstrapProjectFromCwd ?? mode === "web")),
|
||||
onNone: () => env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
});
|
||||
const logWebSocketEvents = Option.match(input.logWebSocketEvents, {
|
||||
// effect/cli boolean flags parse to `false` when absent; in that case
|
||||
// we still want env/dev fallbacks to apply.
|
||||
onSome: (value) => (value ? true : (env.logWebSocketEvents ?? Boolean(devUrl))),
|
||||
onNone: () => env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
});
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const { join } = yield* Path.Path;
|
||||
const keybindingsConfigPath = join(stateDir, "keybindings.json");
|
||||
@@ -176,7 +174,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
env.host ??
|
||||
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
|
||||
return {
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
port,
|
||||
cwd: cliConfig.cwd,
|
||||
@@ -190,6 +188,8 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
|
||||
return config;
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -197,7 +197,10 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
@@ -207,6 +210,31 @@ const isWildcardHost = (host: string | undefined): boolean =>
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
const analytics = yield* AnalyticsService;
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
|
||||
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
|
||||
Effect.map((snapshot) => ({
|
||||
threadCount: snapshot.threads.length,
|
||||
projectCount: snapshot.projects.length,
|
||||
})),
|
||||
Effect.catch((cause) =>
|
||||
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
|
||||
Effect.as({
|
||||
threadCount: 0,
|
||||
projectCount: 0,
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
yield* analytics.record("server.boot.heartbeat", {
|
||||
threadCount,
|
||||
projectCount,
|
||||
});
|
||||
});
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
@@ -226,20 +254,18 @@ const makeServerProgram = (input: CliInput) =>
|
||||
}
|
||||
|
||||
yield* start;
|
||||
yield* Effect.forkChild(recordStartupHeartbeat);
|
||||
|
||||
const localUrl = `http://localhost:${config.port}`;
|
||||
const bindUrl =
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
url: bindUrl,
|
||||
localUrl,
|
||||
bindHost: config.host ?? "default",
|
||||
cwd: config.cwd,
|
||||
mode: config.mode,
|
||||
stateDir: config.stateDir,
|
||||
authEnabled: Boolean(config.authToken),
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
});
|
||||
|
||||
if (!config.noBrowser) {
|
||||
|
||||
+28
-19
@@ -224,28 +224,37 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
});
|
||||
|
||||
export const launchDetached = (launch: EditorLaunch) =>
|
||||
Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
|
||||
);
|
||||
Effect.gen(function* () {
|
||||
if (!isCommandAvailable(launch.command)) {
|
||||
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
|
||||
}
|
||||
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(launch.command, [...launch.args], {
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
} catch (error) {
|
||||
return resume(
|
||||
Effect.fail(
|
||||
new OpenError({ message: "failed to spawn detached process", cause: error }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
const handleSpawn = () => {
|
||||
child.unref();
|
||||
resume(Effect.void);
|
||||
};
|
||||
|
||||
child.once("spawn", handleSpawn);
|
||||
child.once("error", (cause) =>
|
||||
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
|
||||
@@ -6,12 +6,10 @@ import { execFileSync } from "node:child_process";
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -40,28 +38,43 @@ import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd = cwd) {
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: "codex";
|
||||
readonly createdAt: string;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId?: string | undefined;
|
||||
readonly itemId?: string | undefined;
|
||||
readonly requestId?: string | undefined;
|
||||
readonly payload?: unknown | undefined;
|
||||
readonly [key: string]: unknown;
|
||||
};
|
||||
|
||||
function createProviderServiceHarness(
|
||||
cwd: string,
|
||||
hasSession = true,
|
||||
sessionCwd = cwd,
|
||||
providerName: ProviderSession["provider"] = "codex",
|
||||
) {
|
||||
const now = new Date().toISOString();
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
const rollbackConversation = vi.fn(
|
||||
(_input: { readonly sessionId: ProviderSessionId; readonly numTurns: number }) => Effect.void,
|
||||
(_input: { readonly threadId: ThreadId; readonly numTurns: number }) => Effect.void,
|
||||
);
|
||||
|
||||
const unsupported = <A>() =>
|
||||
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
|
||||
const listSessions = () =>
|
||||
hasSession
|
||||
? Effect.succeed([
|
||||
? Effect.succeed([
|
||||
{
|
||||
sessionId: asSessionId("sess-1"),
|
||||
provider: "codex",
|
||||
provider: providerName,
|
||||
status: "ready",
|
||||
threadId: asProviderThreadId("provider-thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
cwd: sessionCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -73,15 +86,16 @@ function createProviderServiceHarness(cwd: string, hasSession = true, sessionCwd
|
||||
sendTurn: () => unsupported(),
|
||||
interruptTurn: () => unsupported(),
|
||||
respondToRequest: () => unsupported(),
|
||||
respondToUserInput: () => unsupported(),
|
||||
stopSession: () => unsupported(),
|
||||
listSessions,
|
||||
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
|
||||
rollbackConversation,
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event));
|
||||
const emit = (event: LegacyProviderRuntimeEvent): void => {
|
||||
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
|
||||
};
|
||||
|
||||
return {
|
||||
@@ -227,6 +241,7 @@ describe("CheckpointReactor", () => {
|
||||
cwd,
|
||||
options?.hasSession ?? true,
|
||||
options?.providerSessionCwd ?? cwd,
|
||||
"codex",
|
||||
);
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
Layer.provide(OrchestrationProjectionPipelineLive),
|
||||
@@ -271,6 +286,8 @@ describe("CheckpointReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: options?.threadWorktreePath ?? cwd,
|
||||
createdAt,
|
||||
@@ -320,10 +337,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -336,10 +350,10 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -351,11 +365,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-1"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -399,10 +413,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-main"),
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -415,10 +426,10 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
@@ -431,11 +442,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-aux"),
|
||||
turnId: asProviderTurnId("turn-aux"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-aux"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
@@ -449,11 +460,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-main"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
const thread = await waitForThread(
|
||||
@@ -476,10 +487,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -492,11 +500,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-missing-baseline"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-missing-baseline"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -531,8 +539,8 @@ describe("CheckpointReactor", () => {
|
||||
text: "start turn",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: new Date().toISOString(),
|
||||
}),
|
||||
);
|
||||
@@ -567,10 +575,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-missing"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-missing-cwd"),
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -584,11 +589,11 @@ describe("CheckpointReactor", () => {
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-missing"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-missing"),
|
||||
turnId: asProviderTurnId("turn-missing-cwd"),
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-missing-cwd"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
@@ -604,7 +609,7 @@ describe("CheckpointReactor", () => {
|
||||
).toBe("v2\n");
|
||||
});
|
||||
|
||||
it("maps runtime checkpoint.captured into thread.turn.diff.complete when missing in read model", async () => {
|
||||
it("ignores non-v2 checkpoint.captured runtime events", async () => {
|
||||
const harness = await createHarness();
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
@@ -617,10 +622,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -633,19 +635,19 @@ describe("CheckpointReactor", () => {
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-3"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-3"),
|
||||
turnCount: 3,
|
||||
status: "completed",
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3),
|
||||
);
|
||||
expect(thread.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
true,
|
||||
await Effect.runPromise(Effect.sleep("40 millis"));
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -670,10 +672,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -683,25 +682,24 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "checkpoint.captured",
|
||||
type: "turn.completed",
|
||||
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-runtime-failure"),
|
||||
turnCount: 1,
|
||||
status: "completed",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-runtime-failure"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
|
||||
provider: "codex",
|
||||
sessionId: asSessionId("sess-1"),
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("turn-after-runtime-failure"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-after-runtime-failure"),
|
||||
});
|
||||
|
||||
await waitForGitRefExists(
|
||||
@@ -726,10 +724,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -785,7 +780,7 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
@@ -807,10 +802,7 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: createdAt,
|
||||
@@ -882,11 +874,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
|
||||
sessionId: asSessionId("sess-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,8 +2,6 @@ import {
|
||||
CommandId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationEvent,
|
||||
@@ -34,11 +32,7 @@ type ReactorInput =
|
||||
};
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | null {
|
||||
return value === undefined ? null : TurnId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function toProviderThreadId(value: string | undefined): ProviderThreadId | null {
|
||||
return value === undefined ? null : ProviderThreadId.makeUnsafe(value);
|
||||
return value === undefined ? null : TurnId.makeUnsafe(String(value));
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
@@ -95,77 +89,58 @@ const make = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const appendCaptureFailureActivity = (input: {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly detail: string;
|
||||
readonly createdAt: string;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === input.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: thread.id,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
},
|
||||
createdAt: input.createdAt,
|
||||
});
|
||||
|
||||
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
|
||||
threadId: ThreadId,
|
||||
): Effect.fn.Return<
|
||||
Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }>
|
||||
Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>
|
||||
> {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find((entry) => entry.id === threadId);
|
||||
const projectedSessionId = thread?.session?.providerSessionId ?? null;
|
||||
const projectedProviderThreadId = thread?.session?.providerThreadId ?? undefined;
|
||||
|
||||
const sessions = yield* providerService.listSessions();
|
||||
|
||||
const findSessionWithCwd = (
|
||||
session: (typeof sessions)[number] | undefined,
|
||||
): Option.Option<{ readonly sessionId: ProviderSessionId; readonly cwd: string }> => {
|
||||
): Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }> => {
|
||||
if (!session?.cwd) {
|
||||
return Option.none();
|
||||
}
|
||||
return Option.some({ sessionId: session.sessionId, cwd: session.cwd });
|
||||
return Option.some({ threadId: session.threadId, cwd: session.cwd });
|
||||
};
|
||||
|
||||
if (projectedSessionId !== null) {
|
||||
const projectedSession = sessions.find((session) => session.sessionId === projectedSessionId);
|
||||
if (thread) {
|
||||
const projectedSession = sessions.find(
|
||||
(session) => session.threadId === thread.id,
|
||||
);
|
||||
const fromProjected = findSessionWithCwd(projectedSession);
|
||||
if (Option.isSome(fromProjected)) {
|
||||
return fromProjected;
|
||||
}
|
||||
}
|
||||
|
||||
if (projectedProviderThreadId) {
|
||||
const matchedSession = sessions.find(
|
||||
(session) => session.threadId === projectedProviderThreadId,
|
||||
);
|
||||
const fromProviderThread = findSessionWithCwd(matchedSession);
|
||||
if (Option.isSome(fromProviderThread)) {
|
||||
return fromProviderThread;
|
||||
}
|
||||
}
|
||||
|
||||
return Option.none();
|
||||
});
|
||||
|
||||
@@ -178,23 +153,11 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
const projectedProviderThreadId = thread.session?.providerThreadId ?? null;
|
||||
const eventProviderThreadId = toProviderThreadId(event.threadId);
|
||||
if (
|
||||
projectedProviderThreadId !== null &&
|
||||
eventProviderThreadId !== null &&
|
||||
!sameId(projectedProviderThreadId, eventProviderThreadId)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
// When a primary turn is active, only that turn may produce completion checkpoints.
|
||||
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
|
||||
return;
|
||||
@@ -266,7 +229,7 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
Effect.tapError((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
sessionId: event.sessionId,
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
detail: `Checkpoint captured, but turn diff summary is unavailable: ${error.message}`,
|
||||
createdAt: event.createdAt,
|
||||
@@ -296,7 +259,7 @@ const make = Effect.gen(function* () {
|
||||
turnId,
|
||||
completedAt: now,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
status: checkpointStatusFromRuntime(event.payload.state),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: nextTurnCount,
|
||||
@@ -314,7 +277,7 @@ const make = Effect.gen(function* () {
|
||||
summary: "Checkpoint captured",
|
||||
payload: {
|
||||
turnCount: nextTurnCount,
|
||||
...(event.status !== undefined ? { status: event.status } : {}),
|
||||
status: event.payload.state,
|
||||
},
|
||||
turnId,
|
||||
createdAt: now,
|
||||
@@ -333,7 +296,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
(entry) => entry.id === event.threadId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
@@ -513,7 +476,7 @@ const make = Effect.gen(function* () {
|
||||
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
|
||||
if (rolledBackTurns > 0) {
|
||||
yield* providerService.rollbackConversation({
|
||||
sessionId: sessionRuntime.value.sessionId,
|
||||
threadId: sessionRuntime.value.threadId,
|
||||
numTurns: rolledBackTurns,
|
||||
});
|
||||
}
|
||||
@@ -581,7 +544,7 @@ const make = Effect.gen(function* () {
|
||||
yield* captureCheckpointFromTurnCompletion(event).pipe(
|
||||
Effect.catch((error) =>
|
||||
appendCaptureFailureActivity({
|
||||
sessionId: event.sessionId,
|
||||
threadId: event.threadId,
|
||||
turnId,
|
||||
detail: error.message,
|
||||
createdAt: new Date().toISOString(),
|
||||
@@ -590,89 +553,6 @@ const make = Effect.gen(function* () {
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.type === "checkpoint.captured") {
|
||||
const turnId = toTurnId(event.turnId);
|
||||
if (!turnId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.session?.providerSessionId === event.sessionId,
|
||||
);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
thread.checkpoints.some(
|
||||
(checkpoint) =>
|
||||
checkpoint.turnId === turnId || checkpoint.checkpointTurnCount === event.turnCount,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sessionRuntime = yield* resolveSessionRuntimeForThread(thread.id);
|
||||
if (Option.isNone(sessionRuntime)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const fromTurnCount = Math.max(0, event.turnCount - 1);
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(thread.id, fromTurnCount);
|
||||
const targetCheckpointRef = checkpointRefForThreadTurn(thread.id, event.turnCount);
|
||||
|
||||
const targetExists = yield* checkpointStore.hasCheckpointRef({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
if (!targetExists) {
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
});
|
||||
}
|
||||
|
||||
const files = yield* checkpointStore
|
||||
.diffCheckpoints({
|
||||
cwd: sessionRuntime.value.cwd,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef: targetCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((diff) =>
|
||||
parseTurnDiffFilesFromUnifiedDiff(diff).map((file) => ({
|
||||
path: file.path,
|
||||
kind: "modified" as const,
|
||||
additions: file.additions,
|
||||
deletions: file.deletions,
|
||||
})),
|
||||
),
|
||||
Effect.catch(() => Effect.succeed([])),
|
||||
);
|
||||
|
||||
const assistantMessageId =
|
||||
thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === turnId)?.id ??
|
||||
MessageId.makeUnsafe(`assistant:${turnId}`);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: serverCommandId("checkpoint-runtime-captured-diff-complete"),
|
||||
threadId: thread.id,
|
||||
turnId,
|
||||
completedAt: event.createdAt,
|
||||
checkpointRef: targetCheckpointRef,
|
||||
status: checkpointStatusFromRuntime(event.status),
|
||||
files,
|
||||
assistantMessageId,
|
||||
checkpointTurnCount: event.turnCount,
|
||||
createdAt: event.createdAt,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const processInput = (
|
||||
@@ -717,11 +597,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(providerService.streamEvents, (event) => {
|
||||
if (
|
||||
event.type !== "turn.started" &&
|
||||
event.type !== "turn.completed" &&
|
||||
event.type !== "checkpoint.captured"
|
||||
) {
|
||||
if (event.type !== "turn.started" && event.type !== "turn.completed") {
|
||||
return Effect.void;
|
||||
}
|
||||
return Queue.offer(queue, { source: "runtime", event }).pipe(Effect.asVoid);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
CheckpointRef,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
@@ -80,6 +81,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -96,8 +99,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -108,6 +111,81 @@ describe("OrchestrationEngine", () => {
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("seeds branched thread history during thread creation", async () => {
|
||||
const createdAt = now();
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-project-branch-seed"),
|
||||
projectId: asProjectId("project-branch-seed"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-branch-seed",
|
||||
defaultModel: "gpt-5-codex",
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-branch-seed"),
|
||||
threadId: ThreadId.makeUnsafe("thread-branch-seed"),
|
||||
projectId: asProjectId("project-branch-seed"),
|
||||
title: "Branch of Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: "feature/source",
|
||||
worktreePath: null,
|
||||
seedMessages: [
|
||||
{
|
||||
messageId: asMessageId("msg-seed-user"),
|
||||
role: "user",
|
||||
text: "original question",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:00.000Z",
|
||||
updatedAt: "2026-02-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
messageId: asMessageId("msg-seed-assistant"),
|
||||
role: "assistant",
|
||||
text: "original answer",
|
||||
attachments: [],
|
||||
createdAt: "2026-02-01T00:00:01.000Z",
|
||||
updatedAt: "2026-02-01T00:00:01.000Z",
|
||||
},
|
||||
],
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
|
||||
const readModel = await system.run(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === "thread-branch-seed");
|
||||
expect(thread?.messages.map((message) => message.text)).toEqual([
|
||||
"original question",
|
||||
"original answer",
|
||||
]);
|
||||
expect(thread?.messages.every((message) => message.turnId === null)).toBe(true);
|
||||
expect(thread?.session).toBeNull();
|
||||
|
||||
const events = await system.run(
|
||||
Stream.runCollect(engine.readEvents(0)).pipe(
|
||||
Effect.map((chunk): OrchestrationEvent[] => Array.from(chunk)),
|
||||
),
|
||||
);
|
||||
expect(events.map((event) => event.type)).toEqual([
|
||||
"project.created",
|
||||
"thread.created",
|
||||
"thread.message-sent",
|
||||
"thread.message-sent",
|
||||
]);
|
||||
|
||||
await system.dispose();
|
||||
});
|
||||
|
||||
it("replays append-only events from sequence", async () => {
|
||||
const system = await createOrchestrationSystem();
|
||||
const { engine } = system;
|
||||
@@ -132,6 +210,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -192,6 +272,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -235,6 +317,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -342,6 +426,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -357,6 +443,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -420,6 +508,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -436,8 +526,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request" as const,
|
||||
sandboxMode: "workspace-write" as const,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required" as const,
|
||||
createdAt,
|
||||
};
|
||||
|
||||
@@ -553,6 +643,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -596,8 +688,8 @@ describe("OrchestrationEngine", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now(),
|
||||
}),
|
||||
),
|
||||
@@ -631,6 +723,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -646,6 +740,8 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
|
||||
@@ -4,8 +4,6 @@ import {
|
||||
CorrelationId,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -104,6 +102,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -374,6 +373,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Thread Clear Attachments",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -500,6 +500,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Thread Overwrite",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -650,6 +651,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Thread Rollback",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -780,6 +782,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Thread Revert Files",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -994,6 +997,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Thread Delete Files",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -1156,6 +1160,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -1279,6 +1284,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Thread Empty",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -1415,6 +1421,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Thread Conflict",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T13:00:01.000Z",
|
||||
@@ -1555,6 +1562,7 @@ projectionLayer("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Thread Revert",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-02-26T12:00:01.000Z",
|
||||
@@ -1749,8 +1757,7 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
payload: {
|
||||
threadId,
|
||||
messageId,
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: turnStartedAt,
|
||||
},
|
||||
});
|
||||
@@ -1772,20 +1779,14 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
|
||||
commandId: CommandId.makeUnsafe("cmd-restart-2"),
|
||||
causationEventId: null,
|
||||
correlationId: CorrelationId.makeUnsafe("cmd-restart-2"),
|
||||
metadata: {
|
||||
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
||||
},
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId,
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: ProviderSessionId.makeUnsafe("provider-session-restart"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-restart"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: turnId,
|
||||
lastError: null,
|
||||
updatedAt: sessionSetAt,
|
||||
|
||||
@@ -18,6 +18,10 @@ import {
|
||||
type ProjectionThreadMessage,
|
||||
ProjectionThreadMessageRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import {
|
||||
type ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import {
|
||||
type ProjectionTurn,
|
||||
@@ -29,6 +33,7 @@ import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/Projec
|
||||
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
|
||||
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
|
||||
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
|
||||
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
|
||||
@@ -48,6 +53,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
|
||||
projects: "projection.projects",
|
||||
threads: "projection.threads",
|
||||
threadMessages: "projection.thread-messages",
|
||||
threadProposedPlans: "projection.thread-proposed-plans",
|
||||
threadActivities: "projection.thread-activities",
|
||||
threadSessions: "projection.thread-sessions",
|
||||
threadTurns: "projection.thread-turns",
|
||||
@@ -189,6 +195,26 @@ function retainProjectionActivitiesAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainProjectionProposedPlansAfterRevert(
|
||||
proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>,
|
||||
turns: ReadonlyArray<ProjectionTurn>,
|
||||
turnCount: number,
|
||||
): ReadonlyArray<ProjectionThreadProposedPlan> {
|
||||
const retainedTurnIds = new Set<string>(
|
||||
turns
|
||||
.filter(
|
||||
(turn) =>
|
||||
turn.turnId !== null &&
|
||||
turn.checkpointTurnCount !== null &&
|
||||
turn.checkpointTurnCount <= turnCount,
|
||||
)
|
||||
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
|
||||
);
|
||||
return proposedPlans.filter(
|
||||
(proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
|
||||
);
|
||||
}
|
||||
|
||||
function collectThreadAttachmentRelativePaths(
|
||||
threadId: string,
|
||||
messages: ReadonlyArray<ProjectionThreadMessage>,
|
||||
@@ -320,6 +346,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
const projectionProjectRepository = yield* ProjectionProjectRepository;
|
||||
const projectionThreadRepository = yield* ProjectionThreadRepository;
|
||||
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
|
||||
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
|
||||
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
|
||||
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
@@ -396,6 +423,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
model: event.payload.model,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
branch: event.payload.branch,
|
||||
worktreePath: event.payload.worktreePath,
|
||||
latestTurnId: null,
|
||||
@@ -425,6 +454,36 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.runtime-mode-set": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.interaction-mode-set": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
case "thread.deleted": {
|
||||
attachmentSideEffects.deletedThreadIds.add(event.payload.threadId);
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
@@ -442,6 +501,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
@@ -583,6 +643,57 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadProposedPlansProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.proposed-plan-upserted":
|
||||
yield* projectionThreadProposedPlanRepository.upsert({
|
||||
planId: event.payload.proposedPlan.id,
|
||||
threadId: event.payload.threadId,
|
||||
turnId: event.payload.proposedPlan.turnId,
|
||||
planMarkdown: event.payload.proposedPlan.planMarkdown,
|
||||
createdAt: event.payload.proposedPlan.createdAt,
|
||||
updatedAt: event.payload.proposedPlan.updatedAt,
|
||||
});
|
||||
return;
|
||||
|
||||
case "thread.reverted": {
|
||||
const existingRows = yield* projectionThreadProposedPlanRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
if (existingRows.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const existingTurns = yield* projectionTurnRepository.listByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
const keptRows = retainProjectionProposedPlansAfterRevert(
|
||||
existingRows,
|
||||
existingTurns,
|
||||
event.payload.turnCount,
|
||||
);
|
||||
if (keptRows.length === existingRows.length) {
|
||||
return;
|
||||
}
|
||||
|
||||
yield* projectionThreadProposedPlanRepository.deleteByThreadId({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
yield* Effect.forEach(keptRows, projectionThreadProposedPlanRepository.upsert, {
|
||||
concurrency: 1,
|
||||
}).pipe(Effect.asVoid);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
return;
|
||||
}
|
||||
});
|
||||
|
||||
const applyThreadActivitiesProjection: ProjectorDefinition["apply"] = (
|
||||
event,
|
||||
_attachmentSideEffects,
|
||||
@@ -598,6 +709,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
kind: event.payload.activity.kind,
|
||||
summary: event.payload.activity.summary,
|
||||
payload: event.payload.activity.payload,
|
||||
...(event.payload.activity.sequence !== undefined
|
||||
? { sequence: event.payload.activity.sequence }
|
||||
: {}),
|
||||
createdAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
@@ -646,10 +760,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
status: event.payload.session.status,
|
||||
providerName: event.payload.session.providerName,
|
||||
providerSessionId: event.payload.session.providerSessionId,
|
||||
providerThreadId: event.payload.session.providerThreadId,
|
||||
approvalPolicy: event.payload.session.approvalPolicy,
|
||||
sandboxMode: event.payload.session.sandboxMode,
|
||||
runtimeMode: event.payload.session.runtimeMode,
|
||||
activeTurnId: event.payload.session.activeTurnId,
|
||||
lastError: event.payload.session.lastError,
|
||||
updatedAt: event.payload.session.updatedAt,
|
||||
@@ -991,6 +1102,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
apply: applyThreadMessagesProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
apply: applyThreadProposedPlansProjection,
|
||||
},
|
||||
{
|
||||
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
apply: applyThreadActivitiesProjection,
|
||||
@@ -1110,6 +1225,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
|
||||
Layer.provideMerge(ProjectionProjectRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
|
||||
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
|
||||
Layer.provideMerge(ProjectionTurnRepositoryLive),
|
||||
|
||||
@@ -3,8 +3,6 @@ import {
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -22,9 +20,6 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
const asProviderSessionId = (value: string): ProviderSessionId =>
|
||||
ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderThreadId = (value: string): ProviderThreadId => ProviderThreadId.makeUnsafe(value);
|
||||
|
||||
const projectionSnapshotLayer = it.layer(
|
||||
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
|
||||
@@ -143,8 +138,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
approval_policy,
|
||||
sandbox_mode,
|
||||
runtime_mode,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at
|
||||
@@ -155,8 +149,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'codex',
|
||||
'provider-session-1',
|
||||
'provider-thread-1',
|
||||
'on-request',
|
||||
'workspace-write',
|
||||
'approval-required',
|
||||
'turn-1',
|
||||
NULL,
|
||||
'2026-02-24T00:00:07.000Z'
|
||||
@@ -241,6 +234,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: {
|
||||
@@ -265,6 +260,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
updatedAt: "2026-02-24T00:00:05.000Z",
|
||||
},
|
||||
],
|
||||
proposedPlans: [],
|
||||
activities: [
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
@@ -291,10 +287,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asProviderSessionId("provider-session-1"),
|
||||
providerThreadId: asProviderThreadId("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-24T00:00:07.000Z",
|
||||
|
||||
@@ -2,6 +2,7 @@ import {
|
||||
ChatAttachment,
|
||||
IsoDateTime,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationReadModel,
|
||||
ProjectScript,
|
||||
@@ -9,6 +10,7 @@ import {
|
||||
type OrchestrationCheckpointSummary,
|
||||
type OrchestrationLatestTurn,
|
||||
type OrchestrationMessage,
|
||||
type OrchestrationProposedPlan,
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
@@ -29,6 +31,7 @@ import { ProjectionProject } from "../../persistence/Services/ProjectionProjects
|
||||
import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
|
||||
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
|
||||
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
|
||||
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
|
||||
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
|
||||
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
|
||||
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
|
||||
@@ -49,10 +52,12 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
sequence: Schema.NullOr(NonNegativeInt),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
|
||||
@@ -76,6 +81,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threads,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
|
||||
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
|
||||
@@ -151,6 +157,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
@@ -182,6 +190,23 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadProposedPlanRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadProposedPlanDbRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
ORDER BY thread_id ASC, created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const listThreadActivityRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionThreadActivityDbRowSchema,
|
||||
@@ -195,9 +220,15 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
ORDER BY thread_id ASC, created_at ASC, activity_id ASC
|
||||
ORDER BY
|
||||
thread_id ASC,
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -212,8 +243,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
provider_name AS "providerName",
|
||||
provider_session_id AS "providerSessionId",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
approval_policy AS "approvalPolicy",
|
||||
sandbox_mode AS "sandboxMode",
|
||||
runtime_mode AS "runtimeMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
@@ -282,6 +312,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
projectRows,
|
||||
threadRows,
|
||||
messageRows,
|
||||
proposedPlanRows,
|
||||
activityRows,
|
||||
sessionRows,
|
||||
checkpointRows,
|
||||
@@ -312,6 +343,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadProposedPlanRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:query",
|
||||
"ProjectionSnapshotQuery.getSnapshot:listThreadProposedPlans:decodeRows",
|
||||
),
|
||||
),
|
||||
),
|
||||
listThreadActivityRows(undefined).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
@@ -355,6 +394,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
]);
|
||||
|
||||
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
|
||||
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
|
||||
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
|
||||
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
|
||||
const sessionsByThread = new Map<string, OrchestrationSession>();
|
||||
@@ -388,6 +428,19 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
messagesByThread.set(row.threadId, threadMessages);
|
||||
}
|
||||
|
||||
for (const row of proposedPlanRows) {
|
||||
updatedAt = maxIso(updatedAt, row.updatedAt);
|
||||
const threadProposedPlans = proposedPlansByThread.get(row.threadId) ?? [];
|
||||
threadProposedPlans.push({
|
||||
id: row.planId,
|
||||
turnId: row.turnId,
|
||||
planMarkdown: row.planMarkdown,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
});
|
||||
proposedPlansByThread.set(row.threadId, threadProposedPlans);
|
||||
}
|
||||
|
||||
for (const row of activityRows) {
|
||||
updatedAt = maxIso(updatedAt, row.createdAt);
|
||||
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
|
||||
@@ -398,6 +451,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
@@ -452,10 +506,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
threadId: row.threadId,
|
||||
status: row.status,
|
||||
providerName: row.providerName,
|
||||
providerSessionId: row.providerSessionId,
|
||||
providerThreadId: row.providerThreadId,
|
||||
approvalPolicy: row.approvalPolicy,
|
||||
sandboxMode: row.sandboxMode,
|
||||
runtimeMode: row.runtimeMode,
|
||||
activeTurnId: row.activeTurnId,
|
||||
lastError: row.lastError,
|
||||
updatedAt: row.updatedAt,
|
||||
@@ -478,6 +529,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
model: row.model,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
@@ -485,6 +538,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
|
||||
@@ -2,15 +2,14 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ProviderTurnId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -19,6 +18,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGenerationError } from "../../git/Errors.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
|
||||
@@ -36,17 +36,15 @@ import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asSessionId = (value: string): ProviderSessionId => ProviderSessionId.makeUnsafe(value);
|
||||
const asProviderTurnId = (value: string): ProviderTurnId => ProviderTurnId.makeUnsafe(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
async function waitFor(predicate: () => boolean, timeoutMs = 2000): Promise<void> {
|
||||
async function waitFor(predicate: () => boolean | Promise<boolean>, timeoutMs = 2000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const poll = async (): Promise<void> => {
|
||||
if (predicate()) {
|
||||
if (await predicate()) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
@@ -88,36 +86,93 @@ describe("ProviderCommandReactor", () => {
|
||||
createdStateDirs.add(stateDir);
|
||||
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
|
||||
let nextSessionIndex = 1;
|
||||
const startSession = vi.fn((_: unknown, __: unknown) => {
|
||||
const runtimeSessions: Array<ProviderSession> = [];
|
||||
const startSession = vi.fn((_: unknown, input: unknown) => {
|
||||
const sessionIndex = nextSessionIndex++;
|
||||
return Effect.succeed({
|
||||
sessionId: asSessionId(`sess-${sessionIndex}`),
|
||||
provider: "codex" as const,
|
||||
const provider =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"provider" in input &&
|
||||
input.provider === "codex"
|
||||
? input.provider
|
||||
: "codex";
|
||||
const resumeCursor =
|
||||
typeof input === "object" && input !== null && "resumeCursor" in input
|
||||
? input.resumeCursor
|
||||
: undefined;
|
||||
const model =
|
||||
typeof input === "object" && input !== null && "model" in input && typeof input.model === "string"
|
||||
? input.model
|
||||
: undefined;
|
||||
const threadId =
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"threadId" in input &&
|
||||
typeof input.threadId === "string"
|
||||
? ThreadId.makeUnsafe(input.threadId)
|
||||
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
status: "ready" as const,
|
||||
threadId: ProviderThreadId.makeUnsafe(`provider-thread-${sessionIndex}`),
|
||||
runtimeMode:
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"runtimeMode" in input &&
|
||||
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
|
||||
? input.runtimeMode
|
||||
: "full-access",
|
||||
...(model !== undefined ? { model } : {}),
|
||||
threadId,
|
||||
resumeCursor: resumeCursor ?? { opaque: `cursor-${sessionIndex}` },
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
});
|
||||
};
|
||||
runtimeSessions.push(session);
|
||||
return Effect.succeed(session);
|
||||
});
|
||||
const sendTurn = vi.fn((_: unknown) =>
|
||||
Effect.succeed({
|
||||
threadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
turnId: asProviderTurnId("provider-turn-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
}),
|
||||
);
|
||||
const interruptTurn = vi.fn((_: unknown) => Effect.void);
|
||||
const respondToRequest = vi.fn((_: unknown) => Effect.void);
|
||||
const stopSession = vi.fn((_: unknown) => Effect.void);
|
||||
const renameBranch = vi.fn((_: unknown) =>
|
||||
Effect.succeed({
|
||||
branch: "t3code/generated-name",
|
||||
const respondToRequest = vi.fn<ProviderServiceShape["respondToRequest"]>(() => Effect.void);
|
||||
const respondToUserInput = vi.fn<ProviderServiceShape["respondToUserInput"]>(() => Effect.void);
|
||||
const stopSession = vi.fn((input: unknown) =>
|
||||
Effect.sync(() => {
|
||||
const threadId =
|
||||
typeof input === "object" && input !== null && "threadId" in input
|
||||
? (input as { threadId?: ThreadId }).threadId
|
||||
: undefined;
|
||||
if (!threadId) {
|
||||
return;
|
||||
}
|
||||
const index = runtimeSessions.findIndex((session) => session.threadId === threadId);
|
||||
if (index >= 0) {
|
||||
runtimeSessions.splice(index, 1);
|
||||
}
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn<TextGenerationShape["generateBranchName"]>(() =>
|
||||
const renameBranch = vi.fn((input: unknown) =>
|
||||
Effect.succeed({
|
||||
branch: "generated-name",
|
||||
branch:
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"newBranch" in input &&
|
||||
typeof input.newBranch === "string"
|
||||
? input.newBranch
|
||||
: "renamed-branch",
|
||||
}),
|
||||
);
|
||||
const generateBranchName = vi.fn(() =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "disabled in test harness",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const unsupported = () => Effect.die(new Error("Unsupported provider call in test")) as never;
|
||||
const service: ProviderServiceShape = {
|
||||
@@ -125,10 +180,14 @@ describe("ProviderCommandReactor", () => {
|
||||
sendTurn: sendTurn as ProviderServiceShape["sendTurn"],
|
||||
interruptTurn: interruptTurn as ProviderServiceShape["interruptTurn"],
|
||||
respondToRequest: respondToRequest as ProviderServiceShape["respondToRequest"],
|
||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed([]),
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (provider) =>
|
||||
Effect.succeed({
|
||||
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
stopAll: () => Effect.void,
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
};
|
||||
|
||||
@@ -175,6 +234,8 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -187,6 +248,7 @@ describe("ProviderCommandReactor", () => {
|
||||
sendTurn,
|
||||
interruptTurn,
|
||||
respondToRequest,
|
||||
respondToUserInput,
|
||||
stopSession,
|
||||
renameBranch,
|
||||
generateBranchName,
|
||||
@@ -209,8 +271,8 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello reactor",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -221,256 +283,103 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
cwd: "/tmp/provider-project",
|
||||
model: "gpt-5-codex",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("generates and renames temporary worktree branch on first turn", async () => {
|
||||
it("forwards codex model options through session start and turn send", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/89abc123",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-worktree-rename"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-fast"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-worktree-rename"),
|
||||
messageId: asMessageId("user-message-fast"),
|
||||
role: "user",
|
||||
text: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-rename",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
text: "hello fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.renameBranch.mock.calls.length === 1);
|
||||
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||
message: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-rename",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(harness.renameBranch.mock.calls[0]?.[0]).toEqual({
|
||||
cwd: "/tmp/provider-project/.t3/worktrees/t3code-89abc123",
|
||||
oldBranch: "t3code/89abc123",
|
||||
newBranch: "t3code/generated-name",
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
const readModel = Effect.runSync(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
return thread?.branch === "t3code/generated-name";
|
||||
});
|
||||
});
|
||||
|
||||
it("passes persisted attachment references to branch generation and turn start", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-persisted"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/abcdef12",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-persisted-attachments"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-persisted-attachments"),
|
||||
role: "user",
|
||||
text: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-persisted",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.generateBranchName.mock.calls[0]?.[0]).toEqual({
|
||||
cwd: "/tmp/provider-project/.t3/worktrees/t3code-abcdef12",
|
||||
message: "Fix visual bug from screenshot",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-persisted",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: "thread-1-att-persisted",
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("skips worktree branch generation after the first user turn", async () => {
|
||||
it("forwards plan interaction mode to the provider turn request", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-2"),
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set-plan"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/1234abcd",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-1234abcd",
|
||||
interactionMode: "plan",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-first"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-plan"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-first"),
|
||||
messageId: asMessageId("user-message-plan"),
|
||||
role: "user",
|
||||
text: "first",
|
||||
text: "plan this change",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-second"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-second"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
expect(harness.generateBranchName.mock.calls.length).toBe(1);
|
||||
expect(harness.renameBranch.mock.calls.length).toBe(1);
|
||||
});
|
||||
|
||||
it("skips worktree rename when branch-name generation fails", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
harness.generateBranchName.mockImplementationOnce(() =>
|
||||
Effect.fail(
|
||||
new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "model returned invalid payload",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-set-temp-branch-null"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
branch: "t3code/0000abcd",
|
||||
worktreePath: "/tmp/provider-project/.t3/worktrees/t3code-0000abcd",
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-null-branch"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-null-branch"),
|
||||
role: "user",
|
||||
text: "Fix visual regression",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.generateBranchName.mock.calls.length === 1);
|
||||
await Effect.runPromise(Effect.sleep("20 millis"));
|
||||
expect(harness.renameBranch.mock.calls.length).toBe(0);
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.branch).toBe("t3code/0000abcd");
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
interactionMode: "plan",
|
||||
});
|
||||
});
|
||||
|
||||
it("reuses the same provider session when runtime mode is unchanged", async () => {
|
||||
@@ -488,8 +397,8 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -508,8 +417,8 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -519,10 +428,20 @@ describe("ProviderCommandReactor", () => {
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
it("restarts the provider session when runtime mode changes", async () => {
|
||||
it("restarts the provider session when runtime mode is updated on the thread", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -534,8 +453,8 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "never",
|
||||
sandboxMode: "danger-full-access",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -543,6 +462,22 @@ describe("ProviderCommandReactor", () => {
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -554,37 +489,44 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.stopSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
|
||||
|
||||
expect(harness.stopSession.mock.calls[0]?.[0]).toEqual({ sessionId: asSessionId("sess-1") });
|
||||
expect(harness.stopSession.mock.calls.length).toBe(0);
|
||||
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
|
||||
resumeThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
resumeCursor: { opaque: "cursor-1" },
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
|
||||
sessionId: asSessionId("sess-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerSessionId).toBe("sess-2");
|
||||
expect(thread?.session?.approvalPolicy).toBe("on-request");
|
||||
expect(thread?.session?.sandboxMode).toBe("workspace-write");
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("approval-required");
|
||||
});
|
||||
|
||||
it("does not stop the active session when restart fails before rebind", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-initial-full-access-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -596,8 +538,8 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "never",
|
||||
sandboxMode: "danger-full-access",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -611,21 +553,19 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-restart-failure-2"),
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-restart-failure"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-restart-failure-2"),
|
||||
role: "user",
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
return thread?.runtimeMode === "approval-required";
|
||||
});
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 2);
|
||||
await Effect.runPromise(Effect.sleep("30 millis"));
|
||||
|
||||
@@ -634,9 +574,8 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session?.providerSessionId).toBe("sess-1");
|
||||
expect(thread?.session?.approvalPolicy).toBe("never");
|
||||
expect(thread?.session?.sandboxMode).toBe("danger-full-access");
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.runtimeMode).toBe("full-access");
|
||||
});
|
||||
|
||||
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
|
||||
@@ -652,10 +591,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: asTurnId("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
@@ -676,7 +612,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.interruptTurn.mock.calls.length === 1);
|
||||
expect(harness.interruptTurn.mock.calls[0]?.[0]).toEqual({
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -693,10 +629,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
@@ -718,12 +651,149 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
await waitFor(() => harness.respondToRequest.mock.calls.length === 1);
|
||||
expect(harness.respondToRequest.mock.calls[0]?.[0]).toEqual({
|
||||
sessionId: "sess-1",
|
||||
threadId: "thread-1",
|
||||
requestId: "approval-request-1",
|
||||
decision: "accept",
|
||||
});
|
||||
});
|
||||
|
||||
it("reacts to thread.user-input.respond by forwarding structured user input answers", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.user-input.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-user-input-respond"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
requestId: asApprovalRequestId("user-input-request-1"),
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.respondToUserInput.mock.calls.length === 1);
|
||||
expect(harness.respondToUserInput.mock.calls[0]?.[0]).toEqual({
|
||||
threadId: "thread-1",
|
||||
requestId: "user-input-request-1",
|
||||
answers: {
|
||||
sandbox_mode: "workspace-write",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("surfaces stale provider approval request failures without faking approval resolution", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
harness.respondToRequest.mockImplementation(() =>
|
||||
Effect.fail(
|
||||
new ProviderAdapterRequestError({
|
||||
provider: "codex",
|
||||
method: "session/request_permission",
|
||||
detail: "Unknown pending permission request: approval-request-1",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-for-approval-error"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-requested"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
activity: {
|
||||
id: EventId.makeUnsafe("activity-approval-requested"),
|
||||
tone: "approval",
|
||||
kind: "approval.requested",
|
||||
summary: "Command approval requested",
|
||||
payload: {
|
||||
requestId: "approval-request-1",
|
||||
requestKind: "command",
|
||||
},
|
||||
turnId: null,
|
||||
createdAt: now,
|
||||
},
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond-stale"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
requestId: asApprovalRequestId("approval-request-1"),
|
||||
decision: "acceptForSession",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(async () => {
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
if (!thread) return false;
|
||||
return thread.activities.some((activity) => activity.kind === "provider.approval.respond.failed");
|
||||
});
|
||||
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread).toBeDefined();
|
||||
|
||||
const failureActivity = thread?.activities.find(
|
||||
(activity) => activity.kind === "provider.approval.respond.failed",
|
||||
);
|
||||
expect(failureActivity).toBeDefined();
|
||||
expect(failureActivity?.payload).toMatchObject({
|
||||
requestId: "approval-request-1",
|
||||
});
|
||||
|
||||
const resolvedActivity = thread?.activities.find(
|
||||
(activity) =>
|
||||
activity.kind === "approval.resolved" &&
|
||||
typeof activity.payload === "object" &&
|
||||
activity.payload !== null &&
|
||||
(activity.payload as Record<string, unknown>).requestId === "approval-request-1",
|
||||
);
|
||||
expect(resolvedActivity).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
@@ -737,10 +807,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
providerSessionId: asSessionId("sess-1"),
|
||||
providerThreadId: ProviderThreadId.makeUnsafe("provider-thread-1"),
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: null,
|
||||
lastError: null,
|
||||
updatedAt: now,
|
||||
@@ -763,8 +830,7 @@ describe("ProviderCommandReactor", () => {
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.session).not.toBeNull();
|
||||
expect(thread?.session?.status).toBe("stopped");
|
||||
expect(thread?.session?.providerSessionId).toBeNull();
|
||||
expect(thread?.session?.providerThreadId).toBeNull();
|
||||
expect(thread?.session?.threadId).toBe("thread-1");
|
||||
expect(thread?.session?.activeTurnId).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,19 +3,20 @@ import {
|
||||
CommandId,
|
||||
EventId,
|
||||
type OrchestrationEvent,
|
||||
type ProviderApprovalPolicy,
|
||||
type ProviderModelOptions,
|
||||
type ProviderKind,
|
||||
type ProviderSandboxMode,
|
||||
type ProviderServiceTier,
|
||||
type OrchestrationSession,
|
||||
type ThreadId,
|
||||
ThreadId,
|
||||
type ProviderSession,
|
||||
type ProviderThreadId,
|
||||
type RuntimeMode,
|
||||
type TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Queue, Schema, Stream } from "effect";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
|
||||
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
|
||||
import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
@@ -28,9 +29,11 @@ type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
{
|
||||
type:
|
||||
| "thread.runtime-mode-set"
|
||||
| "thread.turn-start-requested"
|
||||
| "thread.turn-interrupt-requested"
|
||||
| "thread.approval-response-requested"
|
||||
| "thread.user-input-response-requested"
|
||||
| "thread.session-stop-requested";
|
||||
}
|
||||
>;
|
||||
@@ -66,11 +69,36 @@ const serverCommandId = (tag: string): CommandId =>
|
||||
|
||||
const HANDLED_TURN_START_KEY_MAX = 10_000;
|
||||
const HANDLED_TURN_START_KEY_TTL = Duration.minutes(30);
|
||||
const DEFAULT_APPROVAL_POLICY: ProviderApprovalPolicy = "never";
|
||||
const DEFAULT_SANDBOX_MODE: ProviderSandboxMode = "workspace-write";
|
||||
const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
const WORKTREE_BRANCH_PREFIX = "t3code";
|
||||
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
|
||||
|
||||
function toErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error && error.message.trim().length > 0) {
|
||||
return error.message;
|
||||
}
|
||||
try {
|
||||
return JSON.stringify(error);
|
||||
} catch {
|
||||
return String(error);
|
||||
}
|
||||
}
|
||||
|
||||
function isUnknownPendingApprovalRequestError(error: unknown): boolean {
|
||||
if (Schema.is(ProviderAdapterRequestError)(error)) {
|
||||
const detail = error.detail.toLowerCase();
|
||||
return (
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
const message = toErrorMessage(error).toLowerCase();
|
||||
return (
|
||||
message.includes("unknown pending approval request") ||
|
||||
message.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function isTemporaryWorktreeBranch(branch: string): boolean {
|
||||
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
|
||||
}
|
||||
@@ -122,11 +150,13 @@ const make = Effect.gen(function* () {
|
||||
| "provider.turn.start.failed"
|
||||
| "provider.turn.interrupt.failed"
|
||||
| "provider.approval.respond.failed"
|
||||
| "provider.user-input.respond.failed"
|
||||
| "provider.session.stop.failed";
|
||||
readonly summary: string;
|
||||
readonly detail: string;
|
||||
readonly turnId: TurnId | null;
|
||||
readonly createdAt: string;
|
||||
readonly requestId?: string;
|
||||
}) =>
|
||||
orchestrationEngine.dispatch({
|
||||
type: "thread.activity.append",
|
||||
@@ -139,6 +169,7 @@ const make = Effect.gen(function* () {
|
||||
summary: input.summary,
|
||||
payload: {
|
||||
detail: input.detail,
|
||||
...(input.requestId ? { requestId: input.requestId } : {}),
|
||||
},
|
||||
turnId: input.turnId,
|
||||
createdAt: input.createdAt,
|
||||
@@ -168,8 +199,10 @@ const make = Effect.gen(function* () {
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly approvalPolicy?: ProviderApprovalPolicy;
|
||||
readonly sandboxMode?: ProviderSandboxMode;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly serviceTier?: ProviderServiceTier | null;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -178,27 +211,36 @@ const make = Effect.gen(function* () {
|
||||
return yield* Effect.die(new Error(`Thread '${threadId}' was not found in read model.`));
|
||||
}
|
||||
|
||||
const desiredApprovalPolicy =
|
||||
options?.approvalPolicy ?? thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY;
|
||||
const desiredSandboxMode =
|
||||
options?.sandboxMode ?? thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE;
|
||||
const preferredProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" || thread.session?.providerName === "claudeCode"
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
const desiredRuntimeMode = thread.runtimeMode;
|
||||
const currentProvider: ProviderKind | undefined =
|
||||
thread.session?.providerName === "codex" ? thread.session.providerName : undefined;
|
||||
const preferredProvider: ProviderKind | undefined = options?.provider ?? currentProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
});
|
||||
|
||||
const startProviderSession = (resumeThreadId?: ProviderThreadId | null) =>
|
||||
const resolveActiveSession = (threadId: ThreadId) =>
|
||||
providerService.listSessions().pipe(
|
||||
Effect.map((sessions) => sessions.find((session) => session.threadId === threadId)),
|
||||
);
|
||||
|
||||
const startProviderSession = (input?: {
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly provider?: ProviderKind;
|
||||
}) =>
|
||||
providerService.startSession(threadId, {
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
threadId,
|
||||
...(input?.provider ?? preferredProvider
|
||||
? { provider: input?.provider ?? preferredProvider }
|
||||
: {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
...(thread.model ? { model: thread.model } : {}),
|
||||
...(resumeThreadId ? { resumeThreadId } : {}),
|
||||
approvalPolicy: desiredApprovalPolicy,
|
||||
sandboxMode: desiredSandboxMode,
|
||||
...(desiredModel ? { model: desiredModel } : {}),
|
||||
...(options?.serviceTier !== undefined ? { serviceTier: options.serviceTier } : {}),
|
||||
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
|
||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
});
|
||||
|
||||
const bindSessionToThread = (session: ProviderSession) =>
|
||||
@@ -208,10 +250,7 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
status: mapProviderSessionStatusToOrchestrationStatus(session.status),
|
||||
providerName: session.provider,
|
||||
providerSessionId: session.sessionId,
|
||||
providerThreadId: session.threadId ?? null,
|
||||
approvalPolicy: desiredApprovalPolicy,
|
||||
sandboxMode: desiredSandboxMode,
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
// Provider turn ids are not orchestration turn ids.
|
||||
activeTurnId: null,
|
||||
lastError: session.lastError ?? null,
|
||||
@@ -220,66 +259,105 @@ const make = Effect.gen(function* () {
|
||||
createdAt,
|
||||
});
|
||||
|
||||
const existingSessionId = thread.session?.providerSessionId;
|
||||
if (existingSessionId) {
|
||||
const approvalPolicyChanged =
|
||||
options?.approvalPolicy !== undefined &&
|
||||
options.approvalPolicy !== thread.session?.approvalPolicy;
|
||||
const sandboxModeChanged =
|
||||
options?.sandboxMode !== undefined && options.sandboxMode !== thread.session?.sandboxMode;
|
||||
const existingSessionThreadId =
|
||||
thread.session && thread.session.status !== "stopped" ? thread.id : null;
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged = options?.provider !== undefined && options.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||
const modelChanged =
|
||||
options?.model !== undefined && options.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange =
|
||||
modelChanged && sessionModelSwitch === "restart-session";
|
||||
|
||||
if (!approvalPolicyChanged && !sandboxModeChanged) {
|
||||
return existingSessionId;
|
||||
if (!runtimeModeChanged && !providerChanged && !shouldRestartForModelChange) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
|
||||
const restartedSession = yield* startProviderSession(
|
||||
thread.session?.providerThreadId ?? null,
|
||||
);
|
||||
const resumeCursor =
|
||||
providerChanged || shouldRestartForModelChange
|
||||
? undefined
|
||||
: (activeSession?.resumeCursor ?? undefined);
|
||||
yield* Effect.logInfo("provider command reactor restarting provider session", {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
currentProvider,
|
||||
desiredProvider: options?.provider ?? currentProvider,
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
...(resumeCursor !== undefined ? { resumeCursor } : {}),
|
||||
...(options?.provider !== undefined ? { provider: options.provider } : {}),
|
||||
});
|
||||
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
||||
threadId,
|
||||
previousSessionId: existingSessionThreadId,
|
||||
restartedSessionThreadId: restartedSession.threadId,
|
||||
provider: restartedSession.provider,
|
||||
runtimeMode: restartedSession.runtimeMode,
|
||||
});
|
||||
yield* bindSessionToThread(restartedSession);
|
||||
yield* providerService.stopSession({ sessionId: existingSessionId }).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to stop superseded provider session", {
|
||||
threadId,
|
||||
sessionId: existingSessionId,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
),
|
||||
);
|
||||
return restartedSession.sessionId;
|
||||
return restartedSession.threadId;
|
||||
}
|
||||
|
||||
const startedSession = yield* startProviderSession();
|
||||
const startedSession = yield* startProviderSession(
|
||||
options?.provider !== undefined ? { provider: options.provider } : undefined,
|
||||
);
|
||||
yield* bindSessionToThread(startedSession);
|
||||
return startedSession.sessionId;
|
||||
return startedSession.threadId;
|
||||
});
|
||||
|
||||
const sendTurnForThread = Effect.fnUntraced(function* (input: {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly effort?: string;
|
||||
readonly approvalPolicy: ProviderApprovalPolicy;
|
||||
readonly sandboxMode: ProviderSandboxMode;
|
||||
readonly serviceTier?: ProviderServiceTier | null;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
const thread = yield* resolveThread(input.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const sessionId = yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
approvalPolicy: input.approvalPolicy,
|
||||
sandboxMode: input.sandboxMode,
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
});
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
const activeSession = yield* providerService.listSessions().pipe(
|
||||
Effect.map((sessions) => sessions.find((session) => session.threadId === input.threadId)),
|
||||
);
|
||||
const sessionModelSwitch =
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
sessionId,
|
||||
threadId: input.threadId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.effort !== undefined ? { effort: input.effort } : {}),
|
||||
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
|
||||
...(input.serviceTier !== undefined ? { serviceTier: input.serviceTier } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -390,10 +468,11 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.effort !== undefined ? { effort: event.payload.effort } : {}),
|
||||
approvalPolicy: event.payload.approvalPolicy,
|
||||
sandboxMode: event.payload.sandboxMode,
|
||||
...(event.payload.serviceTier !== undefined ? { serviceTier: event.payload.serviceTier } : {}),
|
||||
...(event.payload.modelOptions !== undefined ? { modelOptions: event.payload.modelOptions } : {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
});
|
||||
});
|
||||
@@ -405,8 +484,8 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
if (!sessionId) {
|
||||
const hasSession = thread.session && thread.session.status !== "stopped";
|
||||
if (!hasSession) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.turn.interrupt.failed",
|
||||
@@ -418,7 +497,7 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
// Orchestration turn ids are not provider turn ids, so interrupt by session.
|
||||
yield* providerService.interruptTurn({ sessionId });
|
||||
yield* providerService.interruptTurn({ threadId: event.payload.threadId });
|
||||
});
|
||||
|
||||
const processApprovalResponseRequested = Effect.fnUntraced(function* (
|
||||
@@ -428,8 +507,8 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
if (!sessionId) {
|
||||
const hasSession = thread.session && thread.session.status !== "stopped";
|
||||
if (!hasSession) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
@@ -437,14 +516,79 @@ const make = Effect.gen(function* () {
|
||||
detail: "No active provider session is bound to this thread.",
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
}
|
||||
|
||||
yield* providerService.respondToRequest({
|
||||
sessionId,
|
||||
requestId: event.payload.requestId,
|
||||
decision: event.payload.decision,
|
||||
});
|
||||
yield* providerService
|
||||
.respondToRequest({
|
||||
threadId: event.payload.threadId,
|
||||
requestId: event.payload.requestId,
|
||||
decision: event.payload.decision,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
const error = Cause.squash(cause);
|
||||
const detail = toErrorMessage(error);
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.approval.respond.failed",
|
||||
summary: "Provider approval response failed",
|
||||
detail,
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
|
||||
if (!isUnknownPendingApprovalRequestError(error)) return;
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const processUserInputResponseRequested = Effect.fnUntraced(function* (
|
||||
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
|
||||
) {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
const hasSession = thread.session && thread.session.status !== "stopped";
|
||||
if (!hasSession) {
|
||||
return yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
detail: "No active provider session is bound to this thread.",
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
}
|
||||
|
||||
yield* providerService
|
||||
.respondToUserInput({
|
||||
threadId: event.payload.threadId,
|
||||
requestId: event.payload.requestId,
|
||||
answers: event.payload.answers,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.gen(function* () {
|
||||
const error = Cause.squash(cause);
|
||||
yield* appendProviderFailureActivity({
|
||||
threadId: event.payload.threadId,
|
||||
kind: "provider.user-input.respond.failed",
|
||||
summary: "Provider user input response failed",
|
||||
detail: toErrorMessage(error),
|
||||
turnId: null,
|
||||
createdAt: event.payload.createdAt,
|
||||
requestId: event.payload.requestId,
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const processSessionStopRequested = Effect.fnUntraced(function* (
|
||||
@@ -456,10 +600,8 @@ const make = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
const now = event.payload.createdAt;
|
||||
const sessionId = thread.session?.providerSessionId;
|
||||
|
||||
if (sessionId) {
|
||||
yield* providerService.stopSession({ sessionId });
|
||||
if (thread.session && thread.session.status !== "stopped") {
|
||||
yield* providerService.stopSession({ threadId: thread.id });
|
||||
}
|
||||
|
||||
yield* setThreadSession({
|
||||
@@ -468,10 +610,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: thread.id,
|
||||
status: "stopped",
|
||||
providerName: thread.session?.providerName ?? null,
|
||||
providerSessionId: null,
|
||||
providerThreadId: null,
|
||||
approvalPolicy: thread.session?.approvalPolicy ?? DEFAULT_APPROVAL_POLICY,
|
||||
sandboxMode: thread.session?.sandboxMode ?? DEFAULT_SANDBOX_MODE,
|
||||
runtimeMode: thread.session?.runtimeMode ?? DEFAULT_RUNTIME_MODE,
|
||||
activeTurnId: null,
|
||||
lastError: thread.session?.lastError ?? null,
|
||||
updatedAt: now,
|
||||
@@ -483,6 +622,14 @@ const make = Effect.gen(function* () {
|
||||
const processDomainEvent = (event: ProviderIntentEvent) =>
|
||||
Effect.gen(function* () {
|
||||
switch (event.type) {
|
||||
case "thread.runtime-mode-set": {
|
||||
const thread = yield* resolveThread(event.payload.threadId);
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt);
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
yield* processTurnStartRequested(event);
|
||||
return;
|
||||
@@ -492,6 +639,9 @@ const make = Effect.gen(function* () {
|
||||
case "thread.approval-response-requested":
|
||||
yield* processApprovalResponseRequested(event);
|
||||
return;
|
||||
case "thread.user-input-response-requested":
|
||||
yield* processUserInputResponseRequested(event);
|
||||
return;
|
||||
case "thread.session-stop-requested":
|
||||
yield* processSessionStopRequested(event);
|
||||
return;
|
||||
@@ -522,9 +672,11 @@ const make = Effect.gen(function* () {
|
||||
yield* Effect.forkScoped(
|
||||
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
|
||||
if (
|
||||
event.type !== "thread.runtime-mode-set" &&
|
||||
event.type !== "thread.turn-start-requested" &&
|
||||
event.type !== "thread.turn-interrupt-requested" &&
|
||||
event.type !== "thread.approval-response-requested" &&
|
||||
event.type !== "thread.user-input-response-requested" &&
|
||||
event.type !== "thread.session-stop-requested"
|
||||
) {
|
||||
return Effect.void;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -4,8 +4,11 @@ import {
|
||||
ProjectDeletedPayload as ContractsProjectDeletedPayloadSchema,
|
||||
ThreadCreatedPayload as ContractsThreadCreatedPayloadSchema,
|
||||
ThreadMetaUpdatedPayload as ContractsThreadMetaUpdatedPayloadSchema,
|
||||
ThreadRuntimeModeSetPayload as ContractsThreadRuntimeModeSetPayloadSchema,
|
||||
ThreadInteractionModeSetPayload as ContractsThreadInteractionModeSetPayloadSchema,
|
||||
ThreadDeletedPayload as ContractsThreadDeletedPayloadSchema,
|
||||
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
|
||||
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
|
||||
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
|
||||
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
|
||||
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
|
||||
@@ -24,9 +27,12 @@ export const ProjectDeletedPayload = ContractsProjectDeletedPayloadSchema;
|
||||
|
||||
export const ThreadCreatedPayload = ContractsThreadCreatedPayloadSchema;
|
||||
export const ThreadMetaUpdatedPayload = ContractsThreadMetaUpdatedPayloadSchema;
|
||||
export const ThreadRuntimeModeSetPayload = ContractsThreadRuntimeModeSetPayloadSchema;
|
||||
export const ThreadInteractionModeSetPayload = ContractsThreadInteractionModeSetPayloadSchema;
|
||||
export const ThreadDeletedPayload = ContractsThreadDeletedPayloadSchema;
|
||||
|
||||
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
|
||||
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
|
||||
export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
|
||||
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
|
||||
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
MessageId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type OrchestrationCommand,
|
||||
@@ -50,6 +51,8 @@ const readModel: OrchestrationReadModel = {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -58,6 +61,7 @@ const readModel: OrchestrationReadModel = {
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
@@ -66,6 +70,8 @@ const readModel: OrchestrationReadModel = {
|
||||
projectId: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Thread B",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -74,6 +80,7 @@ const readModel: OrchestrationReadModel = {
|
||||
messages: [],
|
||||
session: null,
|
||||
activities: [],
|
||||
proposedPlans: [],
|
||||
checkpoints: [],
|
||||
deletedAt: null,
|
||||
},
|
||||
@@ -90,8 +97,8 @@ const messageSendCommand: OrchestrationCommand = {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
};
|
||||
|
||||
@@ -138,6 +145,8 @@ describe("commandInvariants", () => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "new",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -157,6 +166,8 @@ describe("commandInvariants", () => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "dup",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
|
||||
@@ -1,4 +1,11 @@
|
||||
import { CommandId, EventId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
@@ -130,6 +137,8 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -150,10 +159,16 @@ describe("decider project scripts", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
model: "gpt-5",
|
||||
effort: "high",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
@@ -174,10 +189,173 @@ describe("decider project scripts", () => {
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
model: "gpt-5",
|
||||
effort: "high",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
});
|
||||
|
||||
it("emits thread.runtime-mode-set from thread.runtime-mode.set", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = await Effect.runPromise(
|
||||
projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.runtime-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
const singleResult = Array.isArray(result) ? null : result;
|
||||
if (singleResult === null) {
|
||||
throw new Error("Expected a single runtime-mode-set event.");
|
||||
}
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
runtimeMode: "approval-required",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("emits thread.interaction-mode-set from thread.interaction-mode.set", async () => {
|
||||
const now = new Date().toISOString();
|
||||
const initial = createEmptyReadModel(now);
|
||||
const withProject = await Effect.runPromise(
|
||||
projectEvent(initial, {
|
||||
sequence: 1,
|
||||
eventId: asEventId("evt-project-create"),
|
||||
aggregateKind: "project",
|
||||
aggregateId: asProjectId("project-1"),
|
||||
type: "project.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
const readModel = await Effect.runPromise(
|
||||
projectEvent(withProject, {
|
||||
sequence: 2,
|
||||
eventId: asEventId("evt-thread-create"),
|
||||
aggregateKind: "thread",
|
||||
aggregateId: ThreadId.makeUnsafe("thread-1"),
|
||||
type: "thread.created",
|
||||
occurredAt: now,
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
causationEventId: null,
|
||||
correlationId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
metadata: {},
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
decideOrchestrationCommand({
|
||||
command: {
|
||||
type: "thread.interaction-mode.set",
|
||||
commandId: CommandId.makeUnsafe("cmd-interaction-mode-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
interactionMode: "plan",
|
||||
createdAt: now,
|
||||
},
|
||||
readModel,
|
||||
}),
|
||||
);
|
||||
|
||||
const singleResult = Array.isArray(result) ? null : result;
|
||||
if (singleResult === null) {
|
||||
throw new Error("Expected a single interaction-mode-set event.");
|
||||
}
|
||||
expect(singleResult).toMatchObject({
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
interactionMode: "plan",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -144,7 +144,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
const threadCreatedEvent: Omit<OrchestrationEvent, "sequence"> = {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
@@ -157,12 +157,40 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
model: command.model,
|
||||
runtimeMode: command.runtimeMode,
|
||||
interactionMode: command.interactionMode,
|
||||
branch: command.branch,
|
||||
worktreePath: command.worktreePath,
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
|
||||
const seedMessageEvents: ReadonlyArray<Omit<OrchestrationEvent, "sequence">> =
|
||||
command.seedMessages?.map((message) => ({
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.message-sent" as const,
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: message.messageId,
|
||||
role: message.role,
|
||||
text: message.text,
|
||||
attachments: message.attachments,
|
||||
turnId: null,
|
||||
streaming: false,
|
||||
createdAt: message.createdAt,
|
||||
updatedAt: message.updatedAt,
|
||||
},
|
||||
})) ?? [];
|
||||
|
||||
return seedMessageEvents.length > 0
|
||||
? [threadCreatedEvent, ...seedMessageEvents]
|
||||
: threadCreatedEvent;
|
||||
}
|
||||
|
||||
case "thread.delete": {
|
||||
@@ -213,6 +241,52 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.runtime-mode.set": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.runtime-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
runtimeMode: command.runtimeMode,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.interaction-mode.set": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
const occurredAt = nowIso();
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.interaction-mode-set",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
interactionMode: command.interactionMode,
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.turn.start": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
@@ -251,11 +325,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
...(command.provider !== undefined ? { provider: command.provider } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.effort !== undefined ? { effort: command.effort } : {}),
|
||||
...(command.serviceTier !== undefined ? { serviceTier: command.serviceTier } : {}),
|
||||
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
approvalPolicy: command.approvalPolicy,
|
||||
sandboxMode: command.sandboxMode,
|
||||
runtimeMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.runtimeMode ??
|
||||
command.runtimeMode,
|
||||
interactionMode:
|
||||
readModel.threads.find((entry) => entry.id === command.threadId)?.interactionMode ??
|
||||
command.interactionMode,
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
@@ -310,6 +390,32 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.user-input.respond": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: {
|
||||
requestId: command.requestId,
|
||||
},
|
||||
}),
|
||||
type: "thread.user-input-response-requested",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
requestId: command.requestId,
|
||||
answers: command.answers,
|
||||
createdAt: command.createdAt,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.checkpoint.revert": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
@@ -365,14 +471,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
metadata: {
|
||||
...(command.session.providerSessionId !== null
|
||||
? { providerSessionId: command.session.providerSessionId }
|
||||
: {}),
|
||||
...(command.session.providerThreadId !== null
|
||||
? { providerThreadId: command.session.providerThreadId }
|
||||
: {}),
|
||||
},
|
||||
metadata: {},
|
||||
}),
|
||||
type: "thread.session-set",
|
||||
payload: {
|
||||
@@ -436,6 +535,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.proposed-plan.upsert": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
command,
|
||||
threadId: command.threadId,
|
||||
});
|
||||
return {
|
||||
...withEventBase({
|
||||
aggregateKind: "thread",
|
||||
aggregateId: command.threadId,
|
||||
occurredAt: command.createdAt,
|
||||
commandId: command.commandId,
|
||||
}),
|
||||
type: "thread.proposed-plan-upserted",
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
proposedPlan: command.proposedPlan,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
case "thread.turn.diff.complete": {
|
||||
yield* requireThread({
|
||||
readModel,
|
||||
|
||||
@@ -57,6 +57,7 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -73,6 +74,8 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
latestTurn: null,
|
||||
@@ -80,6 +83,7 @@ describe("orchestration projector", () => {
|
||||
updatedAt: now,
|
||||
deletedAt: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
activities: [],
|
||||
checkpoints: [],
|
||||
session: null,
|
||||
@@ -135,8 +139,7 @@ describe("orchestration projector", () => {
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
messageId: "message-1",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
}),
|
||||
@@ -168,6 +171,7 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -195,8 +199,7 @@ describe("orchestration projector", () => {
|
||||
providerName: "codex",
|
||||
providerSessionId: "session-1",
|
||||
providerThreadId: "provider-thread-1",
|
||||
approvalPolicy: "on-request",
|
||||
sandboxMode: "workspace-write",
|
||||
runtimeMode: "approval-required",
|
||||
activeTurnId: "turn-1",
|
||||
lastError: null,
|
||||
updatedAt: startedAt,
|
||||
@@ -211,6 +214,59 @@ describe("orchestration projector", () => {
|
||||
expect(thread?.session?.status).toBe("running");
|
||||
});
|
||||
|
||||
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
|
||||
const createdAt = "2026-02-23T08:00:00.000Z";
|
||||
const updatedAt = "2026-02-23T08:00:05.000Z";
|
||||
const model = createEmptyReadModel(createdAt);
|
||||
|
||||
const afterCreate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
model,
|
||||
makeEvent({
|
||||
sequence: 1,
|
||||
type: "thread.created",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: createdAt,
|
||||
commandId: "cmd-create",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const afterUpdate = await Effect.runPromise(
|
||||
projectEvent(
|
||||
afterCreate,
|
||||
makeEvent({
|
||||
sequence: 2,
|
||||
type: "thread.runtime-mode-set",
|
||||
aggregateKind: "thread",
|
||||
aggregateId: "thread-1",
|
||||
occurredAt: updatedAt,
|
||||
commandId: "cmd-runtime-mode-set",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
runtimeMode: "approval-required",
|
||||
updatedAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(afterUpdate.threads[0]?.runtimeMode).toBe("approval-required");
|
||||
expect(afterUpdate.threads[0]?.updatedAt).toBe(updatedAt);
|
||||
});
|
||||
|
||||
it("marks assistant messages completed with non-streaming updates", async () => {
|
||||
const createdAt = "2026-02-23T09:00:00.000Z";
|
||||
const deltaAt = "2026-02-23T09:00:01.000Z";
|
||||
@@ -232,6 +288,7 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -315,6 +372,7 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -526,6 +584,7 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
@@ -675,6 +734,7 @@ describe("orchestration projector", () => {
|
||||
projectId: "project-1",
|
||||
title: "capped",
|
||||
model: "gpt-5-codex",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt,
|
||||
|
||||
@@ -16,7 +16,10 @@ import {
|
||||
ThreadActivityAppendedPayload,
|
||||
ThreadCreatedPayload,
|
||||
ThreadDeletedPayload,
|
||||
ThreadInteractionModeSetPayload,
|
||||
ThreadMetaUpdatedPayload,
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
ThreadRuntimeModeSetPayload,
|
||||
ThreadRevertedPayload,
|
||||
ThreadSessionSetPayload,
|
||||
ThreadTurnDiffCompletedPayload,
|
||||
@@ -124,6 +127,32 @@ function retainThreadActivitiesAfterRevert(
|
||||
);
|
||||
}
|
||||
|
||||
function retainThreadProposedPlansAfterRevert(
|
||||
proposedPlans: ReadonlyArray<OrchestrationThread["proposedPlans"][number]>,
|
||||
retainedTurnIds: ReadonlySet<string>,
|
||||
): ReadonlyArray<OrchestrationThread["proposedPlans"][number]> {
|
||||
return proposedPlans.filter(
|
||||
(proposedPlan) => proposedPlan.turnId === null || retainedTurnIds.has(proposedPlan.turnId),
|
||||
);
|
||||
}
|
||||
|
||||
function compareThreadActivities(
|
||||
left: OrchestrationThread["activities"][number],
|
||||
right: OrchestrationThread["activities"][number],
|
||||
): number {
|
||||
if (left.sequence !== undefined && right.sequence !== undefined) {
|
||||
if (left.sequence !== right.sequence) {
|
||||
return left.sequence - right.sequence;
|
||||
}
|
||||
} else if (left.sequence !== undefined) {
|
||||
return 1;
|
||||
} else if (right.sequence !== undefined) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
|
||||
}
|
||||
|
||||
export function createEmptyReadModel(nowIso: string): OrchestrationReadModel {
|
||||
return {
|
||||
snapshotSequence: 0,
|
||||
@@ -224,6 +253,8 @@ export function projectEvent(
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
runtimeMode: payload.runtimeMode,
|
||||
interactionMode: payload.interactionMode,
|
||||
branch: payload.branch,
|
||||
worktreePath: payload.worktreePath,
|
||||
latestTurn: null,
|
||||
@@ -272,6 +303,38 @@ export function projectEvent(
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.runtime-mode-set":
|
||||
return decodeForEvent(
|
||||
ThreadRuntimeModeSetPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
runtimeMode: payload.runtimeMode,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.interaction-mode-set":
|
||||
return decodeForEvent(
|
||||
ThreadInteractionModeSetPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
).pipe(
|
||||
Effect.map((payload) => ({
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
interactionMode: payload.interactionMode,
|
||||
updatedAt: payload.updatedAt,
|
||||
}),
|
||||
})),
|
||||
);
|
||||
|
||||
case "thread.message-sent":
|
||||
return Effect.gen(function* () {
|
||||
const payload = yield* decodeForEvent(
|
||||
@@ -382,6 +445,38 @@ export function projectEvent(
|
||||
};
|
||||
});
|
||||
|
||||
case "thread.proposed-plan-upserted":
|
||||
return Effect.gen(function* () {
|
||||
const payload = yield* decodeForEvent(
|
||||
ThreadProposedPlanUpsertedPayload,
|
||||
event.payload,
|
||||
event.type,
|
||||
"payload",
|
||||
);
|
||||
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
|
||||
if (!thread) {
|
||||
return nextBase;
|
||||
}
|
||||
|
||||
const proposedPlans = [
|
||||
...thread.proposedPlans.filter((entry) => entry.id !== payload.proposedPlan.id),
|
||||
payload.proposedPlan,
|
||||
]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
|
||||
)
|
||||
.slice(-200);
|
||||
|
||||
return {
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
proposedPlans,
|
||||
updatedAt: event.occurredAt,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
case "thread.turn-diff-completed":
|
||||
return Effect.gen(function* () {
|
||||
const payload = yield* decodeForEvent(
|
||||
@@ -458,6 +553,10 @@ export function projectEvent(
|
||||
retainedTurnIds,
|
||||
payload.turnCount,
|
||||
).slice(-MAX_THREAD_MESSAGES);
|
||||
const proposedPlans = retainThreadProposedPlansAfterRevert(
|
||||
thread.proposedPlans,
|
||||
retainedTurnIds,
|
||||
).slice(-200);
|
||||
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
|
||||
|
||||
const latestCheckpoint = checkpoints.at(-1) ?? null;
|
||||
@@ -478,6 +577,7 @@ export function projectEvent(
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
checkpoints,
|
||||
messages,
|
||||
proposedPlans,
|
||||
activities,
|
||||
latestTurn,
|
||||
updatedAt: event.occurredAt,
|
||||
@@ -503,7 +603,7 @@ export function projectEvent(
|
||||
...thread.activities.filter((entry) => entry.id !== payload.activity.id),
|
||||
payload.activity,
|
||||
]
|
||||
.toSorted((left, right) => left.createdAt.localeCompare(right.createdAt))
|
||||
.toSorted(compareThreadActivities)
|
||||
.slice(-500);
|
||||
|
||||
return {
|
||||
|
||||
@@ -74,8 +74,6 @@ function inferActorKind(
|
||||
return "server";
|
||||
}
|
||||
if (
|
||||
event.metadata.providerSessionId !== undefined ||
|
||||
event.metadata.providerThreadId !== undefined ||
|
||||
event.metadata.providerTurnId !== undefined ||
|
||||
event.metadata.providerItemId !== undefined ||
|
||||
event.metadata.adapterKey !== undefined
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { NonNegativeInt } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
sequence: Schema.NullOr(NonNegativeInt),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -29,7 +31,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionThreadActivityRow = SqlSchema.void({
|
||||
Request: ProjectionThreadActivityDbRowSchema,
|
||||
Request: ProjectionThreadActivity,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
INSERT INTO projection_thread_activities (
|
||||
@@ -40,6 +42,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
kind,
|
||||
summary,
|
||||
payload_json,
|
||||
sequence,
|
||||
created_at
|
||||
)
|
||||
VALUES (
|
||||
@@ -49,7 +52,8 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
${row.tone},
|
||||
${row.kind},
|
||||
${row.summary},
|
||||
${row.payload},
|
||||
${JSON.stringify(row.payload)},
|
||||
${row.sequence ?? null},
|
||||
${row.createdAt}
|
||||
)
|
||||
ON CONFLICT (activity_id)
|
||||
@@ -60,6 +64,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
kind = excluded.kind,
|
||||
summary = excluded.summary,
|
||||
payload_json = excluded.payload_json,
|
||||
sequence = excluded.sequence,
|
||||
created_at = excluded.created_at
|
||||
`,
|
||||
});
|
||||
@@ -77,10 +82,15 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
kind,
|
||||
summary,
|
||||
payload_json AS "payload",
|
||||
sequence,
|
||||
created_at AS "createdAt"
|
||||
FROM projection_thread_activities
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, activity_id ASC
|
||||
ORDER BY
|
||||
CASE WHEN sequence IS NULL THEN 0 ELSE 1 END ASC,
|
||||
sequence ASC,
|
||||
created_at ASC,
|
||||
activity_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -111,8 +121,18 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
|
||||
"ProjectionThreadActivityRepository.listByThreadId:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map(
|
||||
(rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionThreadActivity>>,
|
||||
Effect.map((rows) =>
|
||||
rows.map((row) => ({
|
||||
activityId: row.activityId,
|
||||
threadId: row.threadId,
|
||||
turnId: row.turnId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
})),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import { Effect, Layer } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadProposedPlansInput,
|
||||
ListProjectionThreadProposedPlansInput,
|
||||
ProjectionThreadProposedPlan,
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
type ProjectionThreadProposedPlanRepositoryShape,
|
||||
} from "../Services/ProjectionThreadProposedPlans.ts";
|
||||
|
||||
const makeProjectionThreadProposedPlanRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionThreadProposedPlanRow = SqlSchema.void({
|
||||
Request: ProjectionThreadProposedPlan,
|
||||
execute: (row) => sql`
|
||||
INSERT INTO projection_thread_proposed_plans (
|
||||
plan_id,
|
||||
thread_id,
|
||||
turn_id,
|
||||
plan_markdown,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
${row.planId},
|
||||
${row.threadId},
|
||||
${row.turnId},
|
||||
${row.planMarkdown},
|
||||
${row.createdAt},
|
||||
${row.updatedAt}
|
||||
)
|
||||
ON CONFLICT (plan_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
turn_id = excluded.turn_id,
|
||||
plan_markdown = excluded.plan_markdown,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at
|
||||
`,
|
||||
});
|
||||
|
||||
const listProjectionThreadProposedPlanRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadProposedPlansInput,
|
||||
Result: ProjectionThreadProposedPlan,
|
||||
execute: ({ threadId }) => sql`
|
||||
SELECT
|
||||
plan_id AS "planId",
|
||||
thread_id AS "threadId",
|
||||
turn_id AS "turnId",
|
||||
plan_markdown AS "planMarkdown",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
ORDER BY created_at ASC, plan_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteProjectionThreadProposedPlanRows = SqlSchema.void({
|
||||
Request: DeleteProjectionThreadProposedPlansInput,
|
||||
execute: ({ threadId }) => sql`
|
||||
DELETE FROM projection_thread_proposed_plans
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
const upsert: ProjectionThreadProposedPlanRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionThreadProposedPlanRow(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.upsert:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const listByThreadId: ProjectionThreadProposedPlanRepositoryShape["listByThreadId"] = (input) =>
|
||||
listProjectionThreadProposedPlanRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.listByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteByThreadId: ProjectionThreadProposedPlanRepositoryShape["deleteByThreadId"] = (
|
||||
input,
|
||||
) =>
|
||||
deleteProjectionThreadProposedPlanRows(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProjectionThreadProposedPlanRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
listByThreadId,
|
||||
deleteByThreadId,
|
||||
} satisfies ProjectionThreadProposedPlanRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProjectionThreadProposedPlanRepositoryLive = Layer.effect(
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
makeProjectionThreadProposedPlanRepository,
|
||||
);
|
||||
@@ -23,10 +23,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
status,
|
||||
provider_name,
|
||||
provider_session_id,
|
||||
provider_thread_id,
|
||||
approval_policy,
|
||||
sandbox_mode,
|
||||
runtime_mode,
|
||||
active_turn_id,
|
||||
last_error,
|
||||
updated_at
|
||||
@@ -35,10 +32,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.status},
|
||||
${row.providerName},
|
||||
${row.providerSessionId},
|
||||
${row.providerThreadId},
|
||||
${row.approvalPolicy},
|
||||
${row.sandboxMode},
|
||||
${row.runtimeMode},
|
||||
${row.activeTurnId},
|
||||
${row.lastError},
|
||||
${row.updatedAt}
|
||||
@@ -47,10 +41,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
status = excluded.status,
|
||||
provider_name = excluded.provider_name,
|
||||
provider_session_id = excluded.provider_session_id,
|
||||
provider_thread_id = excluded.provider_thread_id,
|
||||
approval_policy = excluded.approval_policy,
|
||||
sandbox_mode = excluded.sandbox_mode,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
active_turn_id = excluded.active_turn_id,
|
||||
last_error = excluded.last_error,
|
||||
updated_at = excluded.updated_at
|
||||
@@ -66,10 +57,7 @@ const makeProjectionThreadSessionRepository = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
status,
|
||||
provider_name AS "providerName",
|
||||
provider_session_id AS "providerSessionId",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
approval_policy AS "approvalPolicy",
|
||||
sandbox_mode AS "sandboxMode",
|
||||
runtime_mode AS "runtimeMode",
|
||||
active_turn_id AS "activeTurnId",
|
||||
last_error AS "lastError",
|
||||
updated_at AS "updatedAt"
|
||||
|
||||
@@ -24,6 +24,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
@@ -36,6 +38,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.model},
|
||||
${row.runtimeMode},
|
||||
${row.interactionMode},
|
||||
${row.branch},
|
||||
${row.worktreePath},
|
||||
${row.latestTurnId},
|
||||
@@ -48,6 +52,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id = excluded.project_id,
|
||||
title = excluded.title,
|
||||
model = excluded.model,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
branch = excluded.branch,
|
||||
worktree_path = excluded.worktree_path,
|
||||
latest_turn_id = excluded.latest_turn_id,
|
||||
@@ -67,6 +73,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
@@ -88,6 +96,8 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
worktree_path AS "worktreePath",
|
||||
latest_turn_id AS "latestTurnId",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ProviderSessionId } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema, Struct } from "effect";
|
||||
@@ -24,7 +24,7 @@ const ProviderSessionRuntimeDbRowSchema = ProviderSessionRuntime.mapFields(
|
||||
const decodeRuntime = Schema.decodeUnknownEffect(ProviderSessionRuntime);
|
||||
|
||||
const GetRuntimeRequestSchema = Schema.Struct({
|
||||
providerSessionId: ProviderSessionId,
|
||||
threadId: ThreadId,
|
||||
});
|
||||
|
||||
const DeleteRuntimeRequestSchema = GetRuntimeRequestSchema;
|
||||
@@ -44,33 +44,30 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
execute: (runtime) =>
|
||||
sql`
|
||||
INSERT INTO provider_session_runtime (
|
||||
provider_session_id,
|
||||
thread_id,
|
||||
provider_name,
|
||||
adapter_key,
|
||||
provider_thread_id,
|
||||
runtime_mode,
|
||||
status,
|
||||
last_seen_at,
|
||||
resume_cursor_json,
|
||||
runtime_payload_json
|
||||
)
|
||||
VALUES (
|
||||
${runtime.providerSessionId},
|
||||
${runtime.threadId},
|
||||
${runtime.providerName},
|
||||
${runtime.adapterKey},
|
||||
${runtime.providerThreadId},
|
||||
${runtime.runtimeMode},
|
||||
${runtime.status},
|
||||
${runtime.lastSeenAt},
|
||||
${runtime.resumeCursor},
|
||||
${runtime.runtimePayload}
|
||||
)
|
||||
ON CONFLICT (provider_session_id)
|
||||
ON CONFLICT (thread_id)
|
||||
DO UPDATE SET
|
||||
thread_id = excluded.thread_id,
|
||||
provider_name = excluded.provider_name,
|
||||
adapter_key = excluded.adapter_key,
|
||||
provider_thread_id = excluded.provider_thread_id,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
status = excluded.status,
|
||||
last_seen_at = excluded.last_seen_at,
|
||||
resume_cursor_json = excluded.resume_cursor_json,
|
||||
@@ -78,23 +75,22 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
`,
|
||||
});
|
||||
|
||||
const getRuntimeRowBySessionId = SqlSchema.findOneOption({
|
||||
const getRuntimeRowByThreadId = SqlSchema.findOneOption({
|
||||
Request: GetRuntimeRequestSchema,
|
||||
Result: ProviderSessionRuntimeDbRowSchema,
|
||||
execute: ({ providerSessionId }) =>
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
provider_session_id AS "providerSessionId",
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
adapter_key AS "adapterKey",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
runtime_mode AS "runtimeMode",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
WHERE provider_session_id = ${providerSessionId}
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -104,26 +100,25 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
provider_session_id AS "providerSessionId",
|
||||
thread_id AS "threadId",
|
||||
provider_name AS "providerName",
|
||||
adapter_key AS "adapterKey",
|
||||
provider_thread_id AS "providerThreadId",
|
||||
runtime_mode AS "runtimeMode",
|
||||
status,
|
||||
last_seen_at AS "lastSeenAt",
|
||||
resume_cursor_json AS "resumeCursor",
|
||||
runtime_payload_json AS "runtimePayload"
|
||||
FROM provider_session_runtime
|
||||
ORDER BY last_seen_at ASC, provider_session_id ASC
|
||||
ORDER BY last_seen_at ASC, thread_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteRuntimeBySessionId = SqlSchema.void({
|
||||
const deleteRuntimeByThreadId = SqlSchema.void({
|
||||
Request: DeleteRuntimeRequestSchema,
|
||||
execute: ({ providerSessionId }) =>
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
DELETE FROM provider_session_runtime
|
||||
WHERE provider_session_id = ${providerSessionId}
|
||||
WHERE thread_id = ${threadId}
|
||||
`,
|
||||
});
|
||||
|
||||
@@ -137,12 +132,12 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const getBySessionId: ProviderSessionRuntimeRepositoryShape["getBySessionId"] = (input) =>
|
||||
getRuntimeRowBySessionId(input).pipe(
|
||||
const getByThreadId: ProviderSessionRuntimeRepositoryShape["getByThreadId"] = (input) =>
|
||||
getRuntimeRowByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getBySessionId:query",
|
||||
"ProviderSessionRuntimeRepository.getBySessionId:decodeRow",
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:query",
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:decodeRow",
|
||||
),
|
||||
),
|
||||
Effect.flatMap((runtimeRowOption) =>
|
||||
@@ -152,7 +147,7 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
decodeRuntime(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceDecodeError(
|
||||
"ProviderSessionRuntimeRepository.getBySessionId:rowToRuntime",
|
||||
"ProviderSessionRuntimeRepository.getByThreadId:rowToRuntime",
|
||||
),
|
||||
),
|
||||
Effect.map((runtime) => Option.some(runtime)),
|
||||
@@ -183,18 +178,18 @@ const makeProviderSessionRuntimeRepository = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const deleteBySessionId: ProviderSessionRuntimeRepositoryShape["deleteBySessionId"] = (input) =>
|
||||
deleteRuntimeBySessionId(input).pipe(
|
||||
const deleteByThreadId: ProviderSessionRuntimeRepositoryShape["deleteByThreadId"] = (input) =>
|
||||
deleteRuntimeByThreadId(input).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteBySessionId:query"),
|
||||
toPersistenceSqlError("ProviderSessionRuntimeRepository.deleteByThreadId:query"),
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
upsert,
|
||||
getBySessionId,
|
||||
getByThreadId,
|
||||
list,
|
||||
deleteBySessionId,
|
||||
deleteByThreadId,
|
||||
} satisfies ProviderSessionRuntimeRepositoryShape;
|
||||
});
|
||||
|
||||
|
||||
@@ -1,225 +0,0 @@
|
||||
import { ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
|
||||
import {
|
||||
ProviderSessionRepositoryPersistenceError,
|
||||
ProviderSessionRepositoryValidationError,
|
||||
} from "../Errors.ts";
|
||||
import {
|
||||
ProviderSessionRepository,
|
||||
type ProviderSessionEntry,
|
||||
type ProviderSessionRepositoryShape,
|
||||
} from "../Services/ProviderSessions.ts";
|
||||
|
||||
const ProviderKind = Schema.Literals(["codex", "claudeCode"]);
|
||||
|
||||
const ProviderSessionRowSchema = Schema.Struct({
|
||||
sessionId: ProviderSessionId,
|
||||
provider: ProviderKind,
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
createdAt: Schema.String,
|
||||
updatedAt: Schema.String,
|
||||
});
|
||||
|
||||
const SessionIdRequestSchema = Schema.Struct({
|
||||
sessionId: ProviderSessionId,
|
||||
});
|
||||
|
||||
const UpsertSessionRequestSchema = Schema.Struct({
|
||||
sessionId: ProviderSessionId,
|
||||
provider: ProviderKind,
|
||||
threadId: Schema.NullOr(ThreadId),
|
||||
});
|
||||
|
||||
function errorMessage(cause: unknown, fallback: string): string {
|
||||
if (cause instanceof Error && cause.message.length > 0) {
|
||||
return cause.message;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function toValidationError(
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ProviderSessionRepositoryValidationError {
|
||||
return new ProviderSessionRepositoryValidationError({
|
||||
operation,
|
||||
issue: errorMessage(cause, "Invalid provider session repository input."),
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function decodeInput<S extends Schema.Top>(schema: S, input: unknown, operation: string) {
|
||||
return Schema.decodeUnknownEffect(schema)(input).pipe(
|
||||
Effect.mapError((cause) => toValidationError(operation, cause)),
|
||||
);
|
||||
}
|
||||
|
||||
function toPersistenceError(
|
||||
operation: string,
|
||||
cause: unknown,
|
||||
): ProviderSessionRepositoryPersistenceError {
|
||||
return new ProviderSessionRepositoryPersistenceError({
|
||||
operation,
|
||||
detail: `Failed to execute ${operation}.`,
|
||||
cause,
|
||||
});
|
||||
}
|
||||
|
||||
function toEntry(row: Schema.Schema.Type<typeof ProviderSessionRowSchema>): ProviderSessionEntry {
|
||||
return {
|
||||
sessionId: row.sessionId,
|
||||
provider: row.provider,
|
||||
...(row.threadId !== null ? { threadId: row.threadId } : {}),
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
const makeProviderSessionRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertSessionRow = SqlSchema.findOne({
|
||||
Request: UpsertSessionRequestSchema,
|
||||
Result: ProviderSessionRowSchema,
|
||||
execute: (request) =>
|
||||
sql`
|
||||
INSERT INTO provider_sessions (
|
||||
session_id,
|
||||
provider,
|
||||
thread_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
${request.sessionId},
|
||||
${request.provider},
|
||||
${request.threadId},
|
||||
CURRENT_TIMESTAMP,
|
||||
CURRENT_TIMESTAMP
|
||||
)
|
||||
ON CONFLICT (session_id)
|
||||
DO UPDATE SET
|
||||
provider = excluded.provider,
|
||||
thread_id = excluded.thread_id,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
RETURNING
|
||||
session_id AS "sessionId",
|
||||
provider,
|
||||
thread_id AS "threadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
`,
|
||||
});
|
||||
|
||||
const findSessionRow = SqlSchema.findOneOption({
|
||||
Request: SessionIdRequestSchema,
|
||||
Result: ProviderSessionRowSchema,
|
||||
execute: ({ sessionId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
session_id AS "sessionId",
|
||||
provider,
|
||||
thread_id AS "threadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM provider_sessions
|
||||
WHERE session_id = ${sessionId}
|
||||
`,
|
||||
});
|
||||
|
||||
const listSessionRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProviderSessionRowSchema,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
session_id AS "sessionId",
|
||||
provider,
|
||||
thread_id AS "threadId",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt"
|
||||
FROM provider_sessions
|
||||
ORDER BY created_at ASC, session_id ASC
|
||||
`,
|
||||
});
|
||||
|
||||
const deleteSessionRow = SqlSchema.void({
|
||||
Request: SessionIdRequestSchema,
|
||||
execute: ({ sessionId }) => sql`DELETE FROM provider_sessions WHERE session_id = ${sessionId}`,
|
||||
});
|
||||
|
||||
const upsertSession: ProviderSessionRepositoryShape["upsertSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInput(
|
||||
UpsertSessionRequestSchema,
|
||||
{
|
||||
sessionId: input.sessionId,
|
||||
provider: input.provider,
|
||||
threadId: input.threadId ?? null,
|
||||
},
|
||||
"ProviderSessionRepository.upsertSession",
|
||||
);
|
||||
|
||||
yield* upsertSessionRow(parsed).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.upsertSession:query", cause),
|
||||
),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
|
||||
const getSession: ProviderSessionRepositoryShape["getSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInput(
|
||||
SessionIdRequestSchema,
|
||||
{ sessionId: input.sessionId },
|
||||
"ProviderSessionRepository.getSession",
|
||||
);
|
||||
|
||||
const row = yield* findSessionRow(parsed).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.getSession:query", cause),
|
||||
),
|
||||
);
|
||||
|
||||
return Option.map(row, toEntry);
|
||||
});
|
||||
|
||||
const listSessions: ProviderSessionRepositoryShape["listSessions"] = () =>
|
||||
listSessionRows(undefined).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.listSessions:query", cause),
|
||||
),
|
||||
Effect.map((rows) => rows.map(toEntry)),
|
||||
);
|
||||
|
||||
const deleteSession: ProviderSessionRepositoryShape["deleteSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeInput(
|
||||
SessionIdRequestSchema,
|
||||
{ sessionId: input.sessionId },
|
||||
"ProviderSessionRepository.deleteSession",
|
||||
);
|
||||
|
||||
yield* deleteSessionRow(parsed).pipe(
|
||||
Effect.mapError((cause) =>
|
||||
toPersistenceError("ProviderSessionRepository.deleteSession:query", cause),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
upsertSession,
|
||||
getSession,
|
||||
listSessions,
|
||||
deleteSession,
|
||||
} satisfies ProviderSessionRepositoryShape;
|
||||
});
|
||||
|
||||
export const ProviderSessionRepositoryLive = Layer.effect(
|
||||
ProviderSessionRepository,
|
||||
makeProviderSessionRepository,
|
||||
);
|
||||
@@ -19,6 +19,13 @@ import Migration0004 from "./Migrations/004_ProviderSessionRuntime.ts";
|
||||
import Migration0005 from "./Migrations/005_Projections.ts";
|
||||
import Migration0006 from "./Migrations/006_ProjectionThreadSessionRuntimeModeColumns.ts";
|
||||
import Migration0007 from "./Migrations/007_ProjectionThreadMessageAttachments.ts";
|
||||
import Migration0008 from "./Migrations/008_ProjectionThreadActivitySequence.ts";
|
||||
import Migration0009 from "./Migrations/009_ProviderSessionRuntimeMode.ts";
|
||||
import Migration0010 from "./Migrations/010_ProjectionThreadsRuntimeMode.ts";
|
||||
import Migration0011 from "./Migrations/011_OrchestrationThreadCreatedRuntimeMode.ts";
|
||||
import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts";
|
||||
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
|
||||
import { Effect } from "effect";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -38,6 +45,12 @@ const loader = Migrator.fromRecord({
|
||||
"5_Projections": Migration0005,
|
||||
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
|
||||
"7_ProjectionThreadMessageAttachments": Migration0007,
|
||||
"8_ProjectionThreadActivitySequence": Migration0008,
|
||||
"9_ProviderSessionRuntimeMode": Migration0009,
|
||||
"10_ProjectionThreadsRuntimeMode": Migration0010,
|
||||
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
|
||||
"12_ProjectionThreadsInteractionMode": Migration0012,
|
||||
"13_ProjectionThreadProposedPlans": Migration0013,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -56,7 +69,11 @@ const run = Migrator.make({});
|
||||
*
|
||||
* @returns Effect containing array of executed migrations
|
||||
*/
|
||||
export const runMigrations = run({ loader });
|
||||
export const runMigrations = Effect.gen(function* () {
|
||||
yield* Effect.log("Running migrations...");
|
||||
yield* run({ loader });
|
||||
yield* Effect.log("Migrations ran successfully");
|
||||
});
|
||||
|
||||
/**
|
||||
* Layer that runs migrations when the layer is built.
|
||||
|
||||
@@ -6,11 +6,10 @@ export default Effect.gen(function* () {
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS provider_session_runtime (
|
||||
provider_session_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
thread_id TEXT PRIMARY KEY,
|
||||
provider_name TEXT NOT NULL,
|
||||
adapter_key TEXT NOT NULL,
|
||||
provider_thread_id TEXT,
|
||||
runtime_mode TEXT NOT NULL DEFAULT 'full-access',
|
||||
status TEXT NOT NULL,
|
||||
last_seen_at TEXT NOT NULL,
|
||||
resume_cursor_json TEXT,
|
||||
@@ -18,11 +17,6 @@ export default Effect.gen(function* () {
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_thread
|
||||
ON provider_session_runtime(thread_id)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_provider_session_runtime_status
|
||||
ON provider_session_runtime(status)
|
||||
|
||||
+4
-15
@@ -1,30 +1,19 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
const DEFAULT_APPROVAL_POLICY = "never";
|
||||
const DEFAULT_SANDBOX_MODE = "workspace-write";
|
||||
const DEFAULT_RUNTIME_MODE = "full-access";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_sessions
|
||||
ADD COLUMN approval_policy TEXT NOT NULL DEFAULT 'never'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_sessions
|
||||
ADD COLUMN sandbox_mode TEXT NOT NULL DEFAULT 'workspace-write'
|
||||
ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_thread_sessions
|
||||
SET approval_policy = ${DEFAULT_APPROVAL_POLICY}
|
||||
WHERE approval_policy IS NULL
|
||||
`;
|
||||
yield* sql`
|
||||
UPDATE projection_thread_sessions
|
||||
SET sandbox_mode = ${DEFAULT_SANDBOX_MODE}
|
||||
WHERE sandbox_mode IS NULL
|
||||
SET runtime_mode = ${DEFAULT_RUNTIME_MODE}
|
||||
WHERE runtime_mode IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_thread_activities
|
||||
ADD COLUMN sequence INTEGER
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_activities_thread_sequence
|
||||
ON projection_thread_activities(thread_id, sequence)
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
yield* SqlClient.SqlClient;
|
||||
});
|
||||
@@ -0,0 +1,17 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN runtime_mode TEXT NOT NULL DEFAULT 'full-access'
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET runtime_mode = 'full-access'
|
||||
WHERE runtime_mode IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
UPDATE orchestration_events
|
||||
SET payload_json = json_set(payload_json, '$.runtimeMode', 'full-access')
|
||||
WHERE event_type = 'thread.created'
|
||||
AND json_type(payload_json, '$.runtimeMode') IS NULL
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN interaction_mode TEXT NOT NULL DEFAULT 'default'
|
||||
`;
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
export default Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
yield* sql`
|
||||
CREATE TABLE IF NOT EXISTS projection_thread_proposed_plans (
|
||||
plan_id TEXT PRIMARY KEY,
|
||||
thread_id TEXT NOT NULL,
|
||||
turn_id TEXT,
|
||||
plan_markdown TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
)
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_projection_thread_proposed_plans_thread_created
|
||||
ON projection_thread_proposed_plans(thread_id, created_at)
|
||||
`;
|
||||
});
|
||||
@@ -9,6 +9,7 @@
|
||||
import {
|
||||
EventId,
|
||||
IsoDateTime,
|
||||
NonNegativeInt,
|
||||
OrchestrationThreadActivityTone,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -26,6 +27,7 @@ export const ProjectionThreadActivity = Schema.Struct({
|
||||
kind: Schema.String,
|
||||
summary: Schema.String,
|
||||
payload: Schema.Unknown,
|
||||
sequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
export type ProjectionThreadActivity = typeof ProjectionThreadActivity.Type;
|
||||
@@ -57,7 +59,8 @@ export interface ProjectionThreadActivityRepositoryShape {
|
||||
/**
|
||||
* List projected thread activity rows for a thread.
|
||||
*
|
||||
* Returned in ascending creation order.
|
||||
* Returned in ascending runtime sequence order (or creation order when
|
||||
* sequence is unavailable).
|
||||
*/
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadActivitiesInput,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import {
|
||||
IsoDateTime,
|
||||
OrchestrationProposedPlanId,
|
||||
ThreadId,
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProjectionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProjectionThreadProposedPlan = Schema.Struct({
|
||||
planId: OrchestrationProposedPlanId,
|
||||
threadId: ThreadId,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
planMarkdown: TrimmedNonEmptyString,
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
export type ProjectionThreadProposedPlan = typeof ProjectionThreadProposedPlan.Type;
|
||||
|
||||
export const ListProjectionThreadProposedPlansInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type ListProjectionThreadProposedPlansInput =
|
||||
typeof ListProjectionThreadProposedPlansInput.Type;
|
||||
|
||||
export const DeleteProjectionThreadProposedPlansInput = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
});
|
||||
export type DeleteProjectionThreadProposedPlansInput =
|
||||
typeof DeleteProjectionThreadProposedPlansInput.Type;
|
||||
|
||||
export interface ProjectionThreadProposedPlanRepositoryShape {
|
||||
readonly upsert: (
|
||||
proposedPlan: ProjectionThreadProposedPlan,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
readonly listByThreadId: (
|
||||
input: ListProjectionThreadProposedPlansInput,
|
||||
) => Effect.Effect<ReadonlyArray<ProjectionThreadProposedPlan>, ProjectionRepositoryError>;
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProjectionThreadProposedPlansInput,
|
||||
) => Effect.Effect<void, ProjectionRepositoryError>;
|
||||
}
|
||||
|
||||
export class ProjectionThreadProposedPlanRepository extends ServiceMap.Service<
|
||||
ProjectionThreadProposedPlanRepository,
|
||||
ProjectionThreadProposedPlanRepositoryShape
|
||||
>()(
|
||||
"t3/persistence/Services/ProjectionThreadProposedPlans/ProjectionThreadProposedPlanRepository",
|
||||
) {}
|
||||
@@ -7,12 +7,9 @@
|
||||
* @module ProjectionThreadSessionRepository
|
||||
*/
|
||||
import {
|
||||
RuntimeMode,
|
||||
IsoDateTime,
|
||||
OrchestrationSessionStatus,
|
||||
ProviderApprovalPolicy,
|
||||
ProviderSandboxMode,
|
||||
ProviderSessionId,
|
||||
ProviderThreadId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -25,10 +22,7 @@ export const ProjectionThreadSession = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
status: OrchestrationSessionStatus,
|
||||
providerName: Schema.NullOr(Schema.String),
|
||||
providerSessionId: Schema.NullOr(ProviderSessionId),
|
||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||
approvalPolicy: ProviderApprovalPolicy,
|
||||
sandboxMode: ProviderSandboxMode,
|
||||
runtimeMode: RuntimeMode,
|
||||
activeTurnId: Schema.NullOr(TurnId),
|
||||
lastError: Schema.NullOr(Schema.String),
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -6,7 +6,14 @@
|
||||
*
|
||||
* @module ProjectionThreadRepository
|
||||
*/
|
||||
import { IsoDateTime, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
|
||||
import {
|
||||
IsoDateTime,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
@@ -17,6 +24,8 @@ export const ProjectionThread = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
worktreePath: Schema.NullOr(Schema.String),
|
||||
latestTurnId: Schema.NullOr(TurnId),
|
||||
|
||||
@@ -7,9 +7,8 @@
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ProviderSessionId,
|
||||
ProviderSessionRuntimeStatus,
|
||||
ProviderThreadId,
|
||||
RuntimeMode,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Option, Schema, ServiceMap } from "effect";
|
||||
@@ -18,11 +17,10 @@ import type { Effect } from "effect";
|
||||
import type { ProviderSessionRuntimeRepositoryError } from "../Errors.ts";
|
||||
|
||||
export const ProviderSessionRuntime = Schema.Struct({
|
||||
providerSessionId: ProviderSessionId,
|
||||
threadId: ThreadId,
|
||||
providerName: Schema.String,
|
||||
adapterKey: Schema.String,
|
||||
providerThreadId: Schema.NullOr(ProviderThreadId),
|
||||
runtimeMode: RuntimeMode,
|
||||
status: ProviderSessionRuntimeStatus,
|
||||
lastSeenAt: IsoDateTime,
|
||||
resumeCursor: Schema.NullOr(Schema.Unknown),
|
||||
@@ -30,14 +28,10 @@ export const ProviderSessionRuntime = Schema.Struct({
|
||||
});
|
||||
export type ProviderSessionRuntime = typeof ProviderSessionRuntime.Type;
|
||||
|
||||
export const GetProviderSessionRuntimeInput = Schema.Struct({
|
||||
providerSessionId: ProviderSessionId,
|
||||
});
|
||||
export const GetProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export type GetProviderSessionRuntimeInput = typeof GetProviderSessionRuntimeInput.Type;
|
||||
|
||||
export const DeleteProviderSessionRuntimeInput = Schema.Struct({
|
||||
providerSessionId: ProviderSessionId,
|
||||
});
|
||||
export const DeleteProviderSessionRuntimeInput = Schema.Struct({ threadId: ThreadId });
|
||||
export type DeleteProviderSessionRuntimeInput = typeof DeleteProviderSessionRuntimeInput.Type;
|
||||
|
||||
/**
|
||||
@@ -47,16 +41,16 @@ export interface ProviderSessionRuntimeRepositoryShape {
|
||||
/**
|
||||
* Insert or replace a provider runtime row.
|
||||
*
|
||||
* Upserts by `providerSessionId`, including JSON payload/cursor fields.
|
||||
* Upserts by canonical `threadId`, including JSON payload/cursor fields.
|
||||
*/
|
||||
readonly upsert: (
|
||||
runtime: ProviderSessionRuntime,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read provider runtime state by provider session id.
|
||||
* Read provider runtime state by canonical thread id.
|
||||
*/
|
||||
readonly getBySessionId: (
|
||||
readonly getByThreadId: (
|
||||
input: GetProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<Option.Option<ProviderSessionRuntime>, ProviderSessionRuntimeRepositoryError>;
|
||||
|
||||
@@ -71,9 +65,9 @@ export interface ProviderSessionRuntimeRepositoryShape {
|
||||
>;
|
||||
|
||||
/**
|
||||
* Delete provider runtime state by provider session id.
|
||||
* Delete provider runtime state by canonical thread id.
|
||||
*/
|
||||
readonly deleteBySessionId: (
|
||||
readonly deleteByThreadId: (
|
||||
input: DeleteProviderSessionRuntimeInput,
|
||||
) => Effect.Effect<void, ProviderSessionRuntimeRepositoryError>;
|
||||
}
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
/**
|
||||
* ProviderSessionRepository - Repository interface for provider session lookup.
|
||||
*
|
||||
* Owns persistence operations that map internal sessions to provider kinds and
|
||||
* optional thread ownership.
|
||||
*
|
||||
* @module ProviderSessionRepository
|
||||
*/
|
||||
import type { ProviderKind, ProviderSessionId, ThreadId } from "@t3tools/contracts";
|
||||
import { Option, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProviderSessionRepositoryError } from "../Errors.ts";
|
||||
|
||||
export interface ProviderSessionEntry {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly createdAt: string;
|
||||
readonly updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UpsertProviderSessionInput {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
readonly provider: ProviderKind;
|
||||
readonly threadId?: ThreadId;
|
||||
}
|
||||
|
||||
export interface DeleteProviderSessionInput {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
}
|
||||
|
||||
export interface GetProviderSessionInput {
|
||||
readonly sessionId: ProviderSessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionRepositoryShape - Service API for provider-session records.
|
||||
*/
|
||||
export interface ProviderSessionRepositoryShape {
|
||||
/**
|
||||
* Insert or replace a provider-session row.
|
||||
*
|
||||
* Upserts by `sessionId`.
|
||||
*/
|
||||
readonly upsertSession: (
|
||||
input: UpsertProviderSessionInput,
|
||||
) => Effect.Effect<void, ProviderSessionRepositoryError>;
|
||||
|
||||
/**
|
||||
* Read a provider-session row by session id.
|
||||
*/
|
||||
readonly getSession: (
|
||||
input: GetProviderSessionInput,
|
||||
) => Effect.Effect<Option.Option<ProviderSessionEntry>, ProviderSessionRepositoryError>;
|
||||
|
||||
/**
|
||||
* List all provider-session rows.
|
||||
*
|
||||
* Returned in deterministic creation order.
|
||||
*/
|
||||
readonly listSessions: () => Effect.Effect<
|
||||
ReadonlyArray<ProviderSessionEntry>,
|
||||
ProviderSessionRepositoryError
|
||||
>;
|
||||
|
||||
/**
|
||||
* Delete a provider-session row by session id.
|
||||
*/
|
||||
readonly deleteSession: (
|
||||
input: DeleteProviderSessionInput,
|
||||
) => Effect.Effect<void, ProviderSessionRepositoryError>;
|
||||
}
|
||||
|
||||
/**
|
||||
* ProviderSessionRepository - Service tag for provider-session persistence.
|
||||
*/
|
||||
export class ProviderSessionRepository extends ServiceMap.Service<
|
||||
ProviderSessionRepository,
|
||||
ProviderSessionRepositoryShape
|
||||
>()("t3/persistence/Services/ProviderSessions/ProviderSessionRepository") {}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
|
||||
|
||||
export interface ProcessRunOptions {
|
||||
cwd?: string | undefined;
|
||||
@@ -37,11 +37,21 @@ function normalizeSpawnError(command: string, args: readonly string[], error: un
|
||||
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
|
||||
}
|
||||
|
||||
function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
|
||||
if (process.platform !== "win32") return false;
|
||||
if (code === 9009) return true;
|
||||
return /is not recognized as an internal or external command/i.test(stderr);
|
||||
}
|
||||
|
||||
function normalizeExitError(
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
result: ProcessRunResult,
|
||||
): Error {
|
||||
if (isWindowsCommandNotFound(result.code, result.stderr)) {
|
||||
return new Error(`Command not found: ${command}`);
|
||||
}
|
||||
|
||||
const reason = result.timedOut
|
||||
? "timed out"
|
||||
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
|
||||
@@ -70,6 +80,23 @@ function normalizeBufferError(
|
||||
|
||||
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 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 killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
|
||||
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(signal);
|
||||
}
|
||||
|
||||
function appendChunkWithinLimit(
|
||||
target: string,
|
||||
currentBytes: number,
|
||||
@@ -112,6 +139,7 @@ export async function runProcess(
|
||||
cwd: options.cwd,
|
||||
env: options.env,
|
||||
stdio: "pipe",
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
|
||||
let stdout = "";
|
||||
@@ -126,9 +154,9 @@ export async function runProcess(
|
||||
|
||||
const timeoutTimer = setTimeout(() => {
|
||||
timedOut = true;
|
||||
child.kill("SIGTERM");
|
||||
killChild(child, "SIGTERM");
|
||||
forceKillTimer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
killChild(child, "SIGKILL");
|
||||
}, 1_000);
|
||||
}, timeoutMs);
|
||||
|
||||
@@ -143,7 +171,7 @@ export async function runProcess(
|
||||
};
|
||||
|
||||
const fail = (error: Error): void => {
|
||||
child.kill("SIGTERM");
|
||||
killChild(child, "SIGTERM");
|
||||
finalize(() => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user