Compare commits

..
Author SHA1 Message Date
Cursor Agent 9bd61ebce7 fix: merge base snapshot models during enrichment to prevent catalog shrinkage
When enrichCursorSnapshot runs background capability discovery via
list_available_models, it may return fewer models than the initial
snapshot (which could have been built from session config fallback).
Previously, enrichment replaced all models with only the discovered set,
dropping models that were in the original snapshot but not in the
list_available_models response.

Now we merge: discovered models take precedence (with richer capability
info), but models from the base snapshot that aren't in the discovered
set are preserved.
2026-06-03 16:17:36 +00:00
Julius Marminge 97c5d15fab Merge remote-tracking branch 'origin/main' into t3code/cursor-model-probe
# Conflicts:
#	apps/server/src/provider/Layers/CursorProvider.ts
#	apps/server/src/provider/acp/CursorAcpExtension.ts
2026-06-03 09:12:28 -07:00
Julius Marmingeandcodex d371a1dc8a Merge origin/main into cursor model probe
Resolve Cursor provider conflicts by keeping main's environment-aware provider runtime plumbing while preserving list_available_models discovery.

Co-authored-by: codex <[email protected]>
2026-04-30 17:39:35 -07:00
Julius Marminge f853a7f2d2 Decode Cursor model list responses with schema
- Add a schema for `cursor/list_available_models` responses
- Use decoded model data when building Cursor provider capabilities
- Cover per-model config options in Cursor ACP tests
2026-04-30 17:17:04 -07:00
Julius Marminge c517cfab3d Probe Cursor available models for capabilities
- Add `cursor/list_available_models` support to the ACP mock agent
- Use the new model list response for Cursor model discovery and capability enrichment
- Update tests to cover the extension path and reduced probe teardown
2026-04-30 17:11:54 -07:00
325 changed files with 5174 additions and 18682 deletions

No files matched your search

+1
View File
@@ -0,0 +1 @@
.repos/**
+75 -87
View File
@@ -7,104 +7,80 @@ on:
- main
jobs:
check:
name: Check
quality:
name: Format, Lint, Typecheck, Test, Browser Test, Build
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- name: Check
run: vp check
- name: Typecheck
run: vpr typecheck
- name: Build desktop pipeline
run: vp run build:desktop
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
test:
name: Test
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Cache Bun and Turbo
uses: actions/cache@v5
with:
node-version-file: package.json
cache: true
run-install: true
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
run: vp run test
test_browser:
name: Test Browser
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
path: |
~/.bun/install/cache
.turbo
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
- name: Cache Playwright browsers
uses: actions/cache@v5
with:
path: ~/.cache/ms-playwright
key: ${{ runner.os }}-playwright-${{ hashFiles('pnpm-lock.yaml') }}
key: ${{ runner.os }}-playwright-${{ hashFiles('bun.lock') }}
restore-keys: |
${{ runner.os }}-playwright-
- name: Install browser test runtime
run: vp run --filter @t3tools/web test:browser:install
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Browser test / Chat view
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatView.browser.tsx
- name: Browser test / Chat markdown
working-directory: apps/web
run: vp test run --mode browser --browser=chromium src/components/ChatMarkdown.browser.tsx
- name: Browser test / Components
working-directory: apps/web
- name: Ensure Electron runtime is installed
run: |
vp test run --mode browser --browser=chromium \
src/components/GitActionsControl.browser.tsx \
src/components/KeybindingsToast.browser.tsx \
src/components/ThreadTerminalDrawer.browser.tsx \
src/components/chat/MessagesTimeline.browser.tsx \
src/components/chat/ProviderModelPicker.browser.tsx \
src/components/chat/CompactComposerControlsMenu.browser.tsx \
src/components/settings/SettingsPanels.browser.tsx
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- name: Format
run: bun run fmt:check
- name: Lint
run: bun run lint
- name: Typecheck
run: bun run typecheck
- 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
- name: Verify preload bundle output
run: |
test -f apps/desktop/dist-electron/preload.cjs
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.cjs
mobile_native_static_analysis:
name: Mobile Native Static Analysis
@@ -114,18 +90,24 @@ jobs:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Install mobile native static analysis tools
run: brew bundle install --file apps/mobile/Brewfile
- name: Lint mobile native sources
run: vp run lint:mobile
run: node scripts/mobile-native-static-check.ts
release_smoke:
name: Release Smoke
@@ -135,12 +117,18 @@ jobs:
- name: Checkout
uses: actions/checkout@v6
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Exercise release-only workflow steps
run: node scripts/release-smoke.ts
-78
View File
@@ -1,78 +0,0 @@
name: Mobile EAS Preview
on:
pull_request:
jobs:
preview:
name: EAS Preview
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
pull-requests: write
env:
APP_VARIANT: preview
NODE_OPTIONS: --max-old-space-size=8192
MOBILE_VERSION_POLICY: fingerprint
steps:
- id: expo-token
name: Check for EXPO_TOKEN
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
if [ -n "$EXPO_TOKEN" ]; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
echo "EXPO_TOKEN is not available; skipping EAS preview."
fi
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: true
- name: Expose pnpm
if: steps.expo-token.outputs.present == 'true'
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Setup EAS
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action@v8
with:
eas-version: latest
token: ${{ secrets.EXPO_TOKEN }}
packager: pnpm
- name: Pull preview environment variables
if: steps.expo-token.outputs.present == 'true'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull preview --non-interactive
- name: Deploy with fingerprint check
if: steps.expo-token.outputs.present == 'true'
uses: expo/expo-github-action/continuous-deploy-fingerprint@main
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
with:
profile: preview:dev
branch: pr-${{ github.event.pull_request.number }}
platform: all
environment: preview
working-directory: apps/mobile
github-token: ${{ secrets.GITHUB_TOKEN }}
+92 -57
View File
@@ -85,15 +85,26 @@ jobs:
with:
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Ensure Electron runtime is installed
run: vp run --filter @t3tools/desktop ensure:electron
run: |
if ! node -e "require('./apps/desktop/node_modules/electron')" >/dev/null 2>&1; then
rm -rf apps/desktop/node_modules/electron/dist apps/desktop/node_modules/electron/path.txt
bun apps/desktop/node_modules/electron/install.js
fi
node -e "require('./apps/desktop/node_modules/electron')"
- id: release_meta
name: Resolve release version
@@ -149,14 +160,14 @@ jobs:
fi
fi
- name: Check
run: vp check
- name: Lint
run: bun run lint
- name: Typecheck
run: vp run typecheck
run: bun run typecheck
- name: Test
run: vp run test
run: bun run test
- id: previous_tag
name: Resolve previous release tag
@@ -208,12 +219,18 @@ jobs:
ref: ${{ needs.preflight.outputs.ref }}
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: true
- name: Install dependencies
run: bun install --frozen-lockfile
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
@@ -373,7 +390,7 @@ jobs:
echo "Signing disabled for ${{ matrix.platform }}."
fi
vp run dist:desktop:artifact "${args[@]}"
bun run dist:desktop:artifact -- "${args[@]}"
- name: Collect release assets
shell: bash
@@ -435,25 +452,28 @@ jobs:
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=t3...
- --filter=@t3tools/web...
- --filter=@t3tools/scripts...
registry-url: https://registry.npmjs.org
- name: Install dependencies
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Build web package
run: vp run --filter @t3tools/web build
run: bun --filter=@t3tools/web run build
- name: Build CLI package
run: vp run --filter t3 build
run: bun --filter=t3 run build
- name: Publish CLI package
run: node apps/server/scripts/cli.ts publish --tag "${{ needs.preflight.outputs.cli_dist_tag }}" --app-version "${{ needs.preflight.outputs.version }}" --verbose
@@ -478,14 +498,18 @@ jobs:
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Download all desktop artifacts
uses: actions/download-artifact@v8
@@ -595,21 +619,24 @@ jobs:
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- name: Install release tooling dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts --filter=@t3tools/web
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Refresh release lockfile
run: vp install --lockfile-only --ignore-scripts
run: bun install --lockfile-only --ignore-scripts
- name: Deploy and alias channel
shell: bash
@@ -641,7 +668,7 @@ jobs:
echo "Deploying hosted web app for $channel_name channel."
deployment_url="$(
vp dlx [email protected] deploy \
bunx [email protected] deploy \
--prod \
--skip-domain \
--yes \
@@ -653,13 +680,13 @@ jobs:
)"
echo "Aliasing $deployment_url to $channel_domain."
vp dlx [email protected] alias set "$deployment_url" "$channel_domain" \
bunx [email protected] alias set "$deployment_url" "$channel_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
vp dlx [email protected] alias set "$deployment_url" "$router_domain" \
bunx [email protected] alias set "$deployment_url" "$router_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
fi
@@ -697,14 +724,18 @@ jobs:
echo "name=${APP_SLUG}[bot]" >> "$GITHUB_OUTPUT"
echo "email=${user_id}+${APP_SLUG}[bot]@users.noreply.github.com" >> "$GITHUB_OUTPUT"
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- id: update_versions
name: Update version strings
@@ -714,11 +745,11 @@ jobs:
- name: Format package.json files
if: steps.update_versions.outputs.changed == 'true'
run: vp fmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
run: bunx [email protected] 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: vp install --lockfile-only --ignore-scripts
run: bun install --lockfile-only --ignore-scripts
- name: Commit and push version bump
if: steps.update_versions.outputs.changed == 'true'
@@ -726,7 +757,7 @@ jobs:
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 pnpm-lock.yaml; then
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
@@ -734,7 +765,7 @@ jobs:
git config user.name "${{ steps.app_bot.outputs.name }}"
git config user.email "${{ steps.app_bot.outputs.email }}"
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json pnpm-lock.yaml
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
@@ -755,14 +786,18 @@ jobs:
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- name: Install dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts
- name: Announce prerelease on Discord
if: needs.preflight.outputs.is_prerelease == 'true'
+1
View File
@@ -1,2 +1,3 @@
[tools]
node = "24.13.1"
bun = "1.3.9"
+29
View File
@@ -0,0 +1,29 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".repos/**",
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/web/public/mockServiceWorker.js",
"apps/web/src/lib/vendor/qrcodegen.ts",
"apps/mobile/uniwind-types.d.ts",
"*.icon/**"
],
"sortPackageJson": {},
"overrides": [
{
"files": [".devcontainer/devcontainer.json"],
"options": {
"trailingComma": "none"
}
}
]
}
+30
View File
@@ -0,0 +1,30 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"dist",
"dist-electron",
".repos/**",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/mobile/android/**",
"apps/mobile/ios/**",
"apps/mobile/uniwind-types.d.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
"perf": "warn"
},
"rules": {
"unicorn/no-array-sort": "off",
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off",
"eslint/no-underscore-dangle": "off",
"t3code/no-inline-schema-compile": "warn"
}
}
-1
View File
@@ -1 +0,0 @@
vp staged
+3 -3
View File
@@ -2,9 +2,9 @@
## Task Completion Requirements
- `vp check` and `vp run typecheck` must pass before considering tasks completed.
- If changing native mobile code, `vp run lint:mobile` must also pass.
- Use `vp test` for the built-in Vite+ test command and `vp run test` when you specifically need the `test` package script.
- All of `bun fmt`, `bun lint`, and `bun typecheck` must pass before considering tasks completed.
- If changing native mobile code, `bun lint:mobile` must also pass.
- NEVER run `bun test`. Always use `bun run test` (runs Vitest).
## Project Snapshot
+1 -1
View File
@@ -55,7 +55,7 @@ Before local development, prepare the environment and install dependencies:
```bash
# Optional: only needed if you use mise for dev tool management.
mise install
vp install
bun install .
```
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+6 -5
View File
@@ -5,10 +5,13 @@
"type": "module",
"main": "dist-electron/main.cjs",
"scripts": {
"ensure:electron": "node scripts/ensure-electron-runtime.mjs",
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "tsdown --watch",
"dev:electron": "node scripts/dev-electron.mjs",
"build": "tsdown",
"start": "node scripts/start-electron.mjs",
"typecheck": "tsgo --noEmit",
"test": "vp test run --passWithNoTests",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
@@ -25,9 +28,7 @@
"devDependencies": {
"@effect/vitest": "catalog:",
"@types/node": "catalog:",
"cross-env": "^10.1.0",
"electron-builder": "26.8.1",
"vite-plus": "catalog:",
"tsdown": "catalog:",
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
+1 -4
View File
@@ -15,7 +15,6 @@ import {
import { createRequire } from "node:module";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { ensureElectronRuntime } from "./ensure-electron-runtime.mjs";
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
@@ -130,7 +129,7 @@ function readJson(path) {
}
function buildMacLauncher(electronBinaryPath) {
const sourceAppBundlePath = resolve(dirname(electronBinaryPath), "../..");
const sourceAppBundlePath = resolve(electronBinaryPath, "../../..");
const runtimeDir = join(desktopDir, ".electron-runtime");
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
@@ -164,8 +163,6 @@ function buildMacLauncher(electronBinaryPath) {
}
export function resolveElectronPath() {
ensureElectronRuntime();
const require = createRequire(import.meta.url);
const electronBinaryPath = require("electron");
@@ -1,176 +0,0 @@
import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { spawnSync } from "node:child_process";
const require = createRequire(import.meta.url);
function getPlatformPath() {
switch (process.platform) {
case "darwin":
return "Electron.app/Contents/MacOS/Electron";
case "freebsd":
case "openbsd":
case "linux":
return "electron";
case "win32":
return "electron.exe";
default:
throw new Error(`Electron builds are not available on platform: ${process.platform}`);
}
}
function ensureExecutable(filePath) {
if (process.platform !== "win32") {
chmodSync(filePath, 0o755);
}
}
function repairPathFile(electronDir, platformPath) {
const pathFile = join(electronDir, "path.txt");
const currentPath = existsSync(pathFile) ? readFileSync(pathFile, "utf8") : undefined;
if (currentPath !== platformPath) {
writeFileSync(pathFile, platformPath);
}
}
function getRequiredRuntimePaths(electronDir, platformPath) {
const paths = [join(electronDir, "dist", platformPath)];
if (process.platform === "darwin") {
paths.push(
join(electronDir, "dist", "Electron.app", "Contents", "Info.plist"),
join(
electronDir,
"dist",
"Electron.app",
"Contents",
"Frameworks",
"Electron Framework.framework",
"Electron Framework",
),
);
}
return paths;
}
function isMachO(filePath) {
if (process.platform !== "darwin") {
return true;
}
const result = spawnSync("file", ["-b", filePath], {
encoding: "utf8",
});
return result.status === 0 && result.stdout.includes("Mach-O");
}
function missingRuntimePaths(electronDir, platformPath) {
return getRequiredRuntimePaths(electronDir, platformPath).filter((runtimePath) => {
return !existsSync(runtimePath);
});
}
function invalidRuntimePaths(electronDir, platformPath) {
if (process.platform !== "darwin") {
return [];
}
return [
join(electronDir, "dist", platformPath),
join(
electronDir,
"dist",
"Electron.app",
"Contents",
"Frameworks",
"Electron Framework.framework",
"Electron Framework",
),
].filter((runtimePath) => existsSync(runtimePath) && !isMachO(runtimePath));
}
function runChecked(command, args) {
const result = spawnSync(command, args, {
encoding: "utf8",
stdio: "inherit",
});
if (result.status === 0) {
return;
}
throw new Error(
`${command} ${args.join(" ")} failed with exit code ${result.status ?? "unknown"}`,
);
}
function installElectronRuntime(electronDir, version) {
const tempDir = mkdtempSync(join(tmpdir(), "t3-electron-"));
const zipPath = join(tempDir, `electron-v${version}-${process.platform}-${process.arch}.zip`);
try {
runChecked("curl", [
"-fsSL",
`https://github.com/electron/electron/releases/download/v${version}/electron-v${version}-${process.platform}-${process.arch}.zip`,
"-o",
zipPath,
]);
if (process.platform === "darwin") {
runChecked("ditto", ["-x", "-k", zipPath, join(electronDir, "dist")]);
} else {
runChecked("python3", [
"-c",
"import os, sys, zipfile; os.makedirs(sys.argv[2], exist_ok=True); zipfile.ZipFile(sys.argv[1]).extractall(sys.argv[2])",
zipPath,
join(electronDir, "dist"),
]);
}
} finally {
rmSync(tempDir, { recursive: true, force: true });
}
}
export function ensureElectronRuntime() {
const electronPackageJsonPath = require.resolve("electron/package.json");
const electronPackageJson = JSON.parse(readFileSync(electronPackageJsonPath, "utf8"));
const electronDir = dirname(electronPackageJsonPath);
const platformPath = getPlatformPath();
const electronPath = join(electronDir, "dist", platformPath);
const missingBeforeInstall = missingRuntimePaths(electronDir, platformPath);
const invalidBeforeInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingBeforeInstall.length > 0 || invalidBeforeInstall.length > 0) {
if (existsSync(join(electronDir, "dist"))) {
rmSync(join(electronDir, "dist"), { recursive: true, force: true });
}
rmSync(join(electronDir, "path.txt"), { force: true });
installElectronRuntime(electronDir, electronPackageJson.version);
}
const missingAfterInstall = missingRuntimePaths(electronDir, platformPath);
const invalidAfterInstall = invalidRuntimePaths(electronDir, platformPath);
if (missingAfterInstall.length > 0 || invalidAfterInstall.length > 0) {
throw new Error(
`Electron runtime is incomplete after install.\nMissing:\n${missingAfterInstall
.map((runtimePath) => `- ${runtimePath}`)
.join("\n")}\nInvalid:\n${invalidAfterInstall
.map((runtimePath) => `- ${runtimePath}`)
.join("\n")}`,
);
}
ensureExecutable(electronPath);
repairPathFile(electronDir, platformPath);
return electronPath;
}
if (import.meta.url === `file://${process.argv[1]}`) {
const electronPath = ensureElectronRuntime();
process.stdout.write(`${electronPath}\n`);
}
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
const {
appendSwitchMock,
@@ -2,7 +2,7 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type { BrowserWindow } from "electron";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
import * as ElectronDialog from "./ElectronDialog.ts";
@@ -2,7 +2,7 @@ import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
const { buildFromTemplateMock, createFromNamedImageMock, setApplicationMenuMock } = vi.hoisted(
() => ({
@@ -3,7 +3,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
const { registerFileProtocolMock, registerSchemesAsPrivilegedMock, unregisterProtocolMock } =
vi.hoisted(() => ({
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
const { openExternalMock, writeTextMock } = vi.hoisted(() => ({
openExternalMock: vi.fn(),
@@ -1,6 +1,6 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
const { onMock, removeListenerMock, themeState } = vi.hoisted(() => ({
onMock: vi.fn(),
@@ -1,7 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
const { autoUpdaterMock } = vi.hoisted(() => ({
autoUpdaterMock: {
@@ -1,7 +1,7 @@
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
import { beforeEach, vi } from "vitest";
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
appFocusMock: vi.fn(),
+5 -55
View File
@@ -3,11 +3,8 @@ import {
fetchRemoteEnvironmentDescriptor,
fetchRemoteSessionState,
issueRemoteWebSocketTicket,
RemoteEnvironmentAuthUndeclaredStatusError,
type RemoteEnvironmentAuthError,
} from "@t3tools/client-runtime";
import {
EnvironmentAuthInvalidError,
DesktopDiscoveredSshHostSchema,
DesktopSshBearerBootstrapInputSchema,
DesktopSshBearerRequestInputSchema,
@@ -18,15 +15,10 @@ import {
DesktopSshPasswordPromptCancelledType,
DesktopSshPasswordPromptResolutionInputSchema,
ExecutionEnvironmentDescriptor,
EnvironmentInternalError,
EnvironmentOperationForbiddenError,
EnvironmentRequestInvalidError,
EnvironmentScopeRequiredError,
AuthAccessTokenResult,
AuthSessionState,
AuthWebSocketTicketResult,
} from "@t3tools/contracts";
import { SshHttpBridgeError } from "@t3tools/ssh/errors";
import { resolveLoopbackSshHttpBaseUrl } from "@t3tools/ssh/tunnel";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
@@ -43,68 +35,26 @@ type DesktopSshEnvironmentRequestOperation =
| "fetch-session-state"
| "issue-websocket-ticket";
type DesktopSshEnvironmentRequestCause = RemoteEnvironmentAuthError | SshHttpBridgeError;
const isEnvironmentAuthInvalidError = Schema.is(EnvironmentAuthInvalidError);
const isEnvironmentInternalError = Schema.is(EnvironmentInternalError);
const isEnvironmentOperationForbiddenError = Schema.is(EnvironmentOperationForbiddenError);
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
const isEnvironmentScopeRequiredError = Schema.is(EnvironmentScopeRequiredError);
function readSshHttpStatus(cause: DesktopSshEnvironmentRequestCause): number | null {
if (
cause instanceof RemoteEnvironmentAuthUndeclaredStatusError ||
cause instanceof SshHttpBridgeError
) {
return cause.status ?? null;
}
if (isEnvironmentRequestInvalidError(cause)) {
return 400;
}
if (isEnvironmentAuthInvalidError(cause)) {
return 401;
}
if (isEnvironmentScopeRequiredError(cause)) {
return 403;
}
if (isEnvironmentOperationForbiddenError(cause)) {
return 403;
}
if (isEnvironmentInternalError(cause)) {
return 500;
}
return null;
}
export class DesktopSshEnvironmentRequestError extends Data.TaggedError(
"DesktopSshEnvironmentRequestError",
)<{
readonly operation: DesktopSshEnvironmentRequestOperation;
readonly cause: DesktopSshEnvironmentRequestCause;
readonly sshHttpStatus: number | null;
readonly cause: unknown;
}> {
override get message() {
const prefix = this.sshHttpStatus === null ? "" : `[ssh_http:${this.sshHttpStatus}] `;
return `${prefix}SSH remote API request failed during ${this.operation}.`;
return `SSH remote API request failed during ${this.operation}.`;
}
}
const withLoopbackSshApi =
<A, R>(
<A, E, R>(
operation: DesktopSshEnvironmentRequestOperation,
use: (httpBaseUrl: string) => Effect.Effect<A, RemoteEnvironmentAuthError, R>,
use: (httpBaseUrl: string) => Effect.Effect<A, E, R>,
) =>
(httpBaseUrl: string): Effect.Effect<A, DesktopSshEnvironmentRequestError, R> =>
resolveLoopbackSshHttpBaseUrl(httpBaseUrl).pipe(
Effect.flatMap(use),
Effect.mapError(
(cause) =>
new DesktopSshEnvironmentRequestError({
operation,
cause,
sshHttpStatus: readSshHttpStatus(cause),
}),
),
Effect.mapError((cause) => new DesktopSshEnvironmentRequestError({ operation, cause })),
);
export const discoverSshHosts = makeIpcMethod({
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
createInitialDesktopUpdateState,
@@ -6,7 +6,7 @@ import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
import { vi } from "vitest";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
+1 -1
View File
@@ -5,5 +5,5 @@
"types": ["node", "electron"],
"lib": ["ESNext", "DOM", "esnext.disposable"]
},
"include": ["src", "vite.config.ts"]
"include": ["src", "tsdown.config.ts"]
}
+21
View File
@@ -0,0 +1,21 @@
import { defineConfig } from "tsdown";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
};
export default defineConfig([
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
entry: ["src/preload.ts"],
},
]);
+24
View File
@@ -0,0 +1,24 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist-electron/**"],
},
"dev": {
"dependsOn": ["t3#build"],
"persistent": true,
},
"start": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"persistent": true,
},
"smoke-test": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"outputs": [],
},
},
}
-50
View File
@@ -1,50 +0,0 @@
import { defineConfig } from "vite-plus";
const shouldLaunchElectronAfterPack = process.env.T3CODE_DESKTOP_DEV === "1";
export default defineConfig({
run: {
tasks: {
build: {
command: "vp pack",
dependsOn: ["t3#build"],
cache: false,
},
dev: {
command: "cross-env T3CODE_DESKTOP_DEV=1 vp pack --watch",
dependsOn: ["t3#build"],
cache: false,
},
"dev:bundle": {
command: "vp pack --watch",
cache: false,
},
"dev:electron": {
command: "node scripts/dev-electron.mjs",
dependsOn: ["t3#build"],
cache: false,
},
},
},
pack: [
{
format: "cjs",
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
entry: ["src/main.ts"],
clean: true,
deps: {
alwaysBundle: (id) => id.startsWith("@t3tools/"),
},
...(shouldLaunchElectronAfterPack ? { onSuccess: "node scripts/dev-electron.mjs" } : {}),
},
{
format: "cjs",
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".cjs" }),
entry: ["src/preload.ts"],
},
],
});
-1
View File
@@ -14,7 +14,6 @@
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
"@vercel/config": "^0.3.0",
"typescript": "catalog:"
}
}
-1
View File
@@ -1 +0,0 @@
/// <reference types="astro/client" />
+2 -2
View File
@@ -298,9 +298,9 @@ const mobileEndorsementRows = [
<div class="open-term-body">
<div><span class="prompt">$</span> gh repo fork pingdotgg/t3code --clone</div>
<div class="dim">✓ Cloned t3code into ./t3code</div>
<div><span class="prompt">$</span> cd t3code &amp;&amp; vp install</div>
<div><span class="prompt">$</span> cd t3code &amp;&amp; bun install</div>
<div class="dim">✓ 1 284 packages installed in 4.2s</div>
<div><span class="prompt">$</span> vp run dev</div>
<div><span class="prompt">$</span> bun dev</div>
<div class="dim">▲ T3 Code dev server → <span class="accent">http://localhost:4001</span></div>
<div class="cursor"><span class="prompt">$</span><span class="caret"></span></div>
</div>
-7
View File
@@ -1,7 +0,0 @@
import type { VercelConfig } from "@vercel/config/v1";
export const config: VercelConfig = {
installCommand: "npm install -g vite-plus && vp install --filter '@t3tools/marketing'",
buildCommand: "vp run --filter @t3tools/marketing build",
outputDirectory: "dist",
};
-24
View File
@@ -1,24 +0,0 @@
# Expo artifacts
.expo/
.eas/
# Build outputs
android/
ios/
dist/
web-build/
# Test files
**/*.test.ts
**/*.test.tsx
# Docs
*.md
# Local env
.env
.env.local
.env*.local
# TypeScript
*.tsbuildinfo
+10 -19
View File
@@ -21,25 +21,25 @@ Run commands from `apps/mobile`.
Start Metro for the dev client:
```bash
vp run dev:client
bun run dev:client
```
Build and run the local iOS dev client:
```bash
vp run ios:dev
bun run ios:dev
```
Build and run the local iOS preview app:
```bash
vp run ios:preview
bun run ios:preview
```
Force the review diff highlighter engine:
```bash
EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript vp run ios:dev
EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript bun run ios:dev
```
`javascript` is the default and recommended setting for the review diff screen. Set `EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=native` only when you explicitly want to test the native Shiki engine.
@@ -47,8 +47,8 @@ EXPO_PUBLIC_REVIEW_HIGHLIGHTER_ENGINE=javascript vp run ios:dev
Inspect the resolved Expo config for a variant:
```bash
vp run config:dev
vp run config:preview
bun run config:dev
bun run config:preview
```
Run static checks for mobile native code:
@@ -61,30 +61,21 @@ The native lint task runs SwiftLint for Swift plus ktlint and detekt for Kotlin.
## EAS Builds
CI uses Expo fingerprinting with the `preview:dev` profile to reuse an existing compatible build when possible, or start a new internal EAS build when native runtime inputs change. Production and default local builds continue to use the `appVersion` runtime policy.
Create a PR preview dev-client build manually:
```bash
vp run eas:ios:preview:dev
```
Create a cloud dev-client build:
```bash
vp run eas:ios:dev
bun run eas:ios:dev
```
Create a persistent preview build:
```bash
vp run eas:ios:preview
bun run eas:ios:preview
```
Android equivalents:
```bash
vp run eas:android:dev
vp run eas:android:preview:dev
vp run eas:android:preview
bun run eas:android:dev
bun run eas:android:preview
```
+1 -2
View File
@@ -53,11 +53,10 @@ const variant = VARIANT_CONFIG[APP_VARIANT];
const config: ExpoConfig = {
name: variant.appName,
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "0.1.0",
runtimeVersion: {
policy: process.env.MOBILE_VERSION_POLICY ?? "appVersion",
policy: "appVersion",
},
orientation: "portrait",
icon: "./assets/icon.png",
-15
View File
@@ -17,28 +17,13 @@
"APP_VARIANT": "preview"
},
"channel": "preview",
"environment": "preview",
"distribution": "internal"
},
"preview:dev": {
"env": {
"APP_VARIANT": "preview",
"MOBILE_VERSION_POLICY": "fingerprint"
},
"channel": "preview",
"environment": "preview",
"developmentClient": true,
"distribution": "internal",
"android": {
"buildType": "apk"
}
},
"production": {
"env": {
"APP_VARIANT": "production"
},
"channel": "production",
"environment": "production",
"autoIncrement": true
}
},
+1 -4
View File
@@ -16,7 +16,6 @@
"android:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform android && expo run:android",
"eas:android:dev": "eas build --profile development -p android",
"eas:android:preview": "eas build --profile preview -p android",
"eas:android:preview:dev": "eas build --profile preview:dev -p android",
"eas:android:prod": "eas build --profile production -p android",
"ios": "EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"ios:dev": "APP_VARIANT=development EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
@@ -24,17 +23,15 @@
"ios:prod": "APP_VARIANT=production EXPO_NO_GIT_STATUS=1 expo prebuild --clean --platform ios && expo run:ios",
"eas:ios:dev": "eas build --profile development -p ios",
"eas:ios:preview": "eas build --profile preview -p ios",
"eas:ios:preview:dev": "eas build --profile preview:dev -p ios",
"eas:ios:prod": "eas build --profile production -p ios",
"eas:dev": "eas build --profile development",
"eas:preview": "eas build --profile preview",
"eas:preview:dev": "eas build --profile preview:dev",
"eas:prod": "eas build --profile production",
"config:dev": "APP_VARIANT=development expo config",
"config:preview": "APP_VARIANT=preview expo config",
"config:prod": "APP_VARIANT=production expo config",
"profile:android:hermes": "mkdir -p profiles/review && react-native profile-hermes profiles/review",
"test": "vp test run",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { extractPairingUrlFromQrPayload, parsePairingUrl } from "./pairing";
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const expoMocks = vi.hoisted(() => ({
requireNativeView: vi.fn(),
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
countReviewCommentContexts,
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
getDefaultReviewExpandedFileIds,
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
resolveReviewHighlighterEngine,
@@ -1,4 +1,4 @@
import { assert, beforeEach, it } from "vite-plus/test";
import { assert, beforeEach, it } from "vitest";
import { AtomRegistry } from "effect/unstable/reactivity";
import {
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
MessageId,
@@ -1,5 +1,5 @@
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
@@ -1,4 +1,4 @@
import { assert, it } from "vite-plus/test";
import { assert, it } from "vitest";
import {
getReviewAsyncStateSnapshot,
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { applyDiffRangesToTokens, computeWordAltDiffRanges } from "./reviewWordDiffs";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import type { ReviewRenderableFile } from "./reviewModel";
import { highlightReviewFile } from "./shikiReviewHighlighter";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { buildNativeReviewTokensResetKey, hashReviewDiffKey } from "./useNativeReviewDiffBridge";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { resolveTerminalRouteBootstrap } from "./terminalRouteBootstrap";
@@ -1,4 +1,4 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const expoMocks = vi.hoisted(() => ({
requireNativeView: vi.fn(),
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { getTerminalBufferReplayKey, getTerminalSurfaceReplayBuffer } from "./terminalBufferReplay";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import {
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import type { KnownTerminalSession } from "@t3tools/client-runtime";
import { DEFAULT_TERMINAL_ID, EnvironmentId, ThreadId } from "@t3tools/contracts";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
DEFAULT_TERMINAL_FONT_SIZE,
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { buildGhosttyThemeConfig, getPierreTerminalTheme } from "./terminalTheme";
@@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it } from "vite-plus/test";
import { beforeEach, describe, expect, it } from "vitest";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import {
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
import { makeQueuedMessageMetadata, makeTurnCommandMetadata } from "./commandMetadata";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
import { mobileAuthClientMetadata, redactPairingCredential } from "./connection";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
EventId,
+4 -3
View File
@@ -16,10 +16,11 @@
"type": "module",
"scripts": {
"dev": "node --watch src/bin.ts",
"build:bundle": "vp pack",
"build": "node scripts/cli.ts build",
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"typecheck": "tsgo --noEmit",
"test": "vp test run"
"test": "vitest run"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.3.154",
@@ -42,7 +43,7 @@
"@types/node": "catalog:",
"effect-acp": "workspace:*",
"effect-codex-app-server": "workspace:*",
"vite-plus": "catalog:",
"tsdown": "catalog:",
"vitest": "catalog:"
},
"engines": {
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/env node
#!/usr/bin/env bun
// @effect-diagnostics nodeBuiltinImport:off
import { appendFileSync } from "node:fs";
+4 -22
View File
@@ -17,7 +17,7 @@ import {
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import { fromYaml } from "@t3tools/shared/schemaYaml";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
interface PackageJson {
@@ -39,13 +39,6 @@ interface PackageJson {
const PackageJsonPrettyJson = fromJsonStringPretty(Schema.Unknown);
const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
const WorkspaceConfig = Schema.Struct({
catalog: Schema.optional(Schema.Record(Schema.String, Schema.String)),
overrides: Schema.optional(Schema.Record(Schema.String, Schema.String)),
});
type WorkspaceConfig = typeof WorkspaceConfig.Type;
const decodeWorkspaceConfig = Schema.decodeEffect(fromYaml(WorkspaceConfig));
class CliError extends Data.TaggedError("CliError")<{
readonly message: string;
readonly cause?: unknown;
@@ -55,14 +48,6 @@ const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
);
const readWorkspaceConfig = Effect.fn("readWorkspaceConfig")(function* () {
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const repoRoot = yield* RepoRoot;
const workspaceYaml = yield* fs.readFileString(path.join(repoRoot, "pnpm-workspace.yaml"));
return yield* decodeWorkspaceConfig(workspaceYaml);
});
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const child = yield* spawner.spawn(command);
@@ -230,9 +215,6 @@ const publishCmd = Command.make(
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
Effect.gen(function* () {
const version = Option.getOrElse(config.appVersion, () => serverPackageJson.version);
const workspaceConfig = yield* readWorkspaceConfig();
const workspaceCatalog = workspaceConfig.catalog ?? {};
const workspaceOverrides = workspaceConfig.overrides ?? {};
const pkg: PackageJson = {
name: serverPackageJson.name,
repository: serverPackageJson.repository,
@@ -243,12 +225,12 @@ const publishCmd = Command.make(
files: serverPackageJson.files,
dependencies: resolveCatalogDependencies(
serverPackageJson.dependencies,
workspaceCatalog,
rootPackageJson.workspaces.catalog,
"apps/server",
),
overrides: resolveCatalogDependencies(
workspaceOverrides,
workspaceCatalog,
rootPackageJson.overrides,
rootPackageJson.workspaces.catalog,
"apps/server",
),
};
+1 -1
View File
@@ -3,7 +3,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
createAttachmentId,
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { deriveAuthClientMetadata } from "./utils.ts";
+1 -1
View File
@@ -10,7 +10,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as TestClock from "effect/testing/TestClock";
import { vi } from "vite-plus/test";
import { vi } from "vitest";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
import { assertNone, assertSome } from "@effect/vitest/utils";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
+1 -1
View File
@@ -1,4 +1,4 @@
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import { parsePatchFiles } from "@pierre/diffs";
export interface TurnDiffFileSummary {
readonly path: string;
@@ -2,7 +2,7 @@ import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
ProjectionSnapshotQuery,
@@ -8,7 +8,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import { describe, expect } from "vite-plus/test";
import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import { vi } from "vite-plus/test";
import { vi } from "vitest";
import { ProcessRunner, ProcessSpawnError, type ProcessRunnerShape } from "../../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
+1 -1
View File
@@ -11,7 +11,7 @@ import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vite-plus/test";
import { expect } from "vitest";
import type {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
@@ -28,7 +28,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
@@ -17,7 +17,7 @@ import * as Metric from "effect/Metric";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -3,7 +3,7 @@ import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Scope from "effect/Scope";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it } from "vitest";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
@@ -28,7 +28,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { TextGenerationError } from "@t3tools/contracts";
@@ -30,7 +30,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it } from "vitest";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -2,7 +2,7 @@ import { ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { logCleanupCauseUnlessInterrupted } from "./ThreadDeletionReactor.ts";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
MessageId,
CommandId,
@@ -7,7 +7,7 @@ import {
type OrchestrationEvent,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
+14 -23
View File
@@ -1,5 +1,4 @@
import * as NodeOS from "node:os";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Path from "effect/Path";
import {
@@ -16,11 +15,7 @@ import {
type WindowsCommandAvailabilityChecker = (
command: string,
options?: CommandAvailabilityOptions,
) => Effect.Effect<boolean, never>;
class ShellPathReadError extends Data.TaggedError("ShellPathReadError")<{
readonly cause: unknown;
}> {}
) => boolean;
function logPathHydrationWarning(message: string, error?: unknown): void {
process.stderr.write(
@@ -28,7 +23,7 @@ function logPathHydrationWarning(message: string, error?: unknown): void {
);
}
export const fixPath = Effect.fn("fixPath")(function* (
export function fixPath(
options: {
env?: NodeJS.ProcessEnv;
platform?: NodeJS.Platform;
@@ -39,15 +34,15 @@ export const fixPath = Effect.fn("fixPath")(function* (
userShell?: string;
logWarning?: (message: string, error?: unknown) => void;
} = {},
) {
): void {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const logWarning = options.logWarning ?? logPathHydrationWarning;
const readPath = options.readPath ?? readPathFromLoginShell;
yield* Effect.gen(function* () {
try {
if (platform === "win32") {
const repairedEnvironment = yield* resolveWindowsEnvironment(env, {
const repairedEnvironment = resolveWindowsEnvironment(env, {
readEnvironment: options.readWindowsEnvironment ?? readEnvironmentFromWindowsShell,
...(options.isWindowsCommandAvailable
? { commandAvailable: options.isWindowsCommandAvailable }
@@ -65,17 +60,11 @@ export const fixPath = Effect.fn("fixPath")(function* (
let shellPath: string | undefined;
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
shellPath = yield* Effect.try({
try: () => readPath(shell),
catch: (error) => new ShellPathReadError({ cause: error }),
}).pipe(
Effect.catchTag("ShellPathReadError", (error) =>
Effect.sync(() => {
logWarning(`Failed to read PATH from login shell ${shell}.`, error.cause);
return undefined;
}),
),
);
try {
shellPath = readPath(shell);
} catch (error) {
logWarning(`Failed to read PATH from login shell ${shell}.`, error);
}
if (shellPath) {
break;
@@ -90,8 +79,10 @@ export const fixPath = Effect.fn("fixPath")(function* (
if (mergedPath) {
env.PATH = mergedPath;
}
});
});
} catch (error) {
logWarning("Failed to hydrate PATH from the user environment.", error);
}
}
export const expandHomePath = Effect.fn(function* (input: string) {
const { join } = yield* Path.Path;
+1 -1
View File
@@ -1,7 +1,7 @@
// @effect-diagnostics nodeBuiltinImport:off
import { homedir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { expandHomePath } from "./pathExpansion.ts";
@@ -672,22 +672,17 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(yield* isCommandAvailable("code", { platform: "win32", env }), true);
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
it.effect("returns false when a command is not on PATH", () =>
Effect.gen(function* () {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(
yield* isCommandAvailable("definitely-not-installed", { platform: "win32", env }),
false,
);
}),
);
it("returns false when a command is not on PATH", () => {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
});
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
@@ -699,7 +694,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(yield* isCommandAvailable("npm", { platform: "win32", env }), false);
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
}),
);
@@ -713,7 +708,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(yield* isCommandAvailable("my.tool", { platform: "win32", env }), true);
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
}),
);
@@ -729,7 +724,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(yield* isCommandAvailable("code", { platform: "win32", env }), true);
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
});
@@ -757,7 +752,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
yield* fs.writeFileString(path.join(dir, "rustrover.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "webstorm.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
const editors = yield* resolveAvailableEditors("win32", {
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
@@ -793,19 +788,17 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
yield* fs.chmod(path.join(dir, "xdg-open"), 0o755);
const editors = yield* resolveAvailableEditors("linux", {
const editors = resolveAvailableEditors("linux", {
PATH: dir,
});
assert.deepEqual(editors, ["zed", "file-manager"]);
}),
);
it.effect("omits file-manager when the platform opener is unavailable", () =>
Effect.gen(function* () {
const editors = yield* resolveAvailableEditors("linux", {
PATH: "",
});
assert.deepEqual(editors, []);
}),
);
it("omits file-manager when the platform opener is unavailable", () => {
const editors = resolveAvailableEditors("linux", {
PATH: "",
});
assert.deepEqual(editors, []);
});
});
+29 -49
View File
@@ -16,10 +16,8 @@ import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/sh
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
// ==============================
@@ -111,17 +109,17 @@ function resolveEditorArgs(
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
}
const resolveAvailableCommand = Effect.fn("externalLauncher.resolveAvailableCommand")(function* (
function resolveAvailableCommand(
commands: ReadonlyArray<string>,
options: CommandAvailabilityOptions = {},
): Effect.fn.Return<Option.Option<string>, never, FileSystem.FileSystem | Path.Path> {
): Option.Option<string> {
for (const command of commands) {
if (yield* isCommandAvailable(command, options)) {
if (isCommandAvailable(command, options)) {
return Option.some(command);
}
}
return Option.none();
});
}
function encodeUtf16LeBase64(input: string): string {
const bytes = new Uint8Array(input.length * 2);
@@ -214,31 +212,29 @@ export function resolveBrowserLaunch(
};
}
export const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEditors")(
function* (
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<ReadonlyArray<EditorId>, never, FileSystem.FileSystem | Path.Path> {
const available: EditorId[] = [];
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.commands === null) {
const command = fileManagerCommandForPlatform(platform);
if (yield* isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
continue;
}
const command = yield* resolveAvailableCommand(editor.commands, { platform, env });
if (Option.isSome(command)) {
for (const editor of EDITORS) {
if (editor.commands === null) {
const command = fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
continue;
}
return available;
},
);
const command = resolveAvailableCommand(editor.commands, { platform, env });
if (Option.isSome(command)) {
available.push(editor.id);
}
}
return available;
}
/**
* ExternalLauncherShape - Service API for browser and editor launch actions.
@@ -272,7 +268,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
input: LaunchEditorInput,
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<EditorLaunch, ExternalLauncherError, FileSystem.FileSystem | Path.Path> {
): Effect.fn.Return<EditorLaunch, ExternalLauncherError> {
yield* Effect.annotateCurrentSpan({
"externalLauncher.editor": input.editor,
"externalLauncher.cwd": input.cwd,
@@ -285,7 +281,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
if (editorDef.commands) {
const command = Option.getOrElse(
yield* resolveAvailableCommand(editorDef.commands, { platform, env }),
resolveAvailableCommand(editorDef.commands, { platform, env }),
() => editorDef.commands[0],
);
return {
@@ -324,12 +320,8 @@ export const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(functio
export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
launch: EditorLaunch,
): Effect.fn.Return<
void,
ExternalLauncherError,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> {
if (!(yield* isCommandAvailable(launch.command))) {
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
if (!isCommandAvailable(launch.command)) {
return yield* new ExternalLauncherError({
message: `Editor command not found: ${launch.command}`,
});
@@ -354,16 +346,6 @@ export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProce
const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const provideCommandResolutionServices = <A, E, R>(
effect: Effect.Effect<A, E, R | FileSystem.FileSystem | Path.Path>,
) =>
effect.pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
);
return {
launchBrowser: (target) =>
@@ -371,11 +353,9 @@ const make = Effect.gen(function* () {
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
launchEditor: (input) =>
provideCommandResolutionServices(
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
launchEditorProcess(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
launchEditorProcess(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
),
} satisfies ExternalLauncherShape;
@@ -2,7 +2,7 @@ import { ProjectId, type OrchestrationProject } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
@@ -1,9 +1,10 @@
/**
* CursorDriver — `ProviderDriver` for the Cursor Agent (`agent`) runtime.
*
* Cursor exposes an ACP-based CLI. Model catalog and capability refreshes
* happen during the managed provider status check via Cursor's
* `list_available_models` extension method.
* Cursor exposes an ACP-based CLI. The driver is still a plain value, but
* its snapshot uses `makeManagedServerProvider`'s optional `enrichSnapshot`
* hook to run the slow ACP model-capability probe in the background without
* blocking the initial `ready`-state publish.
*
* Text generation is supported via the ACP runtime — `makeCursorTextGeneration`
* drives `runtime.prompt` with a structured-output schema and collects the
@@ -138,17 +139,20 @@ export const CursorDriver: ProviderDriver<CursorSettings, CursorDriverEnv> = {
initialSnapshot: (settings) =>
buildInitialCursorProviderSnapshot(settings).pipe(Effect.map(stampIdentity)),
checkProvider,
// Model catalog and capabilities come exclusively from Cursor's
// list_available_models extension method during provider checks.
// Preserve the background ACP model-capability probe that used to
// live on `CursorProviderLive`. Only fires when the snapshot reports
// an authenticated, enabled provider with at least one non-custom
// model whose capabilities haven't been captured yet.
enrichSnapshot: ({ settings, snapshot: currentSnapshot, publishSnapshot }) =>
enrichCursorSnapshot({
settings,
environment: processEnv,
snapshot: currentSnapshot,
maintenanceCapabilities,
publishSnapshot,
stampIdentity,
httpClient,
}),
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner)),
refreshInterval: SNAPSHOT_REFRESH_INTERVAL,
}).pipe(
Effect.mapError(
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { describe, it } from "vite-plus/test";
import { describe, it } from "vitest";
import { ThreadId } from "@t3tools/contracts";
import * as CodexErrors from "effect-codex-app-server/errors";
import * as CodexRpc from "effect-codex-app-server/rpc";
@@ -37,8 +37,7 @@ class CursorAdapter extends Context.Service<CursorAdapter, CursorAdapterShape>()
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const mockAgentPath = path.join(__dirname, "../../../scripts/acp-mock-agent.ts");
const mockAgentCommand = "node";
const mockAgentArgs = [mockAgentPath] as const;
const bunExe = "bun";
async function makeMockAgentWrapper(
extraEnv?: Record<string, string>,
@@ -52,7 +51,7 @@ async function makeMockAgentWrapper(
const script = `#!/bin/sh
${envExports}
${options?.initialDelaySeconds ? `sleep ${JSON.stringify(String(options.initialDelaySeconds))}` : ""}
exec ${JSON.stringify(mockAgentCommand)} ${mockAgentArgs.map((arg) => JSON.stringify(arg)).join(" ")} "$@"
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
@@ -74,7 +73,7 @@ printf '%s\t' "$@" >> ${JSON.stringify(argvLogPath)}
printf '\n' >> ${JSON.stringify(argvLogPath)}
export T3_ACP_REQUEST_LOG_PATH=${JSON.stringify(requestLogPath)}
${envExports}
exec ${JSON.stringify(mockAgentCommand)} ${mockAgentArgs.map((arg) => JSON.stringify(arg)).join(" ")} "$@"
exec ${JSON.stringify(bunExe)} ${JSON.stringify(mockAgentPath)} "$@"
`;
await writeFile(wrapperPath, script, "utf8");
await chmod(wrapperPath, 0o755);
@@ -4,15 +4,17 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import type * as EffectAcpSchema from "effect-acp/schema";
import type { CursorSettings } from "@t3tools/contracts";
import type { CursorSettings, ServerProviderModel } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import {
buildCursorProviderSnapshot,
buildCursorCapabilitiesFromConfigOptions,
buildCursorDiscoveredModelsFromConfigOptions,
checkCursorProviderStatus,
discoverCursorModelCapabilitiesViaAcp,
discoverCursorModelsViaAcp,
getCursorFallbackModels,
getCursorParameterizedModelPickerUnsupportedMessage,
@@ -68,13 +70,16 @@ const makeMockAgentWrapper = Effect.fn("makeMockAgentWrapper")(function* (
prefix: "cursor-provider-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const mockAgentCommand = ["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" ");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const bunCommand = JSON.stringify("bun");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const mockAgentPathJson = JSON.stringify(mockAgentPath);
const envExports = Object.entries(extraEnv ?? {})
.map(([key, value]) => `export ${key}=${JSON.stringify(value)}`)
.join("\n");
const script = `#!/bin/sh
${envExports}
exec ${mockAgentCommand} "$@"
exec ${bunCommand} ${mockAgentPathJson} "$@"
`;
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
@@ -90,14 +95,17 @@ const makeMockAgentWithAboutWrapper = Effect.fn("makeMockAgentWithAboutWrapper")
prefix: "cursor-provider-about-mock-",
});
const wrapperPath = path.join(dir, "fake-agent.sh");
const mockAgentCommand = ["node", mockAgentPath].map((arg) => JSON.stringify(arg)).join(" ");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const bunCommand = JSON.stringify("bun");
// @effect-diagnostics-next-line preferSchemaOverJson:off
const mockAgentPathJson = JSON.stringify(mockAgentPath);
const script = `#!/bin/sh
if [ "$1" = "about" ]; then
printf 'CLI Version 2026.04.09-f2b0fcd\\n'
printf 'User Email [email protected]\\n'
exit 0
fi
exec ${mockAgentCommand} "$@"
exec ${bunCommand} ${mockAgentPathJson} "$@"
`;
yield* fileSystem.writeFileString(wrapperPath, script);
yield* fileSystem.chmod(wrapperPath, 0o755);
@@ -287,6 +295,48 @@ const parameterizedClaudeModelOptionConfigOptions = [
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const sessionNewCursorConfigOptions = [
{
type: "select",
currentValue: "agent",
options: [
{ name: "Agent", value: "agent", description: "Full agent capabilities with tool access" },
],
category: "mode",
id: "mode",
name: "Mode",
description: "Controls how the agent executes tasks",
},
{
type: "select",
currentValue: "composer-2",
options: [
{ name: "Auto", value: "default" },
{ name: "Composer 2", value: "composer-2" },
{ name: "GPT-5.4", value: "gpt-5.4" },
{ name: "Sonnet 4.6", value: "claude-sonnet-4-6" },
{ name: "Opus 4.6", value: "claude-opus-4-6" },
{ name: "Codex 5.3 Spark", value: "gpt-5.3-codex-spark" },
],
category: "model",
id: "model",
name: "Model",
description: "Controls which model is used for responses",
},
{
type: "select",
currentValue: "true",
options: [
{ name: "Off", value: "false" },
{ name: "Fast", value: "true" },
],
category: "model_config",
id: "fast",
name: "Fast",
description: "Faster speeds.",
},
] satisfies ReadonlyArray<EffectAcpSchema.SessionConfigOption>;
const baseCursorSettings: CursorSettings = {
enabled: true,
binaryPath: "agent",
@@ -294,6 +344,8 @@ const baseCursorSettings: CursorSettings = {
customModels: [],
};
const emptyCapabilities = createModelCapabilities({ optionDescriptors: [] });
describe("getCursorFallbackModels", () => {
it("does not publish any built-in cursor models before ACP discovery", () => {
expect(
@@ -410,6 +462,51 @@ describe("buildCursorCapabilitiesFromConfigOptions", () => {
});
});
describe("buildCursorDiscoveredModelsFromConfigOptions", () => {
it("publishes ACP model choices immediately from session/new config options", () => {
expect(buildCursorDiscoveredModelsFromConfigOptions(sessionNewCursorConfigOptions)).toEqual([
{
slug: "default",
name: "Auto",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "composer-2",
name: "Composer 2",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [booleanDescriptor("fastMode", "Fast", true)],
}),
},
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "claude-sonnet-4-6",
name: "Sonnet 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
{
slug: "gpt-5.3-codex-spark",
name: "Codex 5.3 Spark",
isCustom: false,
capabilities: emptyCapabilities,
},
]);
});
});
describe("checkCursorProviderStatus", () => {
it("passes the injected environment to ACP model discovery", async () => {
const { requestLogPath, wrapperPath } = await runNode(makeProviderStatusEnvFixture());
@@ -479,6 +576,64 @@ describe("discoverCursorModelsViaAcp", () => {
});
});
describe("discoverCursorModelCapabilitiesViaAcp", () => {
it("discovers model capabilities through Cursor's list_available_models extension method", async () => {
const { exitLogPath, wrapperPath } = await runNode(
makeExitLogFixture("cursor-capabilities-exit-log-"),
);
const existingModels: ReadonlyArray<ServerProviderModel> = [
{ slug: "default", name: "Auto", isCustom: false, capabilities: emptyCapabilities },
{ slug: "composer-2", name: "Composer 2", isCustom: false, capabilities: emptyCapabilities },
{ slug: "gpt-5.4", name: "GPT-5.4", isCustom: false, capabilities: emptyCapabilities },
{
slug: "claude-opus-4-6",
name: "Opus 4.6",
isCustom: false,
capabilities: emptyCapabilities,
},
];
const models = await Effect.runPromise(
discoverCursorModelCapabilitiesViaAcp(
{
enabled: true,
binaryPath: wrapperPath,
apiEndpoint: "",
customModels: [],
},
existingModels,
).pipe(Effect.provide(NodeServices.layer)),
);
expect(models.map((model) => model.slug)).toEqual([
"default",
"composer-2",
"gpt-5.4",
"claude-opus-4-6",
]);
expect(models.find((model) => model.slug === "gpt-5.4")?.capabilities).toEqual(
createModelCapabilities({
optionDescriptors: [
selectDescriptor("reasoning", "Reasoning", [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
{ id: "xhigh", label: "Extra High" },
]),
selectDescriptor("contextWindow", "Context", [
{ id: "272k", label: "272K", isDefault: true },
{ id: "1m", label: "1M" },
]),
booleanDescriptor("fastMode", "Fast", false),
],
}),
);
const exitLog = await runNode(waitForFileContent(exitLogPath));
expect(exitLog.match(/SIGTERM/g)?.length ?? 0).toBe(1);
});
});
describe("parseCursorAboutOutput", () => {
it("parses json about output and forwards subscription metadata", () => {
expect(
+133 -16
View File
@@ -45,9 +45,6 @@ import {
import { AcpSessionRuntime } from "../acp/AcpSessionRuntime.ts";
import { CursorListAvailableModelsResponse } from "../acp/CursorAcpExtension.ts";
const decodeCursorListAvailableModelsResponse = Schema.decodeUnknownEffect(
CursorListAvailableModelsResponse,
);
const PROVIDER = ProviderDriverKind.make("cursor");
const CURSOR_PRESENTATION = {
displayName: "Cursor",
@@ -157,6 +154,12 @@ function normalizeCursorReasoningValue(value: string | null | undefined): string
}
}
function findCursorModelConfigOption(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption>,
): EffectAcpSchema.SessionConfigOption | undefined {
return configOptions.find((option) => option.category === "model");
}
function getCursorConfigOptionCategory(option: EffectAcpSchema.SessionConfigOption): string {
return option.category?.trim().toLowerCase() ?? "";
}
@@ -370,6 +373,39 @@ function buildCursorDiscoveredModels(
});
}
function hasCursorModelCapabilities(model: Pick<ServerProviderModel, "capabilities">): boolean {
return (model.capabilities?.optionDescriptors?.length ?? 0) > 0;
}
export function buildCursorDiscoveredModelsFromConfigOptions(
configOptions: ReadonlyArray<EffectAcpSchema.SessionConfigOption> | null | undefined,
): ReadonlyArray<ServerProviderModel> {
if (!configOptions || configOptions.length === 0) {
return [];
}
const modelOption = findCursorModelConfigOption(configOptions);
const modelChoices = flattenSessionConfigSelectOptions(modelOption);
if (!modelOption || modelChoices.length === 0) {
return [];
}
const currentModelValue =
modelOption.type === "select" ? modelOption.currentValue?.trim() || undefined : undefined;
const currentModelCapabilities = buildCursorCapabilitiesFromConfigOptions(configOptions);
return buildCursorDiscoveredModels(
modelChoices.map((modelChoice) => ({
slug: modelChoice.value.trim(),
name: modelChoice.name.trim(),
capabilities:
currentModelValue === modelChoice.value.trim()
? currentModelCapabilities
: EMPTY_CAPABILITIES,
})),
);
}
function buildCursorDiscoveredModelsFromAvailableModelsResponse(
response: typeof CursorListAvailableModelsResponse.Type,
): ReadonlyArray<ServerProviderModel> {
@@ -550,7 +586,9 @@ const discoverCursorModelsViaListAvailableModels = (
Effect.gen(function* () {
yield* acp.start();
const response = yield* acp.request("cursor/list_available_models", {});
const decoded = yield* decodeCursorListAvailableModelsResponse(response);
const decoded = yield* Schema.decodeUnknownEffect(CursorListAvailableModelsResponse)(
response,
);
return buildCursorDiscoveredModelsFromAvailableModelsResponse(decoded);
}),
environment,
@@ -559,7 +597,34 @@ const discoverCursorModelsViaListAvailableModels = (
export const discoverCursorModelsViaAcp = (
cursorSettings: CursorSettings,
environment: NodeJS.ProcessEnv = process.env,
) => discoverCursorModelsViaListAvailableModels(cursorSettings, environment);
) =>
discoverCursorModelsViaListAvailableModels(cursorSettings, environment).pipe(
Effect.catchCause(() =>
withCursorAcpProbeRuntime(
cursorSettings,
(acp) =>
Effect.map(acp.start(), (started) =>
buildCursorDiscoveredModelsFromConfigOptions(
started.sessionSetupResult.configOptions ?? [],
),
),
environment,
),
),
);
export const discoverCursorModelCapabilitiesViaAcp = (
cursorSettings: CursorSettings,
existingModels: ReadonlyArray<ServerProviderModel>,
environment: NodeJS.ProcessEnv = process.env,
) =>
discoverCursorModelsViaListAvailableModels(cursorSettings, environment).pipe(
Effect.withSpan("cursor-acp-model-capability-discovery", {
attributes: {
"cursor.acp.existing_model_count": existingModels.length,
},
}),
);
export function getCursorFallbackModels(
cursorSettings: Pick<CursorSettings, "customModels">,
@@ -1091,30 +1156,36 @@ export const checkCursorProviderStatus = Effect.fn("checkCursorProviderStatus")(
});
});
export function hasUncapturedCursorModels(snapshot: Pick<ServerProvider, "models">): boolean {
return snapshot.models.some((model) => !model.isCustom && !hasCursorModelCapabilities(model));
}
/**
* Background maintenance enrichment for a Cursor snapshot.
* Background capability enrichment for a Cursor snapshot.
*
* Used by `CursorDriver` as the `makeManagedServerProvider.enrichSnapshot`
* hook: republishes update/version advisory metadata without performing any
* model or capability discovery. Cursor model data comes exclusively from
* `cursor/list_available_models` during provider status checks.
* hook: runs the slow ACP per-model capability probe, and republishes the
* snapshot through `publishSnapshot` when new capabilities arrive. Skips
* the probe when the provider is disabled, unauthenticated, or has no
* uncaptured models. Keeps `EMPTY_CAPABILITIES` and the `PROVIDER` literal
* private to this module.
*/
export const enrichCursorSnapshot = (input: {
readonly settings: CursorSettings;
readonly environment?: NodeJS.ProcessEnv;
readonly snapshot: ServerProvider;
readonly maintenanceCapabilities: ProviderMaintenanceCapabilities;
readonly publishSnapshot: (snapshot: ServerProvider) => Effect.Effect<void>;
readonly stampIdentity?: (snapshot: ServerProvider) => ServerProvider;
readonly httpClient: HttpClient.HttpClient;
}): Effect.Effect<void> => {
}): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
const { settings, snapshot, publishSnapshot } = input;
const stampIdentity = input.stampIdentity ?? ((value) => value);
if (!settings.enabled || snapshot.auth.status === "unauthenticated") {
return Effect.void;
}
return enrichProviderSnapshotWithVersionAdvisory(snapshot, input.maintenanceCapabilities).pipe(
const enrichVersionAdvisory = enrichProviderSnapshotWithVersionAdvisory(
snapshot,
input.maintenanceCapabilities,
).pipe(
Effect.provideService(HttpClient.HttpClient, input.httpClient),
Effect.flatMap((enrichedSnapshot) =>
publishSnapshot(stampIdentity(enrichedSnapshot)).pipe(Effect.as(enrichedSnapshot)),
@@ -1122,7 +1193,53 @@ export const enrichCursorSnapshot = (input: {
Effect.catchCause((cause) =>
Effect.logWarning("Cursor version advisory enrichment failed", {
cause: Cause.pretty(cause),
}).pipe(Effect.asVoid),
}).pipe(Effect.as(snapshot)),
),
);
return enrichVersionAdvisory.pipe(
Effect.flatMap((baseSnapshot) => {
if (
!settings.enabled ||
baseSnapshot.auth.status === "unauthenticated" ||
!hasUncapturedCursorModels(baseSnapshot)
) {
return Effect.void;
}
return discoverCursorModelCapabilitiesViaAcp(
settings,
baseSnapshot.models,
input.environment,
).pipe(
Effect.flatMap((discoveredModels) => {
if (discoveredModels.length === 0) {
return Effect.void;
}
const discoveredSlugs = new Set(discoveredModels.map((m) => m.slug));
const mergedModels = [
...discoveredModels,
...baseSnapshot.models.filter((m) => !discoveredSlugs.has(m.slug)),
];
return publishSnapshot(
stampIdentity({
...baseSnapshot,
models: providerModelsFromSettings(
mergedModels,
PROVIDER,
settings.customModels,
EMPTY_CAPABILITIES,
),
}),
);
}),
Effect.catchCause((cause) =>
Effect.logWarning("Cursor ACP background capability enrichment failed", {
models: baseSnapshot.models.map((model) => model.slug),
cause: Cause.pretty(cause),
}).pipe(Effect.asVoid),
),
);
}),
);
};
@@ -11,7 +11,7 @@ import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { beforeEach } from "vite-plus/test";
import { beforeEach } from "vitest";
import {
OpenCodeSettings,
@@ -5,7 +5,7 @@ import { it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import { beforeEach } from "vite-plus/test";
import { beforeEach } from "vitest";
import { OpenCodeSettings } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
@@ -1131,11 +1131,6 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const initialCheckedAt = initialCodex?.checkedAt;
assert.notStrictEqual(initialCheckedAt, undefined);
// The rebuilt instance may re-probe synchronously during the
// settings update. Advance the TestClock first so `checkedAt`
// can safely act as the fresh-probe marker this assertion uses.
yield* TestClock.adjust("1 second");
// Drive a settings change. The Hydration layer's
// `SettingsWatcherLive` consumes this via `streamChanges`,
// calls `reconcile`, which rebuilds the codex instance (the
@@ -15,7 +15,7 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { mergeProviderInstanceEnvironment } from "./ProviderInstanceEnvironment.ts";
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import * as EffectAcpErrors from "effect-acp/errors";
import { ProviderDriverKind } from "@t3tools/contracts";
@@ -1,5 +1,5 @@
import { ProviderDriverKind, RuntimeRequestId, TurnId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
makeAcpAssistantItemEvent,
Loaded 100 of 325 files, more files were not shown because too many files have changed in this diff. Show more