Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05f0d160a1 | ||
|
|
ce1b679cc9 | ||
|
|
1fd62443af | ||
|
|
cc5871a8ba |
No files matched your search
@@ -9,7 +9,7 @@ on:
|
||||
jobs:
|
||||
quality:
|
||||
name: Format, Lint, Typecheck, Test, Browser Test, Build
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: blacksmith-4vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -71,12 +71,12 @@ jobs:
|
||||
|
||||
- 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 -f apps/desktop/dist-electron/preload.js
|
||||
grep -nE "desktopBridge|getLocalEnvironmentBootstrap|PICK_FOLDER_CHANNEL|wsUrl" apps/desktop/dist-electron/preload.js
|
||||
|
||||
release_smoke:
|
||||
name: Release Smoke
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -92,8 +92,5 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Exercise release-only workflow steps
|
||||
run: node scripts/release-smoke.ts
|
||||
+47
-176
@@ -1,24 +1,14 @@
|
||||
name: Release
|
||||
name: Release Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
schedule:
|
||||
- cron: "0 9 * * *"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
channel:
|
||||
description: "Release channel"
|
||||
required: false
|
||||
default: stable
|
||||
type: choice
|
||||
options:
|
||||
- stable
|
||||
- nightly
|
||||
version:
|
||||
description: "Release version (for example 1.2.3 or v1.2.3)"
|
||||
required: false
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
@@ -28,24 +18,43 @@ permissions:
|
||||
jobs:
|
||||
preflight:
|
||||
name: Preflight
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
outputs:
|
||||
release_channel: ${{ steps.release_meta.outputs.release_channel }}
|
||||
version: ${{ steps.release_meta.outputs.version }}
|
||||
tag: ${{ steps.release_meta.outputs.tag }}
|
||||
release_name: ${{ steps.release_meta.outputs.name }}
|
||||
short_sha: ${{ steps.release_meta.outputs.short_sha }}
|
||||
previous_tag: ${{ steps.previous_tag.outputs.previous_tag }}
|
||||
cli_dist_tag: ${{ steps.release_meta.outputs.cli_dist_tag }}
|
||||
is_prerelease: ${{ steps.release_meta.outputs.is_prerelease }}
|
||||
make_latest: ${{ steps.release_meta.outputs.make_latest }}
|
||||
ref: ${{ github.sha }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${{ github.event.inputs.version }}"
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
@@ -60,60 +69,6 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- id: release_meta
|
||||
name: Resolve release version
|
||||
shell: bash
|
||||
env:
|
||||
DISPATCH_CHANNEL: ${{ github.event.inputs.channel }}
|
||||
DISPATCH_VERSION: ${{ github.event.inputs.version }}
|
||||
NIGHTLY_DATE: ${{ github.run_started_at }}
|
||||
NIGHTLY_SHA: ${{ github.sha }}
|
||||
NIGHTLY_RUN_NUMBER: ${{ github.run_number }}
|
||||
run: |
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "schedule" || ( "${GITHUB_EVENT_NAME}" == "workflow_dispatch" && "${DISPATCH_CHANNEL:-stable}" == "nightly" ) ]]; then
|
||||
nightly_date="$(date -u -d "$NIGHTLY_DATE" +%Y%m%d)"
|
||||
|
||||
node scripts/resolve-nightly-release.ts \
|
||||
--date "$nightly_date" \
|
||||
--run-number "$NIGHTLY_RUN_NUMBER" \
|
||||
--sha "$NIGHTLY_SHA" \
|
||||
--github-output
|
||||
|
||||
echo "release_channel=nightly" >> "$GITHUB_OUTPUT"
|
||||
echo "cli_dist_tag=nightly" >> "$GITHUB_OUTPUT"
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
if [[ "${GITHUB_EVENT_NAME}" == "workflow_dispatch" ]]; then
|
||||
raw="${DISPATCH_VERSION}"
|
||||
if [[ -z "$raw" ]]; then
|
||||
echo "workflow_dispatch stable releases require the version input." >&2
|
||||
exit 1
|
||||
fi
|
||||
else
|
||||
raw="${GITHUB_REF_NAME}"
|
||||
fi
|
||||
|
||||
version="${raw#v}"
|
||||
if [[ ! "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.-][0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo "Invalid release version: $raw" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "release_channel=stable" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$version" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$version" >> "$GITHUB_OUTPUT"
|
||||
echo "name=T3 Code v$version" >> "$GITHUB_OUTPUT"
|
||||
echo "cli_dist_tag=latest" >> "$GITHUB_OUTPUT"
|
||||
if [[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
echo "make_latest=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
fi
|
||||
|
||||
- name: Lint
|
||||
run: bun run lint
|
||||
|
||||
@@ -123,14 +78,6 @@ jobs:
|
||||
- name: Test
|
||||
run: bun run test
|
||||
|
||||
- id: previous_tag
|
||||
name: Resolve previous release tag
|
||||
run: |
|
||||
node scripts/resolve-previous-release-tag.ts \
|
||||
--channel "${{ steps.release_meta.outputs.release_channel }}" \
|
||||
--current-tag "${{ steps.release_meta.outputs.tag }}" \
|
||||
--github-output
|
||||
|
||||
build:
|
||||
name: Build ${{ matrix.label }}
|
||||
needs: preflight
|
||||
@@ -141,30 +88,25 @@ jobs:
|
||||
matrix:
|
||||
include:
|
||||
- label: macOS arm64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
runner: macos-14
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: arm64
|
||||
- label: macOS x64
|
||||
runner: blacksmith-12vcpu-macos-26
|
||||
runner: macos-15-intel
|
||||
platform: mac
|
||||
target: dmg
|
||||
arch: x64
|
||||
- label: Linux x64
|
||||
runner: blacksmith-32vcpu-ubuntu-2404
|
||||
runner: ubuntu-24.04
|
||||
platform: linux
|
||||
target: AppImage
|
||||
arch: x64
|
||||
- label: Windows x64
|
||||
runner: windows-2022 # blacksmith-32vcpu-windows-2025
|
||||
runner: windows-2022
|
||||
platform: win
|
||||
target: nsis
|
||||
arch: x64
|
||||
# - label: Windows arm64
|
||||
# runner: windows-11-arm
|
||||
# platform: win
|
||||
# target: nsis
|
||||
# arch: arm64
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
@@ -264,31 +206,18 @@ jobs:
|
||||
"release/*.AppImage" \
|
||||
"release/*.exe" \
|
||||
"release/*.blockmap" \
|
||||
"release/*.yml"; do
|
||||
"release/latest*.yml"; do
|
||||
for file in $pattern; do
|
||||
cp "$file" release-publish/
|
||||
done
|
||||
done
|
||||
|
||||
if [[ "${{ matrix.platform }}" == "mac" && "${{ matrix.arch }}" != "arm64" ]]; then
|
||||
shopt -s nullglob
|
||||
for manifest in release-publish/*-mac.yml; do
|
||||
mv "$manifest" "${manifest%.yml}-${{ matrix.arch }}.yml"
|
||||
done
|
||||
if [[ -f release-publish/latest-mac.yml ]]; then
|
||||
mv release-publish/latest-mac.yml "release-publish/latest-mac-${{ matrix.arch }}.yml"
|
||||
fi
|
||||
fi
|
||||
|
||||
# Enable if Windows arm64 builds are enabled.
|
||||
# Windows updater metadata is channel-specific (for example
|
||||
# "latest.yml" or "nightly.yml"). Suffix each per-arch copy so the
|
||||
# release job can merge matching arm64/x64 manifests back into one
|
||||
# canonical manifest per channel.
|
||||
# if [[ "${{ matrix.platform }}" == "win" ]]; then
|
||||
# shopt -s nullglob
|
||||
# for manifest in release-publish/*.yml; do
|
||||
# mv "$manifest" "${manifest%.yml}-win-${{ matrix.arch }}.yml"
|
||||
# done
|
||||
# fi
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
@@ -299,7 +228,7 @@ jobs:
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -328,12 +257,12 @@ jobs:
|
||||
run: bun run build --filter=@t3tools/web --filter=t3
|
||||
|
||||
- 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
|
||||
run: node apps/server/scripts/cli.ts publish --tag latest --app-version "${{ needs.preflight.outputs.version }}" --verbose
|
||||
|
||||
release:
|
||||
name: Publish GitHub Release
|
||||
needs: [preflight, build, publish_cli]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -355,71 +284,17 @@ jobs:
|
||||
|
||||
- name: Merge macOS updater manifests
|
||||
run: |
|
||||
shopt -s nullglob
|
||||
for x64_manifest in release-assets/*-mac-x64.yml; do
|
||||
arm64_manifest="${x64_manifest%-x64.yml}.yml"
|
||||
if [[ -f "$arm64_manifest" ]]; then
|
||||
node scripts/merge-update-manifests.ts --platform mac "$arm64_manifest" "$x64_manifest"
|
||||
rm -f "$x64_manifest"
|
||||
fi
|
||||
done
|
||||
|
||||
# - name: Merge Windows updater manifests
|
||||
# run: |
|
||||
# shopt -s nullglob
|
||||
# found_windows_manifest=false
|
||||
# for x64_manifest in release-assets/*-win-x64.yml; do
|
||||
# if [[ "$(basename "$x64_manifest")" == builder-debug-* ]]; then
|
||||
# continue
|
||||
# fi
|
||||
|
||||
# arm64_manifest="${x64_manifest/-x64.yml/-arm64.yml}"
|
||||
# output_manifest="${x64_manifest/-win-x64.yml/.yml}"
|
||||
# if [[ ! -f "$arm64_manifest" ]]; then
|
||||
# echo "Missing matching arm64 Windows manifest for $x64_manifest" >&2
|
||||
# exit 1
|
||||
# fi
|
||||
|
||||
# found_windows_manifest=true
|
||||
# node scripts/merge-update-manifests.ts --platform win \
|
||||
# "$arm64_manifest" \
|
||||
# "$x64_manifest" \
|
||||
# "$output_manifest"
|
||||
# rm -f "$arm64_manifest" "$x64_manifest"
|
||||
# done
|
||||
|
||||
# if [[ "$found_windows_manifest" != true ]]; then
|
||||
# echo "No Windows updater manifests found to merge." >&2
|
||||
# exit 1
|
||||
# fi
|
||||
node scripts/merge-mac-update-manifests.ts \
|
||||
release-assets/latest-mac.yml \
|
||||
release-assets/latest-mac-x64.yml
|
||||
rm -f release-assets/latest-mac-x64.yml
|
||||
|
||||
- name: Publish release
|
||||
if: needs.preflight.outputs.previous_tag != ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: ${{ needs.preflight.outputs.release_name }}
|
||||
generate_release_notes: true
|
||||
previous_tag: ${{ needs.preflight.outputs.previous_tag }}
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
files: |
|
||||
release-assets/*.dmg
|
||||
release-assets/*.zip
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
- name: Publish first release
|
||||
if: needs.preflight.outputs.previous_tag == ''
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.preflight.outputs.tag }}
|
||||
target_commitish: ${{ needs.preflight.outputs.ref }}
|
||||
name: ${{ needs.preflight.outputs.release_name }}
|
||||
name: T3 Code v${{ needs.preflight.outputs.version }}
|
||||
generate_release_notes: true
|
||||
prerelease: ${{ needs.preflight.outputs.is_prerelease }}
|
||||
make_latest: ${{ needs.preflight.outputs.make_latest }}
|
||||
@@ -429,14 +304,13 @@ jobs:
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: needs.preflight.outputs.release_channel == 'stable'
|
||||
needs: [preflight, release]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
@@ -475,9 +349,6 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
|
||||
+1
-2
@@ -10,8 +10,7 @@
|
||||
"*.tsbuildinfo",
|
||||
"**/routeTree.gen.ts",
|
||||
"apps/web/public/mockServiceWorker.js",
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts",
|
||||
"*.icon/**"
|
||||
"apps/web/src/lib/vendor/qrcodegen.ts"
|
||||
],
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -23,7 +23,6 @@ See the full schema for more details: [`packages/contracts/src/keybindings.ts`](
|
||||
{ "key": "mod+d", "command": "terminal.split", "when": "terminalFocus" },
|
||||
{ "key": "mod+n", "command": "terminal.new", "when": "terminalFocus" },
|
||||
{ "key": "mod+w", "command": "terminal.close", "when": "terminalFocus" },
|
||||
{ "key": "mod+k", "command": "commandPalette.toggle", "when": "!terminalFocus" },
|
||||
{ "key": "mod+n", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+o", "command": "chat.new", "when": "!terminalFocus" },
|
||||
{ "key": "mod+shift+n", "command": "chat.newLocal", "when": "!terminalFocus" },
|
||||
@@ -51,7 +50,6 @@ Invalid rules are ignored. Invalid config files are ignored. Warnings are logged
|
||||
- `terminal.split`: split terminal (in focused terminal context by default)
|
||||
- `terminal.new`: create new terminal (in focused terminal context by default)
|
||||
- `terminal.close`: close/kill the focused terminal (in focused terminal context by default)
|
||||
- `commandPalette.toggle`: open or close the global command palette
|
||||
- `chat.new`: create a new chat thread preserving the active thread's branch/worktree state
|
||||
- `chat.newLocal`: create a new chat thread for the active project in a new environment (local/worktree determined by app settings (default `local`))
|
||||
- `editor.openFavorite`: open current project/worktree in the last-used editor
|
||||
|
||||
@@ -49,14 +49,6 @@ Observability guide: [docs/observability.md](./docs/observability.md)
|
||||
|
||||
## If you REALLY want to contribute still.... read this first
|
||||
|
||||
Before local development, prepare the environment and install dependencies:
|
||||
|
||||
```bash
|
||||
# Optional: only needed if you use mise for dev tool management.
|
||||
mise install
|
||||
bun install .
|
||||
```
|
||||
|
||||
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
|
||||
|
||||
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
|
||||
@@ -1,15 +1,14 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.20",
|
||||
"version": "0.0.15",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "dist-electron/main.cjs",
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
"dev": "bun run --parallel dev:bundle dev:electron",
|
||||
"dev:bundle": "tsdown --watch",
|
||||
"dev:electron": "node scripts/dev-electron.mjs",
|
||||
"dev:electron": "bun run scripts/dev-electron.mjs",
|
||||
"build": "tsdown",
|
||||
"start": "node scripts/start-electron.mjs",
|
||||
"start": "bun run scripts/start-electron.mjs",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run --passWithNoTests",
|
||||
"smoke-test": "node scripts/smoke-test.mjs"
|
||||
|
||||
@@ -17,12 +17,12 @@ if (!Number.isInteger(port) || port <= 0) {
|
||||
}
|
||||
|
||||
const requiredFiles = [
|
||||
"dist-electron/main.cjs",
|
||||
"dist-electron/preload.cjs",
|
||||
"dist-electron/main.js",
|
||||
"dist-electron/preload.js",
|
||||
"../server/dist/bin.mjs",
|
||||
];
|
||||
const watchedDirectories = [
|
||||
{ directory: "dist-electron", files: new Set(["main.cjs", "preload.cjs"]) },
|
||||
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
|
||||
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
|
||||
];
|
||||
const forcedShutdownTimeoutMs = 1_500;
|
||||
@@ -69,7 +69,7 @@ function startApp() {
|
||||
|
||||
const app = spawn(
|
||||
resolveElectronPath(),
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.cjs"],
|
||||
[`--t3code-dev-root=${desktopDir}`, "dist-electron/main.js"],
|
||||
{
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -6,8 +6,8 @@ import {
|
||||
cpSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
readdirSync,
|
||||
rmSync,
|
||||
statSync,
|
||||
writeFileSync,
|
||||
@@ -19,13 +19,10 @@ import { fileURLToPath } from "node:url";
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_BUNDLE_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const LAUNCHER_VERSION = 2;
|
||||
const LAUNCHER_VERSION = 1;
|
||||
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
export const desktopDir = resolve(__dirname, "..");
|
||||
const repoRoot = resolve(desktopDir, "..", "..");
|
||||
const defaultIconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const developmentMacIconPngPath = join(repoRoot, "assets", "dev", "blueprint-macos-1024.png");
|
||||
|
||||
function setPlistString(plistPath, key, value) {
|
||||
const replaceResult = spawnSync("plutil", ["-replace", key, "-string", value, plistPath], {
|
||||
@@ -46,68 +43,6 @@ function setPlistString(plistPath, key, value) {
|
||||
throw new Error(`Failed to update plist key "${key}" at ${plistPath}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function runChecked(command, args) {
|
||||
const result = spawnSync(command, args, { encoding: "utf8" });
|
||||
if (result.status === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const details = [result.stdout, result.stderr].filter(Boolean).join("\n");
|
||||
throw new Error(`Failed to run ${command} ${args.join(" ")}: ${details}`.trim());
|
||||
}
|
||||
|
||||
function ensureDevelopmentIconIcns(runtimeDir) {
|
||||
const generatedIconPath = join(runtimeDir, "icon-dev.icns");
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
|
||||
if (!existsSync(developmentMacIconPngPath)) {
|
||||
return defaultIconPath;
|
||||
}
|
||||
|
||||
const sourceMtimeMs = statSync(developmentMacIconPngPath).mtimeMs;
|
||||
if (existsSync(generatedIconPath) && statSync(generatedIconPath).mtimeMs >= sourceMtimeMs) {
|
||||
return generatedIconPath;
|
||||
}
|
||||
|
||||
const iconsetRoot = mkdtempSync(join(runtimeDir, "dev-iconset-"));
|
||||
const iconsetDir = join(iconsetRoot, "icon.iconset");
|
||||
mkdirSync(iconsetDir, { recursive: true });
|
||||
|
||||
try {
|
||||
for (const size of [16, 32, 128, 256, 512]) {
|
||||
runChecked("sips", [
|
||||
"-z",
|
||||
String(size),
|
||||
String(size),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}.png`),
|
||||
]);
|
||||
|
||||
const retinaSize = size * 2;
|
||||
runChecked("sips", [
|
||||
"-z",
|
||||
String(retinaSize),
|
||||
String(retinaSize),
|
||||
developmentMacIconPngPath,
|
||||
"--out",
|
||||
join(iconsetDir, `icon_${size}x${size}@2x.png`),
|
||||
]);
|
||||
}
|
||||
|
||||
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
|
||||
return generatedIconPath;
|
||||
} catch (error) {
|
||||
console.warn(
|
||||
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
|
||||
error,
|
||||
);
|
||||
return defaultIconPath;
|
||||
} finally {
|
||||
rmSync(iconsetRoot, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
const infoPlistPath = join(appBundlePath, "Contents", "Info.plist");
|
||||
setPlistString(infoPlistPath, "CFBundleDisplayName", APP_DISPLAY_NAME);
|
||||
@@ -120,6 +55,40 @@ function patchMainBundleInfoPlist(appBundlePath, iconPath) {
|
||||
copyFileSync(iconPath, join(resourcesDir, "electron.icns"));
|
||||
}
|
||||
|
||||
function patchHelperBundleInfoPlists(appBundlePath) {
|
||||
const frameworksDir = join(appBundlePath, "Contents", "Frameworks");
|
||||
if (!existsSync(frameworksDir)) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (const entry of readdirSync(frameworksDir, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory() || !entry.name.endsWith(".app")) {
|
||||
continue;
|
||||
}
|
||||
if (!entry.name.startsWith("Electron Helper")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const helperPlistPath = join(frameworksDir, entry.name, "Contents", "Info.plist");
|
||||
if (!existsSync(helperPlistPath)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suffix = entry.name.replace("Electron Helper", "").replace(".app", "").trim();
|
||||
const helperName = suffix
|
||||
? `${APP_DISPLAY_NAME} Helper ${suffix}`
|
||||
: `${APP_DISPLAY_NAME} Helper`;
|
||||
const helperIdSuffix = suffix.replace(/[()]/g, "").trim().toLowerCase().replace(/\s+/g, "-");
|
||||
const helperBundleId = helperIdSuffix
|
||||
? `${APP_BUNDLE_ID}.helper.${helperIdSuffix}`
|
||||
: `${APP_BUNDLE_ID}.helper`;
|
||||
|
||||
setPlistString(helperPlistPath, "CFBundleDisplayName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleName", helperName);
|
||||
setPlistString(helperPlistPath, "CFBundleIdentifier", helperBundleId);
|
||||
}
|
||||
}
|
||||
|
||||
function readJson(path) {
|
||||
try {
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
@@ -133,7 +102,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
const runtimeDir = join(desktopDir, ".electron-runtime");
|
||||
const targetAppBundlePath = join(runtimeDir, `${APP_DISPLAY_NAME}.app`);
|
||||
const targetBinaryPath = join(targetAppBundlePath, "Contents", "MacOS", "Electron");
|
||||
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
|
||||
const iconPath = join(desktopDir, "resources", "icon.icns");
|
||||
const metadataPath = join(runtimeDir, "metadata.json");
|
||||
|
||||
mkdirSync(runtimeDir, { recursive: true });
|
||||
@@ -157,6 +126,7 @@ function buildMacLauncher(electronBinaryPath) {
|
||||
rmSync(targetAppBundlePath, { recursive: true, force: true });
|
||||
cpSync(sourceAppBundlePath, targetAppBundlePath, { recursive: true });
|
||||
patchMainBundleInfoPlist(targetAppBundlePath, iconPath);
|
||||
patchHelperBundleInfoPlists(targetAppBundlePath);
|
||||
writeFileSync(metadataPath, `${JSON.stringify(expectedMetadata, null, 2)}\n`);
|
||||
|
||||
return targetBinaryPath;
|
||||
@@ -170,11 +140,5 @@ export function resolveElectronPath() {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
// Dev launches do not need a renamed app bundle badly enough to risk breaking
|
||||
// Electron helper resource lookup on macOS.
|
||||
if (isDevelopment) {
|
||||
return electronBinaryPath;
|
||||
}
|
||||
|
||||
return buildMacLauncher(electronBinaryPath);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url";
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const desktopDir = resolve(__dirname, "..");
|
||||
const electronBin = resolve(desktopDir, "node_modules/.bin/electron");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.cjs");
|
||||
const mainJs = resolve(desktopDir, "dist-electron/main.js");
|
||||
|
||||
console.log("\nLaunching Electron smoke test...");
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
|
||||
const childEnv = { ...process.env };
|
||||
delete childEnv.ELECTRON_RUN_AS_NODE;
|
||||
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.cjs"], {
|
||||
const child = spawn(resolveElectronPath(), ["dist-electron/main.js"], {
|
||||
stdio: "inherit",
|
||||
cwd: desktopDir,
|
||||
env: childEnv,
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopAppBranding, resolveDesktopAppStageLabel } from "./appBranding.ts";
|
||||
|
||||
describe("resolveDesktopAppStageLabel", () => {
|
||||
it("uses Dev in desktop development", () => {
|
||||
expect(
|
||||
resolveDesktopAppStageLabel({
|
||||
isDevelopment: true,
|
||||
appVersion: "0.0.17-nightly.20260414.1",
|
||||
}),
|
||||
).toBe("Dev");
|
||||
});
|
||||
|
||||
it("uses Nightly for packaged nightly builds", () => {
|
||||
expect(
|
||||
resolveDesktopAppStageLabel({
|
||||
isDevelopment: false,
|
||||
appVersion: "0.0.17-nightly.20260414.1",
|
||||
}),
|
||||
).toBe("Nightly");
|
||||
});
|
||||
|
||||
it("uses Alpha for packaged stable builds", () => {
|
||||
expect(
|
||||
resolveDesktopAppStageLabel({
|
||||
isDevelopment: false,
|
||||
appVersion: "0.0.17",
|
||||
}),
|
||||
).toBe("Alpha");
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopAppBranding", () => {
|
||||
it("returns a complete desktop branding payload", () => {
|
||||
expect(
|
||||
resolveDesktopAppBranding({
|
||||
isDevelopment: false,
|
||||
appVersion: "0.0.17-nightly.20260414.1",
|
||||
}),
|
||||
).toEqual({
|
||||
baseName: "T3 Code",
|
||||
stageLabel: "Nightly",
|
||||
displayName: "T3 Code (Nightly)",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
import type { DesktopAppBranding, DesktopAppStageLabel } from "@t3tools/contracts";
|
||||
|
||||
import { isNightlyDesktopVersion } from "./updateChannels.ts";
|
||||
|
||||
const APP_BASE_NAME = "T3 Code";
|
||||
|
||||
export function resolveDesktopAppStageLabel(input: {
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
}): DesktopAppStageLabel {
|
||||
if (input.isDevelopment) {
|
||||
return "Dev";
|
||||
}
|
||||
|
||||
return isNightlyDesktopVersion(input.appVersion) ? "Nightly" : "Alpha";
|
||||
}
|
||||
|
||||
export function resolveDesktopAppBranding(input: {
|
||||
readonly isDevelopment: boolean;
|
||||
readonly appVersion: string;
|
||||
}): DesktopAppBranding {
|
||||
const stageLabel = resolveDesktopAppStageLabel(input);
|
||||
return {
|
||||
baseName: APP_BASE_NAME,
|
||||
stageLabel,
|
||||
displayName: `${APP_BASE_NAME} (${stageLabel})`,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
import { resolveDesktopBackendPort } from "./backendPort";
|
||||
|
||||
describe("resolveDesktopBackendPort", () => {
|
||||
it("returns the starting port when it is available", async () => {
|
||||
@@ -36,57 +36,6 @@ describe("resolveDesktopBackendPort", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("treats wildcard-bound ports as unavailable even when loopback probing succeeds", async () => {
|
||||
const canListenOnHost = vi.fn(async (port: number, host: string) => {
|
||||
if (port === 3773 && host === "127.0.0.1") return true;
|
||||
if (port === 3773 && host === "0.0.0.0") return false;
|
||||
return port === 3774;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0"],
|
||||
startPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3774);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3774, "127.0.0.1"],
|
||||
[3774, "0.0.0.0"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("checks overlapping hosts sequentially to avoid self-interference", async () => {
|
||||
let inFlightCount = 0;
|
||||
const canListenOnHost = vi.fn(async (_port: number, _host: string) => {
|
||||
inFlightCount += 1;
|
||||
const overlapped = inFlightCount > 1;
|
||||
await Promise.resolve();
|
||||
inFlightCount -= 1;
|
||||
return !overlapped;
|
||||
});
|
||||
|
||||
await expect(
|
||||
resolveDesktopBackendPort({
|
||||
host: "127.0.0.1",
|
||||
requiredHosts: ["0.0.0.0", "::"],
|
||||
startPort: 3773,
|
||||
maxPort: 3773,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).resolves.toBe(3773);
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[3773, "127.0.0.1"],
|
||||
[3773, "0.0.0.0"],
|
||||
[3773, "::"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("fails when the scan range is exhausted", async () => {
|
||||
const canListenOnHost = vi.fn(async () => false);
|
||||
|
||||
@@ -97,9 +46,7 @@ describe("resolveDesktopBackendPort", () => {
|
||||
maxPort: 65535,
|
||||
canListenOnHost,
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
"No desktop backend port is available on hosts 127.0.0.1 between 65534 and 65535",
|
||||
);
|
||||
).rejects.toThrow("No desktop backend port is available on 127.0.0.1 between 65534 and 65535");
|
||||
|
||||
expect(canListenOnHost.mock.calls).toEqual([
|
||||
[65534, "127.0.0.1"],
|
||||
|
||||
@@ -8,7 +8,6 @@ export interface ResolveDesktopBackendPortOptions {
|
||||
readonly host: string;
|
||||
readonly startPort?: number;
|
||||
readonly maxPort?: number;
|
||||
readonly requiredHosts?: ReadonlyArray<string>;
|
||||
readonly canListenOnHost?: (port: number, host: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
@@ -22,37 +21,10 @@ const defaultCanListenOnHost = async (port: number, host: string): Promise<boole
|
||||
const isValidPort = (port: number): boolean =>
|
||||
Number.isInteger(port) && port >= 1 && port <= MAX_TCP_PORT;
|
||||
|
||||
const normalizeHosts = (
|
||||
host: string,
|
||||
requiredHosts: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> =>
|
||||
Array.from(
|
||||
new Set(
|
||||
[host, ...requiredHosts]
|
||||
.map((candidate) => candidate.trim())
|
||||
.filter((candidate) => candidate.length > 0),
|
||||
),
|
||||
);
|
||||
|
||||
async function canListenOnAllHosts(
|
||||
port: number,
|
||||
hosts: ReadonlyArray<string>,
|
||||
canListenOnHost: (port: number, host: string) => Promise<boolean>,
|
||||
): Promise<boolean> {
|
||||
for (const candidateHost of hosts) {
|
||||
if (!(await canListenOnHost(port, candidateHost))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function resolveDesktopBackendPort({
|
||||
host,
|
||||
startPort = DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
maxPort = MAX_TCP_PORT,
|
||||
requiredHosts = [],
|
||||
canListenOnHost = defaultCanListenOnHost,
|
||||
}: ResolveDesktopBackendPortOptions): Promise<number> {
|
||||
if (!isValidPort(startPort)) {
|
||||
@@ -67,17 +39,15 @@ export async function resolveDesktopBackendPort({
|
||||
throw new Error(`Desktop backend max port ${maxPort} is below start port ${startPort}`);
|
||||
}
|
||||
|
||||
const hostsToCheck = normalizeHosts(host, requiredHosts);
|
||||
|
||||
// Keep desktop startup predictable across app restarts by probing upward from
|
||||
// the same preferred port instead of picking a fresh ephemeral port.
|
||||
for (let port = startPort; port <= maxPort; port += 1) {
|
||||
if (await canListenOnAllHosts(port, hostsToCheck, canListenOnHost)) {
|
||||
if (await canListenOnHost(port, host)) {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
`No desktop backend port is available on hosts ${hostsToCheck.join(", ")} between ${startPort} and ${maxPort}`,
|
||||
`No desktop backend port is available on ${host} between ${startPort} and ${maxPort}`,
|
||||
);
|
||||
}
|
||||
@@ -4,10 +4,10 @@ import {
|
||||
BackendReadinessAbortedError,
|
||||
isBackendReadinessAborted,
|
||||
waitForHttpReady,
|
||||
} from "./backendReadiness.ts";
|
||||
} from "./backendReadiness";
|
||||
|
||||
describe("waitForHttpReady", () => {
|
||||
it("returns once the backend serves the requested readiness path", async () => {
|
||||
it("returns once the backend reports a successful session endpoint", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
@@ -20,11 +20,6 @@ describe("waitForHttpReady", () => {
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("retries after a readiness request stalls past the per-request timeout", async () => {
|
||||
@@ -85,30 +80,4 @@ describe("waitForHttpReady", () => {
|
||||
expect(isBackendReadinessAborted(new BackendReadinessAbortedError())).toBe(true);
|
||||
expect(isBackendReadinessAborted(new Error("nope"))).toBe(false);
|
||||
});
|
||||
|
||||
it("supports custom readiness predicates", async () => {
|
||||
const fetchImpl = vi
|
||||
.fn<typeof fetch>()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 200 }))
|
||||
.mockResolvedValueOnce(new Response(null, { status: 204 }));
|
||||
|
||||
await waitForHttpReady("http://127.0.0.1:3773", {
|
||||
fetchImpl,
|
||||
timeoutMs: 1_000,
|
||||
intervalMs: 0,
|
||||
path: "/api/healthz",
|
||||
isReady: (response) => response.status === 204,
|
||||
});
|
||||
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
expect(fetchImpl).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://127.0.0.1:3773/api/healthz",
|
||||
expect.objectContaining({ redirect: "manual" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -4,11 +4,9 @@ export interface WaitForHttpReadyOptions {
|
||||
readonly requestTimeoutMs?: number;
|
||||
readonly fetchImpl?: typeof fetch;
|
||||
readonly signal?: AbortSignal;
|
||||
readonly path?: string;
|
||||
readonly isReady?: (response: Response) => boolean;
|
||||
}
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_TIMEOUT_MS = 10_000;
|
||||
const DEFAULT_INTERVAL_MS = 100;
|
||||
const DEFAULT_REQUEST_TIMEOUT_MS = 1_000;
|
||||
|
||||
@@ -59,8 +57,6 @@ export async function waitForHttpReady(
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
|
||||
const requestTimeoutMs = options?.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
const readinessPath = options?.path ?? "/";
|
||||
const isReady = options?.isReady ?? ((response: Response) => response.ok);
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
|
||||
for (;;) {
|
||||
@@ -78,11 +74,11 @@ export async function waitForHttpReady(
|
||||
signal?.addEventListener("abort", abortRequest, { once: true });
|
||||
|
||||
try {
|
||||
const response = await fetchImpl(new URL(readinessPath, baseUrl).toString(), {
|
||||
const response = await fetchImpl(`${baseUrl}/api/auth/session`, {
|
||||
redirect: "manual",
|
||||
signal: requestController.signal,
|
||||
});
|
||||
if (isReady(response)) {
|
||||
if (response.ok) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
type DesktopSecretStorage,
|
||||
} from "./clientPersistence.ts";
|
||||
} from "./clientPersistence";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
@@ -52,17 +52,13 @@ const clientSettings: ClientSettings = {
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
diffWordWrap: true,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
},
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
environmentId: EnvironmentId.makeUnsafe("environment-1"),
|
||||
label: "Remote environment",
|
||||
httpBaseUrl: "https://remote.example.com/",
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
type PersistedSavedEnvironmentRecord,
|
||||
} from "@t3tools/contracts";
|
||||
import type { ClientSettings, PersistedSavedEnvironmentRecord } from "@t3tools/contracts";
|
||||
import { Predicate } from "effect";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
interface ClientSettingsDocument {
|
||||
readonly settings: ClientSettings;
|
||||
@@ -88,15 +83,7 @@ function toPersistedSavedEnvironmentRecord(
|
||||
}
|
||||
|
||||
export function readClientSettings(settingsPath: string): ClientSettings | null {
|
||||
const raw = readJsonFile<ClientSettingsDocument>(settingsPath)?.settings;
|
||||
if (!raw) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Schema.decodeUnknownSync(ClientSettingsSchema)(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return readJsonFile<ClientSettingsDocument>(settingsPath)?.settings ?? null;
|
||||
}
|
||||
|
||||
export function writeClientSettings(settingsPath: string, settings: ClientSettings): void {
|
||||
|
||||
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
|
||||
describe("showDesktopConfirmDialog", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -7,11 +7,9 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings.ts";
|
||||
} from "./desktopSettings";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
@@ -29,15 +27,7 @@ function makeSettingsPath() {
|
||||
|
||||
describe("desktopSettings", () => {
|
||||
it("returns defaults when no settings file exists", () => {
|
||||
expect(readDesktopSettings(makeSettingsPath(), "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("defaults packaged nightly builds to the nightly update channel", () => {
|
||||
expect(resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("persists and reloads the configured server exposure mode", () => {
|
||||
@@ -45,14 +35,10 @@ describe("desktopSettings", () => {
|
||||
|
||||
writeDesktopSettings(settingsPath, {
|
||||
serverExposureMode: "network-accessible",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||
expect(readDesktopSettings(settingsPath)).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -61,32 +47,11 @@ describe("desktopSettings", () => {
|
||||
setDesktopServerExposurePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"network-accessible",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists the requested nightly update channel", () => {
|
||||
expect(
|
||||
setDesktopUpdateChannelPreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"nightly",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -94,54 +59,6 @@ describe("desktopSettings", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, "{not-json", "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("falls back to the nightly channel for legacy nightly settings without an update track", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(settingsPath, JSON.stringify({ serverExposureMode: "local-only" }), "utf8");
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("migrates legacy implicit stable settings to nightly when running a nightly build", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves an explicit stable choice on nightly builds", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17-nightly.20260415.1")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
});
|
||||
@@ -1,28 +1,15 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as Path from "node:path";
|
||||
import type { DesktopServerExposureMode, DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
import { resolveDefaultDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
|
||||
export interface DesktopSettings {
|
||||
readonly serverExposureMode: DesktopServerExposureMode;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
serverExposureMode: "local-only",
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
};
|
||||
|
||||
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
|
||||
return {
|
||||
...DEFAULT_DESKTOP_SETTINGS,
|
||||
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
|
||||
};
|
||||
}
|
||||
|
||||
export function setDesktopServerExposurePreference(
|
||||
settings: DesktopSettings,
|
||||
requestedMode: DesktopServerExposureMode,
|
||||
@@ -35,51 +22,23 @@ export function setDesktopServerExposurePreference(
|
||||
};
|
||||
}
|
||||
|
||||
export function setDesktopUpdateChannelPreference(
|
||||
settings: DesktopSettings,
|
||||
requestedChannel: DesktopUpdateChannel,
|
||||
): DesktopSettings {
|
||||
return {
|
||||
...settings,
|
||||
updateChannel: requestedChannel,
|
||||
updateChannelConfiguredByUser: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function readDesktopSettings(settingsPath: string, appVersion: string): DesktopSettings {
|
||||
const defaultSettings = resolveDefaultDesktopSettings(appVersion);
|
||||
|
||||
export function readDesktopSettings(settingsPath: string): DesktopSettings {
|
||||
try {
|
||||
if (!FS.existsSync(settingsPath)) {
|
||||
return defaultSettings;
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
}
|
||||
|
||||
const raw = FS.readFileSync(settingsPath, "utf8");
|
||||
const parsed = JSON.parse(raw) as {
|
||||
readonly serverExposureMode?: unknown;
|
||||
readonly updateChannel?: unknown;
|
||||
readonly updateChannelConfiguredByUser?: unknown;
|
||||
};
|
||||
const parsedUpdateChannel =
|
||||
parsed.updateChannel === "nightly" || parsed.updateChannel === "latest"
|
||||
? parsed.updateChannel
|
||||
: null;
|
||||
const isLegacySettings = parsed.updateChannelConfiguredByUser === undefined;
|
||||
const updateChannelConfiguredByUser =
|
||||
parsed.updateChannelConfiguredByUser === true ||
|
||||
(isLegacySettings && parsedUpdateChannel === "nightly");
|
||||
|
||||
return {
|
||||
serverExposureMode:
|
||||
parsed.serverExposureMode === "network-accessible" ? "network-accessible" : "local-only",
|
||||
updateChannel:
|
||||
updateChannelConfiguredByUser && parsedUpdateChannel !== null
|
||||
? parsedUpdateChannel
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
};
|
||||
} catch {
|
||||
return defaultSettings;
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+96
-406
@@ -7,7 +7,6 @@ import * as Path from "node:path";
|
||||
import {
|
||||
app,
|
||||
BrowserWindow,
|
||||
type BrowserWindowConstructorOptions,
|
||||
clipboard,
|
||||
dialog,
|
||||
ipcMain,
|
||||
@@ -18,14 +17,12 @@ import {
|
||||
safeStorage,
|
||||
shell,
|
||||
} from "electron";
|
||||
import type { MenuItemConstructorOptions, OpenDialogOptions } from "electron";
|
||||
import type { MenuItemConstructorOptions } from "electron";
|
||||
import type {
|
||||
ClientSettings,
|
||||
DesktopTheme,
|
||||
DesktopAppBranding,
|
||||
DesktopServerExposureMode,
|
||||
DesktopServerExposureState,
|
||||
DesktopUpdateChannel,
|
||||
PersistedSavedEnvironmentRecord,
|
||||
DesktopUpdateActionResult,
|
||||
DesktopUpdateCheckResult,
|
||||
@@ -36,14 +33,13 @@ import { autoUpdater } from "electron-updater";
|
||||
import type { ContextMenuItem } from "@t3tools/contracts";
|
||||
import { RotatingFileSink } from "@t3tools/shared/logging";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort.ts";
|
||||
import { DEFAULT_DESKTOP_BACKEND_PORT, resolveDesktopBackendPort } from "./backendPort";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings.ts";
|
||||
} from "./desktopSettings";
|
||||
import {
|
||||
readClientSettings,
|
||||
readSavedEnvironmentRegistry,
|
||||
@@ -52,14 +48,12 @@ import {
|
||||
writeClientSettings,
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
} from "./clientPersistence.ts";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness.ts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure.ts";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState.ts";
|
||||
import { doesVersionMatchDesktopUpdateChannel } from "./updateChannels.ts";
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
} from "./clientPersistence";
|
||||
import { isBackendReadinessAborted, waitForHttpReady } from "./backendReadiness";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
import { resolveDesktopServerExposure } from "./serverExposure";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
|
||||
import {
|
||||
createInitialDesktopUpdateState,
|
||||
reduceDesktopUpdateStateOnCheckFailure,
|
||||
@@ -71,9 +65,8 @@ import {
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine.ts";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
import { resolveDesktopAppBranding } from "./appBranding.ts";
|
||||
} from "./updateMachine";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
|
||||
syncShellEnvironment();
|
||||
|
||||
@@ -85,11 +78,9 @@ 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_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
@@ -108,12 +99,8 @@ const SAVED_ENVIRONMENT_REGISTRY_PATH = Path.join(STATE_DIR, "saved-environments
|
||||
const DESKTOP_SCHEME = "t3";
|
||||
const ROOT_DIR = Path.resolve(__dirname, "../../..");
|
||||
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
|
||||
const desktopAppBranding: DesktopAppBranding = resolveDesktopAppBranding({
|
||||
isDevelopment,
|
||||
appVersion: app.getVersion(),
|
||||
});
|
||||
const APP_DISPLAY_NAME = desktopAppBranding.displayName;
|
||||
const APP_USER_MODEL_ID = isDevelopment ? "com.t3tools.t3code.dev" : "com.t3tools.t3code";
|
||||
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
|
||||
const APP_USER_MODEL_ID = "com.t3tools.t3code";
|
||||
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
|
||||
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
|
||||
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
|
||||
@@ -127,72 +114,9 @@ const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
|
||||
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
|
||||
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
|
||||
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
|
||||
|
||||
function resolvePickFolderDefaultPath(rawOptions: unknown): string | undefined {
|
||||
if (typeof rawOptions !== "object" || rawOptions === null) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { initialPath } = rawOptions as { initialPath?: unknown };
|
||||
if (typeof initialPath !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const trimmedPath = initialPath.trim();
|
||||
if (trimmedPath.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (trimmedPath === "~") {
|
||||
return OS.homedir();
|
||||
}
|
||||
|
||||
if (trimmedPath.startsWith("~/") || trimmedPath.startsWith("~\\")) {
|
||||
return Path.join(OS.homedir(), trimmedPath.slice(2));
|
||||
}
|
||||
|
||||
return Path.resolve(trimmedPath);
|
||||
}
|
||||
const DESKTOP_UPDATE_CHANNEL = "latest";
|
||||
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_REQUIRED_PORT_PROBE_HOSTS = ["0.0.0.0", "::"] as const;
|
||||
const TITLEBAR_HEIGHT = 40;
|
||||
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
|
||||
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
|
||||
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
|
||||
|
||||
function normalizeContextMenuItems(source: readonly ContextMenuItem[]): ContextMenuItem[] {
|
||||
const normalizedItems: ContextMenuItem[] = [];
|
||||
|
||||
for (const sourceItem of source) {
|
||||
if (typeof sourceItem.id !== "string" || typeof sourceItem.label !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const normalizedItem: ContextMenuItem = {
|
||||
id: sourceItem.id,
|
||||
label: sourceItem.label,
|
||||
destructive: sourceItem.destructive === true,
|
||||
disabled: sourceItem.disabled === true,
|
||||
};
|
||||
|
||||
if (sourceItem.children) {
|
||||
const normalizedChildren = normalizeContextMenuItems(sourceItem.children);
|
||||
if (normalizedChildren.length === 0) {
|
||||
continue;
|
||||
}
|
||||
normalizedItem.children = normalizedChildren;
|
||||
}
|
||||
|
||||
normalizedItems.push(normalizedItem);
|
||||
}
|
||||
|
||||
return normalizedItems;
|
||||
}
|
||||
|
||||
type WindowTitleBarOptions = Pick<
|
||||
BrowserWindowConstructorOptions,
|
||||
"titleBarOverlay" | "titleBarStyle" | "trafficLightPosition"
|
||||
>;
|
||||
|
||||
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
|
||||
type LinuxDesktopNamedApp = Electron.App & {
|
||||
@@ -209,8 +133,6 @@ let backendWsUrl = "";
|
||||
let backendEndpointUrl: string | null = null;
|
||||
let backendAdvertisedHost: string | null = null;
|
||||
let backendReadinessAbortController: AbortController | null = null;
|
||||
let backendInitialWindowOpenInFlight: Promise<void> | null = null;
|
||||
let backendListeningDetector: ServerListeningDetector | null = null;
|
||||
let restartAttempt = 0;
|
||||
let restartTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let isQuitting = false;
|
||||
@@ -220,7 +142,7 @@ let desktopLogSink: RotatingFileSink | null = null;
|
||||
let backendLogSink: RotatingFileSink | null = null;
|
||||
let restoreStdIoCapture: (() => void) | null = null;
|
||||
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
|
||||
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH, app.getVersion());
|
||||
let desktopSettings = readDesktopSettings(DESKTOP_SETTINGS_PATH);
|
||||
let desktopServerExposureMode: DesktopServerExposureMode = desktopSettings.serverExposureMode;
|
||||
|
||||
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
|
||||
@@ -231,11 +153,7 @@ const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
|
||||
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
|
||||
});
|
||||
const initialUpdateState = (): DesktopUpdateState =>
|
||||
createInitialDesktopUpdateState(
|
||||
app.getVersion(),
|
||||
desktopRuntimeInfo,
|
||||
desktopSettings.updateChannel,
|
||||
);
|
||||
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
|
||||
|
||||
function logTimestamp(): string {
|
||||
return new Date().toISOString();
|
||||
@@ -433,17 +351,13 @@ function getSafeTheme(rawTheme: unknown): DesktopTheme | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
async function waitForBackendHttpReady(
|
||||
baseUrl: string,
|
||||
options?: Parameters<typeof waitForHttpReady>[1],
|
||||
): Promise<void> {
|
||||
async function waitForBackendHttpReady(baseUrl: string): Promise<void> {
|
||||
cancelBackendReadinessWait();
|
||||
const controller = new AbortController();
|
||||
backendReadinessAbortController = controller;
|
||||
|
||||
try {
|
||||
await waitForHttpReady(baseUrl, {
|
||||
...options,
|
||||
signal: controller.signal,
|
||||
});
|
||||
} finally {
|
||||
@@ -458,88 +372,6 @@ function cancelBackendReadinessWait(): void {
|
||||
backendReadinessAbortController = null;
|
||||
}
|
||||
|
||||
async function waitForBackendWindowReady(baseUrl: string): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = waitForBackendHttpReady(baseUrl, {
|
||||
timeoutMs: 60_000,
|
||||
});
|
||||
const listeningPromise = backendListeningDetector?.promise;
|
||||
|
||||
if (!listeningPromise) {
|
||||
await httpReadyPromise;
|
||||
return "http";
|
||||
}
|
||||
|
||||
return await new Promise<"listening" | "http">((resolve, reject) => {
|
||||
let settled = false;
|
||||
|
||||
const settleResolve = (source: "listening" | "http") => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
if (source === "listening") {
|
||||
cancelBackendReadinessWait();
|
||||
}
|
||||
resolve(source);
|
||||
};
|
||||
|
||||
const settleReject = (error: unknown) => {
|
||||
if (settled) {
|
||||
return;
|
||||
}
|
||||
settled = true;
|
||||
reject(error);
|
||||
};
|
||||
|
||||
listeningPromise.then(
|
||||
() => settleResolve("listening"),
|
||||
(error) => settleReject(error),
|
||||
);
|
||||
httpReadyPromise.then(
|
||||
() => settleResolve("http"),
|
||||
(error) => {
|
||||
if (settled && isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
settleReject(error);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
function ensureInitialBackendWindowOpen(): void {
|
||||
const existingWindow = mainWindow ?? BrowserWindow.getAllWindows()[0] ?? null;
|
||||
if (isDevelopment || existingWindow !== null || backendInitialWindowOpenInFlight !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextOpen = waitForBackendWindowReady(backendHttpUrl)
|
||||
.then((source) => {
|
||||
writeDesktopLogHeader(`bootstrap backend ready source=${source}`);
|
||||
if (mainWindow ?? BrowserWindow.getAllWindows()[0]) {
|
||||
return;
|
||||
}
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
})
|
||||
.catch((error) => {
|
||||
if (isBackendReadinessAborted(error)) {
|
||||
return;
|
||||
}
|
||||
writeDesktopLogHeader(
|
||||
`bootstrap backend readiness warning message=${formatErrorMessage(error)}`,
|
||||
);
|
||||
console.warn("[desktop] backend readiness check timed out during packaged bootstrap", error);
|
||||
})
|
||||
.finally(() => {
|
||||
if (backendInitialWindowOpenInFlight === nextOpen) {
|
||||
backendInitialWindowOpenInFlight = null;
|
||||
}
|
||||
});
|
||||
|
||||
backendInitialWindowOpenInFlight = nextOpen;
|
||||
}
|
||||
|
||||
function writeDesktopStreamChunk(
|
||||
streamName: "stdout" | "stderr",
|
||||
chunk: unknown,
|
||||
@@ -617,16 +449,14 @@ function initializePackagedLogging(): void {
|
||||
}
|
||||
|
||||
function captureBackendOutput(child: ChildProcess.ChildProcess): void {
|
||||
const attachStream = (stream: NodeJS.ReadableStream | null | undefined): void => {
|
||||
stream?.on("data", (chunk: unknown) => {
|
||||
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), "utf8");
|
||||
backendLogSink?.write(buffer);
|
||||
backendListeningDetector?.push(buffer);
|
||||
});
|
||||
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);
|
||||
};
|
||||
|
||||
attachStream(child.stdout);
|
||||
attachStream(child.stderr);
|
||||
child.stdout?.on("data", writeChunk);
|
||||
child.stderr?.on("data", writeChunk);
|
||||
}
|
||||
|
||||
initializePackagedLogging();
|
||||
@@ -1043,18 +873,6 @@ function resolveResourcePath(fileName: string): string | null {
|
||||
}
|
||||
|
||||
function resolveIconPath(ext: "ico" | "icns" | "png"): string | null {
|
||||
if (isDevelopment && process.platform === "darwin" && ext === "png") {
|
||||
const developmentDockIconPath = Path.join(
|
||||
ROOT_DIR,
|
||||
"assets",
|
||||
"dev",
|
||||
"blueprint-macos-1024.png",
|
||||
);
|
||||
if (FS.existsSync(developmentDockIconPath)) {
|
||||
return developmentDockIconPath;
|
||||
}
|
||||
}
|
||||
|
||||
return resolveResourcePath(`icon.${ext}`);
|
||||
}
|
||||
|
||||
@@ -1154,26 +972,6 @@ function setUpdateState(patch: Partial<DesktopUpdateState>): void {
|
||||
emitUpdateState();
|
||||
}
|
||||
|
||||
function createBaseUpdateState(
|
||||
channel: DesktopUpdateChannel,
|
||||
enabled: boolean,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo, channel),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
};
|
||||
}
|
||||
|
||||
function applyAutoUpdaterChannel(channel: DesktopUpdateChannel): void {
|
||||
autoUpdater.channel = channel;
|
||||
autoUpdater.allowPrerelease = channel === "nightly";
|
||||
autoUpdater.allowDowngrade = channel === "nightly";
|
||||
console.info(
|
||||
`[desktop-updater] Using update channel '${channel}' (allowPrerelease=${channel === "nightly"}, allowDowngrade=${channel === "nightly"}).`,
|
||||
);
|
||||
}
|
||||
|
||||
function shouldEnableAutoUpdates(): boolean {
|
||||
const hasUpdateFeedConfig =
|
||||
readAppUpdateYml() !== null || Boolean(process.env.T3CODE_DESKTOP_MOCK_UPDATES);
|
||||
@@ -1293,7 +1091,11 @@ function configureAutoUpdater(): void {
|
||||
}
|
||||
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState(createBaseUpdateState(desktopSettings.updateChannel, enabled));
|
||||
setUpdateState({
|
||||
...createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo),
|
||||
enabled,
|
||||
status: enabled ? "idle" : "disabled",
|
||||
});
|
||||
if (!enabled) {
|
||||
return;
|
||||
}
|
||||
@@ -1301,7 +1103,10 @@ function configureAutoUpdater(): void {
|
||||
|
||||
autoUpdater.autoDownload = false;
|
||||
autoUpdater.autoInstallOnAppQuit = false;
|
||||
applyAutoUpdaterChannel(desktopSettings.updateChannel);
|
||||
// Keep alpha branding, but force all installs onto the stable update track.
|
||||
autoUpdater.channel = DESKTOP_UPDATE_CHANNEL;
|
||||
autoUpdater.allowPrerelease = DESKTOP_UPDATE_ALLOW_PRERELEASE;
|
||||
autoUpdater.allowDowngrade = false;
|
||||
autoUpdater.disableDifferentialDownload = isArm64HostRunningIntelBuild(desktopRuntimeInfo);
|
||||
let lastLoggedDownloadMilestone = -1;
|
||||
|
||||
@@ -1315,15 +1120,6 @@ function configureAutoUpdater(): void {
|
||||
console.info("[desktop-updater] Looking for updates...");
|
||||
});
|
||||
autoUpdater.on("update-available", (info) => {
|
||||
if (!doesVersionMatchDesktopUpdateChannel(info.version, updateState.channel)) {
|
||||
console.info(
|
||||
`[desktop-updater] Ignoring ${info.version} because it does not match the selected '${updateState.channel}' channel.`,
|
||||
);
|
||||
setUpdateState(reduceDesktopUpdateStateOnNoUpdate(updateState, new Date().toISOString()));
|
||||
lastLoggedDownloadMilestone = -1;
|
||||
return;
|
||||
}
|
||||
|
||||
setUpdateState(
|
||||
reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
updateState,
|
||||
@@ -1415,7 +1211,7 @@ function startBackend(): void {
|
||||
return;
|
||||
}
|
||||
|
||||
const captureBackendLogs = !isDevelopment;
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
cwd: resolveBackendCwd(),
|
||||
// In Electron main, process.execPath points to the Electron binary.
|
||||
@@ -1452,8 +1248,6 @@ function startBackend(): void {
|
||||
scheduleBackendRestart("missing desktop bootstrap pipe");
|
||||
return;
|
||||
}
|
||||
const listeningDetector = new ServerListeningDetector();
|
||||
backendListeningDetector = listeningDetector;
|
||||
backendProcess = child;
|
||||
let backendSessionClosed = false;
|
||||
const closeBackendSession = (details: string) => {
|
||||
@@ -1472,10 +1266,6 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("error", (error) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(error);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1488,14 +1278,6 @@ function startBackend(): void {
|
||||
});
|
||||
|
||||
child.on("exit", (code, signal) => {
|
||||
if (backendListeningDetector === listeningDetector) {
|
||||
listeningDetector.fail(
|
||||
new Error(
|
||||
`backend exited before logging readiness (code=${code ?? "null"} signal=${signal ?? "null"})`,
|
||||
),
|
||||
);
|
||||
backendListeningDetector = null;
|
||||
}
|
||||
const wasExpected = expectedBackendExitChildren.has(child);
|
||||
if (backendProcess === child) {
|
||||
backendProcess = null;
|
||||
@@ -1507,13 +1289,10 @@ function startBackend(): void {
|
||||
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
|
||||
scheduleBackendRestart(reason);
|
||||
});
|
||||
|
||||
ensureInitialBackendWindowOpen();
|
||||
}
|
||||
|
||||
function stopBackend(): void {
|
||||
cancelBackendReadinessWait();
|
||||
backendListeningDetector = null;
|
||||
if (restartTimer) {
|
||||
clearTimeout(restartTimer);
|
||||
restartTimer = null;
|
||||
@@ -1588,11 +1367,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
|
||||
}
|
||||
|
||||
function registerIpcHandlers(): void {
|
||||
ipcMain.removeAllListeners(GET_APP_BRANDING_CHANNEL);
|
||||
ipcMain.on(GET_APP_BRANDING_CHANNEL, (event) => {
|
||||
event.returnValue = desktopAppBranding;
|
||||
});
|
||||
|
||||
ipcMain.removeAllListeners(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
ipcMain.on(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL, (event) => {
|
||||
event.returnValue = {
|
||||
@@ -1706,16 +1480,15 @@ function registerIpcHandlers(): void {
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async (_event, rawOptions: unknown) => {
|
||||
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
|
||||
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
|
||||
const defaultPath = resolvePickFolderDefaultPath(rawOptions);
|
||||
const openDialogOptions: OpenDialogOptions = {
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
...(defaultPath ? { defaultPath } : {}),
|
||||
};
|
||||
const result = owner
|
||||
? await dialog.showOpenDialog(owner, openDialogOptions)
|
||||
: await dialog.showOpenDialog(openDialogOptions);
|
||||
? await dialog.showOpenDialog(owner, {
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
})
|
||||
: await dialog.showOpenDialog({
|
||||
properties: ["openDirectory", "createDirectory"],
|
||||
});
|
||||
if (result.canceled) return null;
|
||||
return result.filePaths[0] ?? null;
|
||||
});
|
||||
@@ -1744,7 +1517,14 @@ function registerIpcHandlers(): void {
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
async (_event, items: ContextMenuItem[], position?: { x: number; y: number }) => {
|
||||
const normalizedItems = normalizeContextMenuItems(items);
|
||||
const normalizedItems = items
|
||||
.filter((item) => typeof item.id === "string" && typeof item.label === "string")
|
||||
.map((item) => ({
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
destructive: item.destructive === true,
|
||||
disabled: item.disabled === true,
|
||||
}));
|
||||
if (normalizedItems.length === 0) {
|
||||
return null;
|
||||
}
|
||||
@@ -1765,37 +1545,28 @@ function registerIpcHandlers(): void {
|
||||
if (!window) return null;
|
||||
|
||||
return new Promise<string | null>((resolve) => {
|
||||
const buildTemplate = (
|
||||
entries: readonly ContextMenuItem[],
|
||||
): MenuItemConstructorOptions[] => {
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
for (const item of entries) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
};
|
||||
if (item.children && item.children.length > 0) {
|
||||
itemOption.submenu = buildTemplate(item.children);
|
||||
} else {
|
||||
itemOption.click = () => resolve(item.id);
|
||||
}
|
||||
if (item.destructive && (!item.children || item.children.length === 0)) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (destructiveIcon) {
|
||||
itemOption.icon = destructiveIcon;
|
||||
}
|
||||
}
|
||||
template.push(itemOption);
|
||||
const template: MenuItemConstructorOptions[] = [];
|
||||
let hasInsertedDestructiveSeparator = false;
|
||||
for (const item of normalizedItems) {
|
||||
if (item.destructive && !hasInsertedDestructiveSeparator && template.length > 0) {
|
||||
template.push({ type: "separator" });
|
||||
hasInsertedDestructiveSeparator = true;
|
||||
}
|
||||
return template;
|
||||
};
|
||||
const itemOption: MenuItemConstructorOptions = {
|
||||
label: item.label,
|
||||
enabled: !item.disabled,
|
||||
click: () => resolve(item.id),
|
||||
};
|
||||
if (item.destructive) {
|
||||
const destructiveIcon = getDestructiveMenuIcon();
|
||||
if (destructiveIcon) {
|
||||
itemOption.icon = destructiveIcon;
|
||||
}
|
||||
}
|
||||
template.push(itemOption);
|
||||
}
|
||||
|
||||
const menu = Menu.buildFromTemplate(buildTemplate(normalizedItems));
|
||||
const menu = Menu.buildFromTemplate(template);
|
||||
menu.popup({
|
||||
window,
|
||||
...popupPosition,
|
||||
@@ -1823,43 +1594,6 @@ function registerIpcHandlers(): void {
|
||||
ipcMain.removeHandler(UPDATE_GET_STATE_CHANNEL);
|
||||
ipcMain.handle(UPDATE_GET_STATE_CHANNEL, async () => updateState);
|
||||
|
||||
ipcMain.removeHandler(UPDATE_SET_CHANNEL_CHANNEL);
|
||||
ipcMain.handle(UPDATE_SET_CHANNEL_CHANNEL, async (_event, rawChannel: unknown) => {
|
||||
if (rawChannel !== "latest" && rawChannel !== "nightly") {
|
||||
throw new Error("Invalid desktop update channel input.");
|
||||
}
|
||||
if (updateCheckInFlight || updateDownloadInFlight || updateInstallInFlight) {
|
||||
throw new Error("Cannot change update tracks while an update action is in progress.");
|
||||
}
|
||||
|
||||
const nextChannel = rawChannel as DesktopUpdateChannel;
|
||||
|
||||
desktopSettings = setDesktopUpdateChannelPreference(desktopSettings, nextChannel);
|
||||
writeDesktopSettings(DESKTOP_SETTINGS_PATH, desktopSettings);
|
||||
|
||||
if (nextChannel === updateState.channel) {
|
||||
return updateState;
|
||||
}
|
||||
|
||||
const enabled = shouldEnableAutoUpdates();
|
||||
setUpdateState(createBaseUpdateState(nextChannel, enabled));
|
||||
|
||||
if (!enabled || !updaterConfigured) {
|
||||
return updateState;
|
||||
}
|
||||
|
||||
applyAutoUpdaterChannel(nextChannel);
|
||||
const allowDowngrade = autoUpdater.allowDowngrade;
|
||||
// An explicit channel switch should allow the immediate nightly->stable rollback path.
|
||||
autoUpdater.allowDowngrade = true;
|
||||
try {
|
||||
await checkForUpdates("channel-change");
|
||||
} finally {
|
||||
autoUpdater.allowDowngrade = allowDowngrade;
|
||||
}
|
||||
return updateState;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(UPDATE_DOWNLOAD_CHANNEL);
|
||||
ipcMain.handle(UPDATE_DOWNLOAD_CHANNEL, async () => {
|
||||
const result = await downloadAvailableUpdate();
|
||||
@@ -1914,60 +1648,21 @@ function getInitialWindowBackgroundColor(): string {
|
||||
return nativeTheme.shouldUseDarkColors ? "#0a0a0a" : "#ffffff";
|
||||
}
|
||||
|
||||
function getWindowTitleBarOptions(): WindowTitleBarOptions {
|
||||
if (process.platform === "darwin") {
|
||||
return {
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
titleBarStyle: "hidden",
|
||||
titleBarOverlay: {
|
||||
color: TITLEBAR_COLOR,
|
||||
height: TITLEBAR_HEIGHT,
|
||||
symbolColor: nativeTheme.shouldUseDarkColors
|
||||
? TITLEBAR_DARK_SYMBOL_COLOR
|
||||
: TITLEBAR_LIGHT_SYMBOL_COLOR,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function syncWindowAppearance(window: BrowserWindow): void {
|
||||
if (window.isDestroyed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.setBackgroundColor(getInitialWindowBackgroundColor());
|
||||
const { titleBarOverlay } = getWindowTitleBarOptions();
|
||||
if (typeof titleBarOverlay === "object") {
|
||||
window.setTitleBarOverlay(titleBarOverlay);
|
||||
}
|
||||
}
|
||||
|
||||
function syncAllWindowAppearance(): void {
|
||||
for (const window of BrowserWindow.getAllWindows()) {
|
||||
syncWindowAppearance(window);
|
||||
}
|
||||
}
|
||||
|
||||
nativeTheme.on("updated", syncAllWindowAppearance);
|
||||
|
||||
function createWindow(): BrowserWindow {
|
||||
const window = new BrowserWindow({
|
||||
width: 1100,
|
||||
height: 780,
|
||||
minWidth: 840,
|
||||
minHeight: 620,
|
||||
show: false,
|
||||
show: isDevelopment,
|
||||
autoHideMenuBar: true,
|
||||
backgroundColor: getInitialWindowBackgroundColor(),
|
||||
...getIconOption(),
|
||||
title: APP_DISPLAY_NAME,
|
||||
...getWindowTitleBarOptions(),
|
||||
titleBarStyle: "hiddenInset",
|
||||
trafficLightPosition: { x: 16, y: 18 },
|
||||
webPreferences: {
|
||||
preload: Path.join(__dirname, "preload.cjs"),
|
||||
preload: Path.join(__dirname, "preload.js"),
|
||||
contextIsolation: true,
|
||||
nodeIntegration: false,
|
||||
sandbox: true,
|
||||
@@ -2000,14 +1695,6 @@ function createWindow(): BrowserWindow {
|
||||
);
|
||||
}
|
||||
|
||||
if (params.mediaType === "image") {
|
||||
menuTemplate.push({
|
||||
label: "Copy Image",
|
||||
click: () => window.webContents.copyImageAt(params.x, params.y),
|
||||
});
|
||||
menuTemplate.push({ type: "separator" });
|
||||
}
|
||||
|
||||
menuTemplate.push(
|
||||
{ role: "cut", enabled: params.editFlags.canCut },
|
||||
{ role: "copy", enabled: params.editFlags.canCopy },
|
||||
@@ -2034,23 +1721,20 @@ function createWindow(): BrowserWindow {
|
||||
window.setTitle(APP_DISPLAY_NAME);
|
||||
emitUpdateState();
|
||||
});
|
||||
|
||||
let initialRevealScheduled = false;
|
||||
const revealInitialWindow = () => {
|
||||
if (initialRevealScheduled) {
|
||||
return;
|
||||
}
|
||||
initialRevealScheduled = true;
|
||||
revealWindow(window);
|
||||
};
|
||||
|
||||
window.once("ready-to-show", revealInitialWindow);
|
||||
if (!isDevelopment) {
|
||||
window.once("ready-to-show", () => {
|
||||
revealWindow(window);
|
||||
});
|
||||
}
|
||||
|
||||
if (isDevelopment) {
|
||||
void window.loadURL(resolveDesktopDevServerUrl());
|
||||
window.webContents.openDevTools({ mode: "detach" });
|
||||
setImmediate(() => {
|
||||
revealWindow(window);
|
||||
});
|
||||
} else {
|
||||
void window.loadURL(backendHttpUrl);
|
||||
void window.loadURL(resolveDesktopWindowUrl());
|
||||
}
|
||||
|
||||
window.on("closed", () => {
|
||||
@@ -2062,6 +1746,14 @@ function createWindow(): BrowserWindow {
|
||||
return window;
|
||||
}
|
||||
|
||||
function resolveDesktopWindowUrl(): string {
|
||||
if (backendHttpUrl) {
|
||||
return backendHttpUrl;
|
||||
}
|
||||
|
||||
return `${DESKTOP_SCHEME}://app`;
|
||||
}
|
||||
|
||||
// Override Electron's userData path before the `ready` event so that
|
||||
// Chromium session data uses a filesystem-friendly directory name.
|
||||
// Must be called synchronously at the top level — before `app.whenReady()`.
|
||||
@@ -2081,7 +1773,6 @@ async function bootstrap(): Promise<void> {
|
||||
(await resolveDesktopBackendPort({
|
||||
host: DESKTOP_LOOPBACK_HOST,
|
||||
startPort: DEFAULT_DESKTOP_BACKEND_PORT,
|
||||
requiredHosts: DESKTOP_REQUIRED_PORT_PROBE_HOSTS,
|
||||
}));
|
||||
writeDesktopLogHeader(
|
||||
configuredBackendPort === undefined
|
||||
@@ -2135,7 +1826,10 @@ async function bootstrap(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureInitialBackendWindowOpen();
|
||||
await waitForBackendHttpReady(backendHttpUrl);
|
||||
writeDesktopLogHeader("bootstrap backend ready");
|
||||
mainWindow = createWindow();
|
||||
writeDesktopLogHeader("bootstrap main window created");
|
||||
}
|
||||
|
||||
app.on("before-quit", () => {
|
||||
@@ -2169,11 +1863,7 @@ app
|
||||
revealWindow(existingWindow);
|
||||
return;
|
||||
}
|
||||
if (isDevelopment) {
|
||||
mainWindow = createWindow();
|
||||
return;
|
||||
}
|
||||
ensureInitialBackendWindowOpen();
|
||||
mainWindow = createWindow();
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -9,11 +9,9 @@ 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_SET_CHANNEL_CHANNEL = "desktop:update-set-channel";
|
||||
const UPDATE_CHECK_CHANNEL = "desktop:update-check";
|
||||
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
|
||||
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
|
||||
const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
|
||||
const GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL = "desktop:get-local-environment-bootstrap";
|
||||
const GET_CLIENT_SETTINGS_CHANNEL = "desktop:get-client-settings";
|
||||
const SET_CLIENT_SETTINGS_CHANNEL = "desktop:set-client-settings";
|
||||
@@ -26,13 +24,6 @@ const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getAppBranding: () => {
|
||||
const result = ipcRenderer.sendSync(GET_APP_BRANDING_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
return null;
|
||||
}
|
||||
return result as ReturnType<DesktopBridge["getAppBranding"]>;
|
||||
},
|
||||
getLocalEnvironmentBootstrap: () => {
|
||||
const result = ipcRenderer.sendSync(GET_LOCAL_ENVIRONMENT_BOOTSTRAP_CHANNEL);
|
||||
if (typeof result !== "object" || result === null) {
|
||||
@@ -53,7 +44,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
||||
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
||||
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
@@ -70,7 +61,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
};
|
||||
},
|
||||
getUpdateState: () => ipcRenderer.invoke(UPDATE_GET_STATE_CHANNEL),
|
||||
setUpdateChannel: (channel) => ipcRenderer.invoke(UPDATE_SET_CHANNEL_CHANNEL, channel),
|
||||
checkForUpdate: () => ipcRenderer.invoke(UPDATE_CHECK_CHANNEL),
|
||||
downloadUpdate: () => ipcRenderer.invoke(UPDATE_DOWNLOAD_CHANNEL),
|
||||
installUpdate: () => ipcRenderer.invoke(UPDATE_INSTALL_CHANNEL),
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch.ts";
|
||||
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
|
||||
|
||||
describe("resolveDesktopRuntimeInfo", () => {
|
||||
it("detects Rosetta-translated Intel builds on Apple Silicon", () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure.ts";
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
it("prefers an explicit host override", () => {
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { ServerListeningDetector } from "./serverListeningDetector.ts";
|
||||
|
||||
describe("ServerListeningDetector", () => {
|
||||
it("resolves when the server logs the listening line", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listening on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("resolves when the listening line arrives across multiple chunks", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
|
||||
detector.push("[01:23:30.571] INFO (#148): Listen");
|
||||
detector.push("ing on http://0.0.0.0:7011\n");
|
||||
|
||||
await expect(detector.promise).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects when the server exits before logging readiness", async () => {
|
||||
const detector = new ServerListeningDetector();
|
||||
const error = new Error("server exited");
|
||||
|
||||
detector.fail(error);
|
||||
|
||||
await expect(detector.promise).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
const LISTENING_LOG_FRAGMENT = "Listening on http://";
|
||||
const MAX_BUFFER_CHARS = 8_192;
|
||||
|
||||
export class ServerListeningDetector {
|
||||
private buffer = "";
|
||||
private settled = false;
|
||||
private readonly resolvePromise: () => void;
|
||||
private readonly rejectPromise: (error: unknown) => void;
|
||||
readonly promise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
let resolvePromise: (() => void) | null = null;
|
||||
let rejectPromise: ((error: unknown) => void) | null = null;
|
||||
|
||||
this.promise = new Promise<void>((resolve, reject) => {
|
||||
resolvePromise = resolve;
|
||||
rejectPromise = reject;
|
||||
});
|
||||
|
||||
this.resolvePromise = () => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
resolvePromise?.();
|
||||
};
|
||||
this.rejectPromise = (error) => {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
this.settled = true;
|
||||
rejectPromise?.(error);
|
||||
};
|
||||
}
|
||||
|
||||
push(chunk: unknown): void {
|
||||
if (this.settled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const text = Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk);
|
||||
this.buffer = `${this.buffer}${text.replace(/\r/g, "")}`;
|
||||
if (this.buffer.includes(LISTENING_LOG_FRAGMENT)) {
|
||||
this.resolvePromise();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.buffer.length > MAX_BUFFER_CHARS) {
|
||||
this.buffer = this.buffer.slice(-MAX_BUFFER_CHARS);
|
||||
}
|
||||
}
|
||||
|
||||
fail(error: unknown): void {
|
||||
this.rejectPromise(error);
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment.ts";
|
||||
import { syncShellEnvironment } from "./syncShellEnvironment";
|
||||
|
||||
describe("syncShellEnvironment", () => {
|
||||
it("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on macOS", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/bin/zsh",
|
||||
PATH: "/Users/test/.local/bin:/usr/bin",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi.fn(() => ({
|
||||
PATH: "/opt/homebrew/bin:/usr/bin",
|
||||
SSH_AUTH_SOCK: "/tmp/secretive.sock",
|
||||
HOMEBREW_PREFIX: "/opt/homebrew",
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
@@ -19,18 +18,9 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin:/Users/test/.local/bin");
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
expect(env.HOMEBREW_PREFIX).toBe("/opt/homebrew");
|
||||
});
|
||||
|
||||
it("preserves an inherited SSH_AUTH_SOCK value", () => {
|
||||
@@ -87,68 +77,12 @@ describe("syncShellEnvironment", () => {
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenCalledWith("/bin/zsh", ["PATH", "SSH_AUTH_SOCK"]);
|
||||
expect(env.PATH).toBe("/home/linuxbrew/.linuxbrew/bin:/usr/bin");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/secretive.sock");
|
||||
});
|
||||
|
||||
it("falls back to launchctl PATH on macOS when shell probing does not return one", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "/opt/homebrew/bin/nu",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const readEnvironment = vi
|
||||
.fn()
|
||||
.mockImplementationOnce(() => {
|
||||
throw new Error("unknown flag");
|
||||
})
|
||||
.mockImplementationOnce(() => ({}));
|
||||
const readLaunchctlPath = vi.fn(() => "/opt/homebrew/bin:/usr/bin");
|
||||
const logWarning = vi.fn();
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "darwin",
|
||||
readEnvironment,
|
||||
readLaunchctlPath,
|
||||
userShell: "/bin/zsh",
|
||||
logWarning,
|
||||
});
|
||||
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(1, "/opt/homebrew/bin/nu", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readEnvironment).toHaveBeenNthCalledWith(2, "/bin/zsh", [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
]);
|
||||
expect(readLaunchctlPath).toHaveBeenCalledTimes(1);
|
||||
expect(logWarning).toHaveBeenCalledWith(
|
||||
"Failed to read login shell environment from /opt/homebrew/bin/nu.",
|
||||
expect.any(Error),
|
||||
);
|
||||
expect(env.PATH).toBe("/opt/homebrew/bin:/usr/bin");
|
||||
});
|
||||
|
||||
it("does nothing on unsupported platforms", () => {
|
||||
it("does nothing outside macOS and linux", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
SHELL: "C:/Program Files/Git/bin/bash.exe",
|
||||
PATH: "C:\\Windows\\System32",
|
||||
@@ -160,7 +94,7 @@ describe("syncShellEnvironment", () => {
|
||||
}));
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "freebsd",
|
||||
platform: "win32",
|
||||
readEnvironment,
|
||||
});
|
||||
|
||||
@@ -168,122 +102,4 @@ describe("syncShellEnvironment", () => {
|
||||
expect(env.PATH).toBe("C:\\Windows\\System32");
|
||||
expect(env.SSH_AUTH_SOCK).toBe("/tmp/inherited.sock");
|
||||
});
|
||||
|
||||
it("hydrates PATH on Windows by merging PowerShell PATH with inherited PATH", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(() => ({
|
||||
PATH: "C:\\Custom\\Bin;C:\\Windows\\System32",
|
||||
}));
|
||||
const isWindowsCommandAvailable = vi.fn(() => true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(readWindowsEnvironment).toHaveBeenCalledWith(["PATH"], { loadProfile: false });
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(isWindowsCommandAvailable).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("loads the PowerShell profile on Windows when node is not available", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
LOCALAPPDATA: "C:\\Users\\testuser\\AppData\\Local",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) =>
|
||||
options?.loadProfile
|
||||
? {
|
||||
PATH: "C:\\Profile\\Node;C:\\Windows\\System32",
|
||||
FNM_DIR: "C:\\Users\\testuser\\AppData\\Roaming\\fnm",
|
||||
FNM_MULTISHELL_PATH: "C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
}
|
||||
: { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" },
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn().mockReturnValueOnce(false).mockReturnValueOnce(true);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Profile\\Node",
|
||||
"C:\\Windows\\System32",
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
|
||||
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.FNM_DIR).toBe("C:\\Users\\testuser\\AppData\\Roaming\\fnm");
|
||||
expect(env.FNM_MULTISHELL_PATH).toBe(
|
||||
"C:\\Users\\testuser\\AppData\\Local\\fnm_multishells\\123",
|
||||
);
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(1, ["PATH"], { loadProfile: false });
|
||||
expect(readWindowsEnvironment).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"],
|
||||
{ loadProfile: true },
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves baseline Windows env when the profile probe fails", () => {
|
||||
const env: NodeJS.ProcessEnv = {
|
||||
PATH: "C:\\Windows\\System32",
|
||||
APPDATA: "C:\\Users\\testuser\\AppData\\Roaming",
|
||||
USERPROFILE: "C:\\Users\\testuser",
|
||||
};
|
||||
const readWindowsEnvironment = vi.fn(
|
||||
(_names: ReadonlyArray<string>, options?: { loadProfile?: boolean }) => {
|
||||
if (options?.loadProfile) {
|
||||
throw new Error("profile load failed");
|
||||
}
|
||||
return { PATH: "C:\\Custom\\Bin;C:\\Windows\\System32" };
|
||||
},
|
||||
);
|
||||
const isWindowsCommandAvailable = vi.fn(() => false);
|
||||
|
||||
syncShellEnvironment(env, {
|
||||
platform: "win32",
|
||||
readWindowsEnvironment,
|
||||
isWindowsCommandAvailable,
|
||||
});
|
||||
|
||||
expect(env.PATH).toBe(
|
||||
[
|
||||
"C:\\Users\\testuser\\AppData\\Roaming\\npm",
|
||||
"C:\\Users\\testuser\\.bun\\bin",
|
||||
"C:\\Users\\testuser\\scoop\\shims",
|
||||
"C:\\Custom\\Bin",
|
||||
"C:\\Windows\\System32",
|
||||
].join(";"),
|
||||
);
|
||||
expect(env.SSH_AUTH_SOCK).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -1,109 +1,36 @@
|
||||
import {
|
||||
listLoginShellCandidates,
|
||||
mergePathEntries,
|
||||
readPathFromLaunchctl,
|
||||
readEnvironmentFromLoginShell,
|
||||
resolveWindowsEnvironment,
|
||||
} from "@t3tools/shared/shell";
|
||||
import type {
|
||||
CommandAvailabilityOptions,
|
||||
resolveLoginShell,
|
||||
ShellEnvironmentReader,
|
||||
WindowsShellEnvironmentReader,
|
||||
} from "@t3tools/shared/shell";
|
||||
|
||||
type WindowsCommandAvailabilityChecker = (
|
||||
command: string,
|
||||
options?: CommandAvailabilityOptions,
|
||||
) => boolean;
|
||||
|
||||
const LOGIN_SHELL_ENV_NAMES = [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const;
|
||||
|
||||
function logShellEnvironmentWarning(message: string, error?: unknown): void {
|
||||
console.warn(`[desktop] ${message}`, error instanceof Error ? error.message : (error ?? ""));
|
||||
}
|
||||
|
||||
export function syncShellEnvironment(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
options: {
|
||||
platform?: NodeJS.Platform;
|
||||
readEnvironment?: ShellEnvironmentReader;
|
||||
readWindowsEnvironment?: WindowsShellEnvironmentReader;
|
||||
isWindowsCommandAvailable?: WindowsCommandAvailabilityChecker;
|
||||
readLaunchctlPath?: typeof readPathFromLaunchctl;
|
||||
userShell?: string;
|
||||
logWarning?: (message: string, error?: unknown) => void;
|
||||
} = {},
|
||||
): void {
|
||||
const platform = options.platform ?? process.platform;
|
||||
|
||||
const logWarning = options.logWarning ?? logShellEnvironmentWarning;
|
||||
const readEnvironment = options.readEnvironment ?? readEnvironmentFromLoginShell;
|
||||
const shellEnvironment: Partial<Record<string, string>> = {};
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
|
||||
try {
|
||||
if (platform === "win32") {
|
||||
const repairedEnvironment = resolveWindowsEnvironment(env, {
|
||||
...(options.readWindowsEnvironment
|
||||
? { readEnvironment: options.readWindowsEnvironment }
|
||||
: {}),
|
||||
...(options.isWindowsCommandAvailable
|
||||
? { commandAvailable: options.isWindowsCommandAvailable }
|
||||
: {}),
|
||||
});
|
||||
for (const [key, value] of Object.entries(repairedEnvironment)) {
|
||||
if (value !== undefined) {
|
||||
env[key] = value;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
const shell = resolveLoginShell(platform, env.SHELL);
|
||||
if (!shell) return;
|
||||
|
||||
if (platform !== "darwin" && platform !== "linux") return;
|
||||
const shellEnvironment = (options.readEnvironment ?? readEnvironmentFromLoginShell)(shell, [
|
||||
"PATH",
|
||||
"SSH_AUTH_SOCK",
|
||||
]);
|
||||
|
||||
for (const shell of listLoginShellCandidates(platform, env.SHELL, options.userShell)) {
|
||||
try {
|
||||
Object.assign(shellEnvironment, readEnvironment(shell, LOGIN_SHELL_ENV_NAMES));
|
||||
if (shellEnvironment.PATH) {
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning(`Failed to read login shell environment from ${shell}.`, error);
|
||||
}
|
||||
}
|
||||
|
||||
const launchctlPath =
|
||||
platform === "darwin" && !shellEnvironment.PATH
|
||||
? (options.readLaunchctlPath ?? readPathFromLaunchctl)()
|
||||
: undefined;
|
||||
const mergedPath = mergePathEntries(shellEnvironment.PATH ?? launchctlPath, env.PATH, platform);
|
||||
if (mergedPath) {
|
||||
env.PATH = mergedPath;
|
||||
if (shellEnvironment.PATH) {
|
||||
env.PATH = shellEnvironment.PATH;
|
||||
}
|
||||
|
||||
if (!env.SSH_AUTH_SOCK && shellEnvironment.SSH_AUTH_SOCK) {
|
||||
env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
|
||||
}
|
||||
|
||||
for (const name of [
|
||||
"HOMEBREW_PREFIX",
|
||||
"HOMEBREW_CELLAR",
|
||||
"HOMEBREW_REPOSITORY",
|
||||
"XDG_CONFIG_HOME",
|
||||
"XDG_DATA_HOME",
|
||||
] as const) {
|
||||
if (!env[name] && shellEnvironment[name]) {
|
||||
env[name] = shellEnvironment[name];
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logWarning("Failed to synchronize the desktop shell environment.", error);
|
||||
} catch {
|
||||
// Keep inherited environment if shell lookup fails.
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
doesVersionMatchDesktopUpdateChannel,
|
||||
isNightlyDesktopVersion,
|
||||
resolveDefaultDesktopUpdateChannel,
|
||||
} from "./updateChannels.ts";
|
||||
|
||||
describe("isNightlyDesktopVersion", () => {
|
||||
it("detects packaged nightly versions", () => {
|
||||
expect(isNightlyDesktopVersion("0.0.17-nightly.20260415.1")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not flag stable versions as nightly", () => {
|
||||
expect(isNightlyDesktopVersion("0.0.17")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDefaultDesktopUpdateChannel", () => {
|
||||
it("defaults stable builds to latest", () => {
|
||||
expect(resolveDefaultDesktopUpdateChannel("0.0.17")).toBe("latest");
|
||||
});
|
||||
|
||||
it("defaults nightly builds to nightly", () => {
|
||||
expect(resolveDefaultDesktopUpdateChannel("0.0.17-nightly.20260415.1")).toBe("nightly");
|
||||
});
|
||||
});
|
||||
|
||||
describe("doesVersionMatchDesktopUpdateChannel", () => {
|
||||
it("accepts nightly releases on the nightly channel", () => {
|
||||
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "nightly")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects stable releases on the nightly channel", () => {
|
||||
expect(doesVersionMatchDesktopUpdateChannel("0.0.17", "nightly")).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects nightly releases on the stable channel", () => {
|
||||
expect(doesVersionMatchDesktopUpdateChannel("0.0.17-nightly.20260416.1", "latest")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { DesktopUpdateChannel } from "@t3tools/contracts";
|
||||
|
||||
const NIGHTLY_VERSION_PATTERN = /-nightly\.\d{8}\.\d+$/;
|
||||
|
||||
export function isNightlyDesktopVersion(version: string): boolean {
|
||||
return NIGHTLY_VERSION_PATTERN.test(version);
|
||||
}
|
||||
|
||||
export function resolveDefaultDesktopUpdateChannel(appVersion: string): DesktopUpdateChannel {
|
||||
return isNightlyDesktopVersion(appVersion) ? "nightly" : "latest";
|
||||
}
|
||||
|
||||
export function doesVersionMatchDesktopUpdateChannel(
|
||||
version: string,
|
||||
channel: DesktopUpdateChannel,
|
||||
): boolean {
|
||||
return resolveDefaultDesktopUpdateChannel(version) === channel;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
reduceDesktopUpdateStateOnInstallFailure,
|
||||
reduceDesktopUpdateStateOnNoUpdate,
|
||||
reduceDesktopUpdateStateOnUpdateAvailable,
|
||||
} from "./updateMachine.ts";
|
||||
} from "./updateMachine";
|
||||
|
||||
const runtimeInfo = {
|
||||
hostArch: "x64",
|
||||
@@ -23,7 +23,7 @@ describe("updateMachine", () => {
|
||||
it("clears transient errors when a check starts", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckStart(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
message: "network",
|
||||
@@ -42,7 +42,7 @@ describe("updateMachine", () => {
|
||||
it("records a check failure without exposing an action", () => {
|
||||
const state = reduceDesktopUpdateStateOnCheckFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
@@ -58,7 +58,7 @@ describe("updateMachine", () => {
|
||||
it("preserves available version on download failure for retry", () => {
|
||||
const state = reduceDesktopUpdateStateOnDownloadFailure(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -76,7 +76,7 @@ describe("updateMachine", () => {
|
||||
it("transitions to downloaded and then preserves install retry state", () => {
|
||||
const downloaded = reduceDesktopUpdateStateOnDownloadComplete(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "downloading",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -98,7 +98,7 @@ describe("updateMachine", () => {
|
||||
it("clears stale download state when no update is available", () => {
|
||||
const state = reduceDesktopUpdateStateOnNoUpdate(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "error",
|
||||
availableVersion: "1.1.0",
|
||||
@@ -120,7 +120,7 @@ describe("updateMachine", () => {
|
||||
it("tracks available, download start, and progress cleanly", () => {
|
||||
const available = reduceDesktopUpdateStateOnUpdateAvailable(
|
||||
{
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo, "latest"),
|
||||
...createInitialDesktopUpdateState("1.0.0", runtimeInfo),
|
||||
enabled: true,
|
||||
status: "checking",
|
||||
},
|
||||
@@ -131,7 +131,6 @@ describe("updateMachine", () => {
|
||||
const progress = reduceDesktopUpdateStateOnDownloadProgress(downloading, 55.5);
|
||||
|
||||
expect(available.status).toBe("available");
|
||||
expect(available.channel).toBe("latest");
|
||||
expect(downloading.status).toBe("downloading");
|
||||
expect(downloading.downloadPercent).toBe(0);
|
||||
expect(progress.downloadPercent).toBe(55.5);
|
||||
|
||||
@@ -1,20 +1,14 @@
|
||||
import type {
|
||||
DesktopRuntimeInfo,
|
||||
DesktopUpdateChannel,
|
||||
DesktopUpdateState,
|
||||
} from "@t3tools/contracts";
|
||||
import type { DesktopRuntimeInfo, DesktopUpdateState } from "@t3tools/contracts";
|
||||
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState.ts";
|
||||
import { getCanRetryAfterDownloadFailure, nextStatusAfterDownloadFailure } from "./updateState";
|
||||
|
||||
export function createInitialDesktopUpdateState(
|
||||
currentVersion: string,
|
||||
runtimeInfo: DesktopRuntimeInfo,
|
||||
channel: DesktopUpdateChannel,
|
||||
): DesktopUpdateState {
|
||||
return {
|
||||
enabled: false,
|
||||
status: "disabled",
|
||||
channel,
|
||||
currentVersion,
|
||||
hostArch: runtimeInfo.hostArch,
|
||||
appArch: runtimeInfo.appArch,
|
||||
|
||||
@@ -6,12 +6,11 @@ import {
|
||||
getAutoUpdateDisabledReason,
|
||||
nextStatusAfterDownloadFailure,
|
||||
shouldBroadcastDownloadProgress,
|
||||
} from "./updateState.ts";
|
||||
} from "./updateState";
|
||||
|
||||
const baseState: DesktopUpdateState = {
|
||||
enabled: true,
|
||||
status: "idle",
|
||||
channel: "latest",
|
||||
currentVersion: "1.0.0",
|
||||
hostArch: "x64",
|
||||
appArch: "x64",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"types": ["node", "electron"],
|
||||
"lib": ["ESNext", "DOM", "esnext.disposable"]
|
||||
"lib": ["ES2023", "DOM", "esnext.disposable"]
|
||||
},
|
||||
"include": ["src", "tsdown.config.ts"]
|
||||
}
|
||||
@@ -4,7 +4,7 @@ const shared = {
|
||||
format: "cjs" as const,
|
||||
outDir: "dist-electron",
|
||||
sourcemap: true,
|
||||
outExtensions: () => ({ js: ".cjs" }),
|
||||
outExtensions: () => ({ js: ".js" }),
|
||||
};
|
||||
|
||||
export default defineConfig([
|
||||
|
||||
@@ -438,7 +438,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
) =>
|
||||
waitFor(
|
||||
pendingApprovalRepository
|
||||
.getByRequestId({ requestId: ApprovalRequestId.make(requestId) })
|
||||
.getByRequestId({ requestId: ApprovalRequestId.makeUnsafe(requestId) })
|
||||
.pipe(
|
||||
Effect.map((row) =>
|
||||
Option.match(row, {
|
||||
|
||||
@@ -289,7 +289,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
state.turnCount += 1;
|
||||
const turnCount = state.turnCount;
|
||||
const turnId = TurnId.make(`turn-${turnCount}`);
|
||||
const turnId = TurnId.makeUnsafe(`turn-${turnCount}`);
|
||||
|
||||
const response = state.queuedResponses.shift();
|
||||
if (!response) {
|
||||
@@ -307,7 +307,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: randomUUID(),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
sessionId: RuntimeSessionId.makeUnsafe(String(input.threadId)),
|
||||
createdAt: nowIso(),
|
||||
};
|
||||
rawEvent.threadId = state.snapshot.threadId;
|
||||
@@ -363,7 +363,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make(randomUUID()),
|
||||
eventId: EventId.makeUnsafe(randomUUID()),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
|
||||
@@ -5,14 +5,14 @@ const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
const REQUEST_ID = RuntimeRequestId.make("req-1");
|
||||
const REQUEST_ID = RuntimeRequestId.makeUnsafe("req-1");
|
||||
|
||||
function baseEvent(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
): Pick<LegacyProviderRuntimeEvent, "eventId" | "provider" | "sessionId" | "createdAt"> {
|
||||
return {
|
||||
eventId: EventId.make(eventId),
|
||||
eventId: EventId.makeUnsafe(eventId),
|
||||
provider: PROVIDER,
|
||||
sessionId: SESSION_ID,
|
||||
createdAt,
|
||||
|
||||
@@ -30,13 +30,14 @@ import type {
|
||||
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asEventId = (value: string): EventId => EventId.make(value);
|
||||
const asApprovalRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.make(value);
|
||||
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 asApprovalRequestId = (value: string): ApprovalRequestId =>
|
||||
ApprovalRequestId.makeUnsafe(value);
|
||||
|
||||
const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const THREAD_ID = ThreadId.makeUnsafe("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = ProviderKind;
|
||||
@@ -111,7 +112,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -124,7 +125,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -149,7 +150,7 @@ const startTurn = (input: {
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make(input.commandId),
|
||||
commandId: CommandId.makeUnsafe(input.commandId),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId(input.messageId),
|
||||
@@ -260,7 +261,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create-real-codex"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create-real-codex"),
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
@@ -273,7 +274,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create-real-codex"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create-real-codex"),
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
@@ -290,7 +291,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-1"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-1"),
|
||||
@@ -317,7 +318,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-real-codex-2"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-real-codex-2"),
|
||||
threadId: THREAD_ID,
|
||||
message: {
|
||||
messageId: asMessageId("msg-real-codex-2"),
|
||||
@@ -582,7 +583,7 @@ it.live("tracks approval requests and resolves pending approvals on user respons
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.make("cmd-approval-respond"),
|
||||
commandId: CommandId.makeUnsafe("cmd-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -814,7 +815,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-checkpoint-revert"),
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
@@ -874,7 +875,7 @@ it.live(
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-no-session"),
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-no-session"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 0,
|
||||
createdAt: nowIso(),
|
||||
@@ -1118,7 +1119,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.approval.respond",
|
||||
commandId: CommandId.make("cmd-claude-approval-respond"),
|
||||
commandId: CommandId.makeUnsafe("cmd-claude-approval-respond"),
|
||||
threadId: THREAD_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
decision: "accept",
|
||||
@@ -1191,7 +1192,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.interrupt",
|
||||
commandId: CommandId.make("cmd-turn-interrupt-claude"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-interrupt-claude"),
|
||||
threadId: THREAD_ID,
|
||||
createdAt: nowIso(),
|
||||
});
|
||||
@@ -1308,7 +1309,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-checkpoint-revert-claude"),
|
||||
commandId: CommandId.makeUnsafe("cmd-checkpoint-revert-claude"),
|
||||
threadId: THREAD_ID,
|
||||
turnCount: 1,
|
||||
createdAt: nowIso(),
|
||||
|
||||
@@ -122,12 +122,15 @@ it.live("replays typed runtime fixture events", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
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);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -154,12 +157,15 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
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);
|
||||
|
||||
const observedEvents = yield* runTurn({
|
||||
@@ -190,12 +196,15 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
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);
|
||||
|
||||
const firstTurnEvents = yield* runTurn({
|
||||
@@ -241,12 +250,15 @@ it.live("rolls back provider conversation state only", () =>
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
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);
|
||||
|
||||
yield* runTurn({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.20",
|
||||
"version": "0.0.15",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -15,17 +15,15 @@
|
||||
],
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node --watch src/bin.ts",
|
||||
"dev": "bun run src/bin.ts",
|
||||
"build": "node scripts/cli.ts build",
|
||||
"build:bundle": "tsdown",
|
||||
"start": "node dist/bin.mjs",
|
||||
"prepare": "effect-language-service patch",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"test:process-reaper": "vitest run src/server.test.ts src/provider/Layers/ClaudeAdapter.test.ts src/provider/Layers/ProviderSessionDirectory.test.ts src/provider/Layers/ProviderSessionReaper.test.ts src/provider/Layers/CodexAdapter.test.ts"
|
||||
"test": "vitest run"
|
||||
},
|
||||
"dependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.111",
|
||||
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
|
||||
"@effect/platform-bun": "catalog:",
|
||||
"@effect/platform-node": "catalog:",
|
||||
"@effect/sql-sqlite-bun": "catalog:",
|
||||
|
||||
+16
-33
@@ -14,22 +14,6 @@ import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog
|
||||
import rootPackageJson from "../../../package.json" with { type: "json" };
|
||||
import serverPackageJson from "../package.json" with { type: "json" };
|
||||
|
||||
interface PackageJson {
|
||||
name: string;
|
||||
repository: {
|
||||
type: string;
|
||||
url: string;
|
||||
directory: string;
|
||||
};
|
||||
bin: Record<string, string>;
|
||||
type: string;
|
||||
version: string;
|
||||
engines: Record<string, string>;
|
||||
files: string[];
|
||||
dependencies: Record<string, string>;
|
||||
overrides: Record<string, string>;
|
||||
}
|
||||
|
||||
class CliError extends Data.TaggedError("CliError")<{
|
||||
readonly message: string;
|
||||
readonly cause?: unknown;
|
||||
@@ -147,13 +131,13 @@ const buildCmd = Command.make(
|
||||
|
||||
yield* Effect.log("[cli] Running tsdown...");
|
||||
yield* runCommand(
|
||||
ChildProcess.make(process.execPath, ["--run", "build:bundle"], {
|
||||
ChildProcess.make({
|
||||
cwd: serverDir,
|
||||
stdout: config.verbose ? "inherit" : "ignore",
|
||||
stderr: "inherit",
|
||||
// Windows needs shell mode to resolve `.cmd` shims on PATH.
|
||||
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
})`bun tsdown`,
|
||||
);
|
||||
|
||||
const webDist = path.join(repoRoot, "apps/web/dist");
|
||||
@@ -193,7 +177,7 @@ const publishCmd = Command.make(
|
||||
const backupPath = `${packageJsonPath}.bak`;
|
||||
|
||||
// Assert build assets exist
|
||||
for (const relPath of ["dist/bin.mjs", "dist/client/index.html"]) {
|
||||
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({
|
||||
@@ -203,10 +187,12 @@ const publishCmd = Command.make(
|
||||
}
|
||||
|
||||
yield* Effect.acquireUseRelease(
|
||||
// Acquire: backup package.json, resolve catalog dependencies, and strip devDependencies/scripts
|
||||
// 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: PackageJson = {
|
||||
const pkg = {
|
||||
name: serverPackageJson.name,
|
||||
repository: serverPackageJson.repository,
|
||||
bin: serverPackageJson.bin,
|
||||
@@ -214,22 +200,19 @@ const publishCmd = Command.make(
|
||||
version,
|
||||
engines: serverPackageJson.engines,
|
||||
files: serverPackageJson.files,
|
||||
dependencies: resolveCatalogDependencies(
|
||||
serverPackageJson.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server",
|
||||
),
|
||||
overrides: resolveCatalogDependencies(
|
||||
rootPackageJson.overrides,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server",
|
||||
),
|
||||
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] Prepared package.json for publish");
|
||||
yield* Effect.log("[cli] Resolved package.json for publish");
|
||||
|
||||
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
|
||||
return { iconBackups };
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { expect, it } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import type { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfigShape } from "../../config.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
|
||||
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
|
||||
|
||||
@@ -10,10 +10,8 @@ import { layerConfig as SqlitePersistenceLayerLive } from "../../persistence/Lay
|
||||
import {
|
||||
AuthControlPlane,
|
||||
AuthControlPlaneError,
|
||||
DEFAULT_SESSION_SUBJECT,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
import type {
|
||||
AuthControlPlaneShape,
|
||||
DEFAULT_SESSION_SUBJECT,
|
||||
IssuedBearerSession,
|
||||
IssuedPairingLink,
|
||||
} from "../Services/AuthControlPlane.ts";
|
||||
|
||||
@@ -20,10 +20,7 @@ import {
|
||||
AuthError,
|
||||
type ServerAuthShape,
|
||||
} from "../Services/ServerAuth.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
} from "../Services/SessionCredentialService.ts";
|
||||
import { SessionCredentialService } from "../Services/SessionCredentialService.ts";
|
||||
import { AuthControlPlaneLive, AuthCoreLive } from "./AuthControlPlane.ts";
|
||||
|
||||
type BootstrapExchangeResult = {
|
||||
@@ -68,13 +65,6 @@ export const makeServerAuth = Effect.gen(function* () {
|
||||
|
||||
const authenticateToken = (token: string): Effect.Effect<AuthenticatedSession, AuthError> =>
|
||||
sessions.verify(token).pipe(
|
||||
Effect.tapError((cause: SessionCredentialError) =>
|
||||
Effect.logWarning("Rejected authenticated session credential.").pipe(
|
||||
Effect.annotateLogs({
|
||||
reason: cause.message,
|
||||
}),
|
||||
),
|
||||
),
|
||||
Effect.map((session) => ({
|
||||
sessionId: session.sessionId,
|
||||
subject: session.subject,
|
||||
|
||||
@@ -33,12 +33,10 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("desktop-managed-local");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["desktop-bootstrap"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session_3773");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
mode: "desktop",
|
||||
port: 3773,
|
||||
}),
|
||||
),
|
||||
),
|
||||
@@ -68,7 +66,6 @@ it.layer(NodeServices.layer)("ServerAuthPolicyLive", (it) => {
|
||||
|
||||
expect(descriptor.policy).toBe("loopback-browser");
|
||||
expect(descriptor.bootstrapMethods).toEqual(["one-time-token"]);
|
||||
expect(descriptor.sessionCookieName).toBe("t3_session");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeServerAuthPolicyLayer({
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Effect, Layer } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
|
||||
import { resolveSessionCookieName } from "../utils.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import { isLoopbackHost, isWildcardHost } from "../../startupAccess.ts";
|
||||
|
||||
export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
@@ -30,10 +30,7 @@ export const makeServerAuthPolicy = Effect.gen(function* () {
|
||||
policy,
|
||||
bootstrapMethods,
|
||||
sessionMethods: ["browser-session-cookie", "bearer-session-token"],
|
||||
sessionCookieName: resolveSessionCookieName({
|
||||
mode: config.mode,
|
||||
port: config.port,
|
||||
}),
|
||||
sessionCookieName: SESSION_COOKIE_NAME,
|
||||
};
|
||||
|
||||
return {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
@@ -28,14 +28,17 @@ export const makeServerSecretStore = Effect.gen(function* () {
|
||||
|
||||
const resolveSecretPath = (name: string) => path.join(serverConfig.secretsDir, `${name}.bin`);
|
||||
|
||||
const isPlatformError = (u: unknown): u is PlatformError.PlatformError =>
|
||||
Predicate.isTagged(u, "PlatformError");
|
||||
const isMissingSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "NotFound";
|
||||
|
||||
const isAlreadyExistsSecretFileError = (cause: unknown): cause is PlatformError.PlatformError =>
|
||||
cause instanceof PlatformError.PlatformError && cause.reason._tag === "AlreadyExists";
|
||||
|
||||
const get: ServerSecretStoreShape["get"] = (name) =>
|
||||
fileSystem.readFile(resolveSecretPath(name)).pipe(
|
||||
Effect.map((bytes) => Uint8Array.from(bytes)),
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
isMissingSecretFileError(cause)
|
||||
? Effect.succeed(null)
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
@@ -105,7 +108,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
|
||||
return create(name, generated).pipe(
|
||||
Effect.as(Uint8Array.from(generated)),
|
||||
Effect.catchTag("SecretStoreError", (error) =>
|
||||
isPlatformError(error.cause) && error.cause.reason._tag === "AlreadyExists"
|
||||
isAlreadyExistsSecretFileError(error.cause)
|
||||
? get(name).pipe(
|
||||
Effect.flatMap((created) =>
|
||||
created !== null
|
||||
@@ -126,7 +129,7 @@ export const makeServerSecretStore = Effect.gen(function* () {
|
||||
const remove: ServerSecretStoreShape["remove"] = (name) =>
|
||||
fileSystem.remove(resolveSecretPath(name)).pipe(
|
||||
Effect.catch((cause) =>
|
||||
cause.reason._tag === "NotFound"
|
||||
isMissingSecretFileError(cause)
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
new SecretStoreError({
|
||||
|
||||
@@ -2,10 +2,10 @@ import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "
|
||||
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
|
||||
import { Option } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
|
||||
import { AuthSessionRepository } from "../../persistence/Services/AuthSessions.ts";
|
||||
import { ServerSecretStore } from "../Services/ServerSecretStore.ts";
|
||||
import { SESSION_COOKIE_NAME } from "../utils.ts";
|
||||
import {
|
||||
SessionCredentialError,
|
||||
SessionCredentialService,
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
import {
|
||||
base64UrlDecodeUtf8,
|
||||
base64UrlEncode,
|
||||
resolveSessionCookieName,
|
||||
signPayload,
|
||||
timingSafeEqualBase64Url,
|
||||
} from "../utils.ts";
|
||||
@@ -82,16 +81,11 @@ function toAuthClientSession(input: Omit<AuthClientSession, "current">): AuthCli
|
||||
}
|
||||
|
||||
export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const secretStore = yield* ServerSecretStore;
|
||||
const authSessions = yield* AuthSessionRepository;
|
||||
const signingSecret = yield* secretStore.getOrCreateRandom(SIGNING_SECRET_NAME, 32);
|
||||
const connectedSessionsRef = yield* Ref.make(new Map<string, number>());
|
||||
const changesPubSub = yield* PubSub.unbounded<SessionCredentialChange>();
|
||||
const cookieName = resolveSessionCookieName({
|
||||
mode: serverConfig.mode,
|
||||
port: serverConfig.port,
|
||||
});
|
||||
|
||||
const toSessionCredentialError = (message: string) => (cause: unknown) =>
|
||||
new SessionCredentialError({
|
||||
@@ -194,7 +188,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
|
||||
const issue: SessionCredentialServiceShape["issue"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
const sessionId = AuthSessionId.make(crypto.randomUUID());
|
||||
const sessionId = AuthSessionId.makeUnsafe(crypto.randomUUID());
|
||||
const issuedAt = yield* DateTime.now;
|
||||
const expiresAt = DateTime.add(issuedAt, {
|
||||
milliseconds: Duration.toMillis(input?.ttl ?? DEFAULT_SESSION_TTL),
|
||||
@@ -478,7 +472,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
|
||||
}).pipe(Effect.mapError(toSessionCredentialError("Failed to revoke other sessions.")));
|
||||
|
||||
return {
|
||||
cookieName,
|
||||
cookieName: SESSION_COOKIE_NAME,
|
||||
issue,
|
||||
verify,
|
||||
issueWebSocketToken,
|
||||
|
||||
@@ -4,8 +4,8 @@ import type {
|
||||
AuthPairingLink,
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, Context } from "effect";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
import { Data, DateTime, Duration, Effect, ServiceMap } from "effect";
|
||||
import { SessionRole } from "./SessionCredentialService";
|
||||
|
||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
||||
|
||||
@@ -64,6 +64,6 @@ export interface AuthControlPlaneShape {
|
||||
) => Effect.Effect<number, AuthControlPlaneError>;
|
||||
}
|
||||
|
||||
export class AuthControlPlane extends Context.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
export class AuthControlPlane extends ServiceMap.Service<AuthControlPlane, AuthControlPlaneShape>()(
|
||||
"t3/AuthControlPlane",
|
||||
) {}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import { Data, DateTime, Duration, ServiceMap } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type BootstrapCredentialRole = "owner" | "client";
|
||||
@@ -51,7 +51,7 @@ export interface BootstrapCredentialServiceShape {
|
||||
readonly consume: (credential: string) => Effect.Effect<BootstrapGrant, BootstrapCredentialError>;
|
||||
}
|
||||
|
||||
export class BootstrapCredentialService extends Context.Service<
|
||||
export class BootstrapCredentialService extends ServiceMap.Service<
|
||||
BootstrapCredentialService,
|
||||
BootstrapCredentialServiceShape
|
||||
>()("t3/auth/Services/BootstrapCredentialService") {}
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
ServerAuthSessionMethod,
|
||||
AuthWebSocketTokenResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Context } from "effect";
|
||||
import { Data, DateTime, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
@@ -79,6 +79,6 @@ export interface ServerAuthShape {
|
||||
readonly issueStartupPairingUrl: (baseUrl: string) => Effect.Effect<string, AuthError>;
|
||||
}
|
||||
|
||||
export class ServerAuth extends Context.Service<ServerAuth, ServerAuthShape>()(
|
||||
export class ServerAuth extends ServiceMap.Service<ServerAuth, ServerAuthShape>()(
|
||||
"t3/auth/Services/ServerAuth",
|
||||
) {}
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { ServerAuthDescriptor } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerAuthPolicyShape {
|
||||
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerAuthPolicy extends Context.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
export class ServerAuthPolicy extends ServiceMap.Service<ServerAuthPolicy, ServerAuthPolicyShape>()(
|
||||
"t3/auth/Services/ServerAuthPolicy",
|
||||
) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Data, Context } from "effect";
|
||||
import { Data, ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
|
||||
@@ -16,6 +16,7 @@ export interface ServerSecretStoreShape {
|
||||
readonly remove: (name: string) => Effect.Effect<void, SecretStoreError>;
|
||||
}
|
||||
|
||||
export class ServerSecretStore extends Context.Service<ServerSecretStore, ServerSecretStoreShape>()(
|
||||
"t3/auth/Services/ServerSecretStore",
|
||||
) {}
|
||||
export class ServerSecretStore extends ServiceMap.Service<
|
||||
ServerSecretStore,
|
||||
ServerSecretStoreShape
|
||||
>()("t3/auth/Services/ServerSecretStore") {}
|
||||
@@ -4,7 +4,7 @@ import type {
|
||||
AuthSessionId,
|
||||
ServerAuthSessionMethod,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Context } from "effect";
|
||||
import { Data, DateTime, Duration, ServiceMap } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
|
||||
export type SessionRole = "owner" | "client";
|
||||
@@ -81,7 +81,7 @@ export interface SessionCredentialServiceShape {
|
||||
readonly markDisconnected: (sessionId: AuthSessionId) => Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
export class SessionCredentialService extends Context.Service<
|
||||
export class SessionCredentialService extends ServiceMap.Service<
|
||||
SessionCredentialService,
|
||||
SessionCredentialServiceShape
|
||||
>()("t3/auth/Services/SessionCredentialService") {}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { deriveAuthClientMetadata } from "./utils.ts";
|
||||
import { deriveAuthClientMetadata } from "./utils";
|
||||
|
||||
describe("deriveAuthClientMetadata", () => {
|
||||
it("labels Electron user agents as Electron instead of Chrome", () => {
|
||||
|
||||
@@ -2,18 +2,7 @@ import type { AuthClientMetadata, AuthClientMetadataDeviceType } from "@t3tools/
|
||||
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function resolveSessionCookieName(input: {
|
||||
readonly mode: "web" | "desktop";
|
||||
readonly port: number;
|
||||
}): string {
|
||||
if (input.mode !== "desktop") {
|
||||
return SESSION_COOKIE_NAME;
|
||||
}
|
||||
|
||||
return `${SESSION_COOKIE_NAME}_${input.port}`;
|
||||
}
|
||||
export const SESSION_COOKIE_NAME = "t3_session";
|
||||
|
||||
export function base64UrlEncode(input: string | Uint8Array): string {
|
||||
const buffer = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
|
||||
|
||||
@@ -5,12 +5,12 @@ import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { cli } from "./cli.ts";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { cli } from "./cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
Command.run(cli, { version: packageJson.version }).pipe(
|
||||
Command.run(cli, { version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
|
||||
@@ -10,7 +10,7 @@ import * as Fiber from "effect/Fiber";
|
||||
import { TestClock } from "effect/testing";
|
||||
import { vi } from "vitest";
|
||||
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
|
||||
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
|
||||
import { assertNone, assertSome } from "@effect/vitest/utils";
|
||||
|
||||
const openSyncInterceptor = vi.hoisted(() => ({ failPath: null as string | null }));
|
||||
|
||||
@@ -26,7 +26,7 @@ function makeThreadCheckpointContext(input: {
|
||||
worktreePath: input.worktreePath,
|
||||
checkpoints: [
|
||||
{
|
||||
turnId: TurnId.make("turn-1"),
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
checkpointTurnCount: input.checkpointTurnCount,
|
||||
checkpointRef: input.checkpointRef,
|
||||
status: "ready",
|
||||
@@ -40,8 +40,8 @@ function makeThreadCheckpointContext(input: {
|
||||
|
||||
describe("CheckpointDiffQueryLive", () => {
|
||||
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
|
||||
const projectId = ProjectId.make("project-1");
|
||||
const threadId = ThreadId.make("thread-1");
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
|
||||
const diffCheckpointsCalls: Array<{
|
||||
@@ -82,15 +82,10 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -124,7 +119,7 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
const threadId = ThreadId.makeUnsafe("thread-missing");
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
@@ -141,15 +136,10 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -93,7 +93,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-checkpoint-store");
|
||||
const threadId = ThreadId.makeUnsafe("thread-checkpoint-store");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
OrchestrationGetTurnDiffInput,
|
||||
OrchestrationGetTurnDiffResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointServiceError } from "../Errors.ts";
|
||||
@@ -43,7 +43,7 @@ export interface CheckpointDiffQueryShape {
|
||||
/**
|
||||
* CheckpointDiffQuery - Service tag for checkpoint diff queries.
|
||||
*/
|
||||
export class CheckpointDiffQuery extends Context.Service<
|
||||
export class CheckpointDiffQuery extends ServiceMap.Service<
|
||||
CheckpointDiffQuery,
|
||||
CheckpointDiffQueryShape
|
||||
>()("t3/checkpointing/Services/CheckpointDiffQuery") {}
|
||||
@@ -5,12 +5,12 @@
|
||||
* workspace thread timeline. It does not store user-facing checkpoint metadata
|
||||
* and does not coordinate provider conversation rollback.
|
||||
*
|
||||
* Uses Effect `Context.Service` for dependency injection and exposes typed
|
||||
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
|
||||
* domain errors for checkpoint storage operations.
|
||||
*
|
||||
* @module CheckpointStore
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { CheckpointStoreError } from "../Errors.ts";
|
||||
@@ -95,6 +95,6 @@ export interface CheckpointStoreShape {
|
||||
/**
|
||||
* CheckpointStore - Service tag for checkpoint persistence and restore operations.
|
||||
*/
|
||||
export class CheckpointStore extends Context.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
export class CheckpointStore extends ServiceMap.Service<CheckpointStore, CheckpointStoreShape>()(
|
||||
"t3/checkpointing/Services/CheckpointStore",
|
||||
) {}
|
||||
@@ -4,7 +4,7 @@ import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
|
||||
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
|
||||
|
||||
export function checkpointRefForThreadTurn(threadId: ThreadId, turnCount: number): CheckpointRef {
|
||||
return CheckpointRef.make(
|
||||
return CheckpointRef.makeUnsafe(
|
||||
`${CHECKPOINT_REFS_PREFIX}/${Encoding.encodeBase64Url(threadId)}/turn/${turnCount}`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,8 +5,8 @@ import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect"
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { deriveServerPaths } from "./config.ts";
|
||||
import { resolveServerConfig } from "./cli.ts";
|
||||
import { deriveServerPaths } from "./config";
|
||||
import { resolveServerConfig } from "./cli";
|
||||
|
||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
@@ -153,69 +153,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
|
||||
const fd = yield* openBootstrapFd({
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
const resolved = yield* resolveServerConfig(
|
||||
{
|
||||
mode: Option.some("web"),
|
||||
port: Option.some(8788),
|
||||
host: Option.some("127.0.0.1"),
|
||||
baseDir: Option.some(baseDir),
|
||||
cwd: Option.none(),
|
||||
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
|
||||
noBrowser: Option.some(false),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(false),
|
||||
logWebSocketEvents: Option.some(false),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(
|
||||
ConfigProvider.layer(
|
||||
ConfigProvider.fromEnv({
|
||||
env: {
|
||||
T3CODE_BOOTSTRAP_FD: String(fd),
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
|
||||
T3CODE_LOG_WS_EVENTS: "true",
|
||||
},
|
||||
}),
|
||||
),
|
||||
NetService.layer,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(resolved).toEqual({
|
||||
logLevel: "Info",
|
||||
...defaultObservabilityConfig,
|
||||
mode: "web",
|
||||
port: 8788,
|
||||
cwd: process.cwd(),
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
host: "127.0.0.1",
|
||||
staticDir: undefined,
|
||||
devUrl: new URL("http://127.0.0.1:4173"),
|
||||
noBrowser: false,
|
||||
startupPresentation: "browser",
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
|
||||
Effect.gen(function* () {
|
||||
const { join } = yield* Path.Path;
|
||||
|
||||
@@ -152,10 +152,6 @@ it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("accepts canonical --no-<flag> boolean negation", () =>
|
||||
runCliWithRuntime(["--no-log-websocket-events", "--version"]),
|
||||
);
|
||||
|
||||
it.effect("rejects invalid log-level casing before launching the server", () =>
|
||||
Effect.gen(function* () {
|
||||
const error = yield* runCliWithRuntime(["--log-level", "Debug"]).pipe(Effect.flip);
|
||||
|
||||
+79
-49
@@ -40,31 +40,30 @@ import {
|
||||
RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
type StartupPresentation,
|
||||
} from "./config.ts";
|
||||
import { readBootstrapEnvelope } from "./bootstrap.ts";
|
||||
import { expandHomePath, resolveBaseDir } from "./os-jank.ts";
|
||||
import { runServer } from "./server.ts";
|
||||
} from "./config";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { expandHomePath, resolveBaseDir } from "./os-jank";
|
||||
import { runServer } from "./server";
|
||||
import { AuthControlPlaneRuntimeLive } from "./auth/Layers/AuthControlPlane.ts";
|
||||
import {
|
||||
formatIssuedPairingCredential,
|
||||
formatIssuedSession,
|
||||
formatPairingCredentialList,
|
||||
formatSessionList,
|
||||
} from "./cliAuthFormat.ts";
|
||||
import { AuthControlPlane } from "./auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
|
||||
} from "./cliAuthFormat";
|
||||
import { AuthControlPlane, AuthControlPlaneShape } from "./auth/Services/AuthControlPlane.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup.ts";
|
||||
import { getAutoBootstrapDefaultModelSelection } from "./serverRuntimeStartup";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "./serverRuntimeState.ts";
|
||||
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths.ts";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
|
||||
} from "./serverRuntimeState";
|
||||
import { WorkspacePaths } from "./workspace/Services/WorkspacePaths";
|
||||
import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths";
|
||||
|
||||
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
@@ -194,6 +193,9 @@ interface CliAuthLocationFlags {
|
||||
readonly devUrl?: Option.Option<URL>;
|
||||
}
|
||||
|
||||
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
|
||||
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
@@ -239,13 +241,12 @@ export const resolveServerConfig = (
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
|
||||
|
||||
const mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.fromUndefinedOr(bootstrap?.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
@@ -254,7 +255,7 @@ export const resolveServerConfig = (
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.fromUndefinedOr(bootstrap?.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
@@ -270,7 +271,7 @@ export const resolveServerConfig = (
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.fromUndefinedOr(bootstrap?.devUrl),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
@@ -279,7 +280,9 @@ export const resolveServerConfig = (
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.fromUndefinedOr(bootstrap?.t3Home),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.t3Home),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
@@ -294,41 +297,60 @@ export const resolveServerConfig = (
|
||||
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
|
||||
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
|
||||
const startupPresentation = options?.startupPresentation ?? "browser";
|
||||
const isHeadlessStartup = startupPresentation === "headless";
|
||||
const noBrowser = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
isHeadlessStartup ? Option.some(true) : Option.none(),
|
||||
normalizedFlags.noBrowser,
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.fromUndefinedOr(bootstrap?.noBrowser),
|
||||
const noBrowser =
|
||||
startupPresentation === "headless"
|
||||
? true
|
||||
: resolveBooleanFlag(
|
||||
normalizedFlags.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const desktopBootstrapToken = Option.getOrUndefined(
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.desktopBootstrapToken),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
);
|
||||
const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
|
||||
const autoBootstrapProjectFromCwd = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
|
||||
isHeadlessStartup ? Option.some(false) : Option.none(),
|
||||
normalizedFlags.autoBootstrapProjectFromCwd,
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.fromUndefinedOr(bootstrap?.autoBootstrapProjectFromCwd),
|
||||
const autoBootstrapProjectFromCwd =
|
||||
options?.forceAutoBootstrapProjectFromCwd ??
|
||||
(startupPresentation === "headless"
|
||||
? false
|
||||
: resolveBooleanFlag(
|
||||
normalizedFlags.autoBootstrapProjectFromCwd,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
));
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
normalizedFlags.logWebSocketEvents,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
() => mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.logWebSocketEvents,
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.fromUndefinedOr(bootstrap?.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
@@ -343,11 +365,19 @@ export const resolveServerConfig = (
|
||||
traceMaxFiles: env.traceMaxFiles,
|
||||
otlpTracesUrl:
|
||||
env.otlpTracesUrl ??
|
||||
bootstrap?.otlpTracesUrl ??
|
||||
Option.getOrUndefined(
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
|
||||
),
|
||||
) ??
|
||||
persistedObservabilitySettings.otlpTracesUrl,
|
||||
otlpMetricsUrl:
|
||||
env.otlpMetricsUrl ??
|
||||
bootstrap?.otlpMetricsUrl ??
|
||||
Option.getOrUndefined(
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
|
||||
),
|
||||
) ??
|
||||
persistedObservabilitySettings.otlpMetricsUrl,
|
||||
otlpExportIntervalMs: env.otlpExportIntervalMs,
|
||||
otlpServiceName: env.otlpServiceName,
|
||||
@@ -1000,10 +1030,10 @@ const projectAddCommand = Command.make("add", {
|
||||
}
|
||||
|
||||
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
|
||||
const projectId = ProjectId.make(crypto.randomUUID());
|
||||
const projectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||
yield* dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot,
|
||||
@@ -1041,7 +1071,7 @@ const projectRemoveCommand = Command.make("remove", {
|
||||
});
|
||||
yield* dispatch({
|
||||
type: "project.delete",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
@@ -1081,7 +1111,7 @@ const projectRenameCommand = Command.make("rename", {
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
title: nextTitle,
|
||||
});
|
||||
|
||||
@@ -15,9 +15,9 @@ import {
|
||||
normalizeCodexModelSlug,
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
} from "./codexAppServerManager.ts";
|
||||
} from "./codexAppServerManager";
|
||||
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.make(value);
|
||||
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
|
||||
|
||||
function createSendTurnHarness() {
|
||||
const manager = new CodexAppServerManager();
|
||||
@@ -111,9 +111,9 @@ function createPendingUserInputHarness() {
|
||||
},
|
||||
pendingUserInputs: new Map([
|
||||
[
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
requestId: ApprovalRequestId.make("req-user-input-1"),
|
||||
requestId: ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
jsonRpcId: 42,
|
||||
threadId: asThreadId("thread_1"),
|
||||
},
|
||||
@@ -470,154 +470,6 @@ describe("startSession", () => {
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("disposes an existing session before starting a replacement for the same thread", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const existingContext = {
|
||||
session: {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.set(asThreadId("thread-1"), existingContext);
|
||||
|
||||
const disposeSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
disposeSession: (
|
||||
context: typeof existingContext,
|
||||
options?: { readonly emitLifecycleEvent?: boolean },
|
||||
) => void;
|
||||
},
|
||||
"disposeSession",
|
||||
)
|
||||
.mockImplementation(() => {});
|
||||
const assertSupportedCodexCliVersion = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
assertSupportedCodexCliVersion: (input: {
|
||||
binaryPath: string;
|
||||
cwd: string;
|
||||
homePath?: string;
|
||||
}) => void;
|
||||
},
|
||||
"assertSupportedCodexCliVersion",
|
||||
)
|
||||
.mockImplementation(() => {});
|
||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
||||
throw new Error("cwd missing");
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
|
||||
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
|
||||
emitLifecycleEvent: false,
|
||||
});
|
||||
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
disposeSession.mockRestore();
|
||||
assertSupportedCodexCliVersion.mockRestore();
|
||||
processCwd.mockRestore();
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.clear();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
|
||||
it("continues replacement start when existing session disposal fails", async () => {
|
||||
const manager = new CodexAppServerManager();
|
||||
const existingContext = {
|
||||
session: {
|
||||
provider: "codex",
|
||||
status: "ready",
|
||||
threadId: asThreadId("thread-1"),
|
||||
runtimeMode: "full-access",
|
||||
createdAt: "2026-02-10T00:00:00.000Z",
|
||||
updatedAt: "2026-02-10T00:00:00.000Z",
|
||||
},
|
||||
};
|
||||
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.set(asThreadId("thread-1"), existingContext);
|
||||
|
||||
const disposeSession = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
disposeSession: (
|
||||
context: typeof existingContext,
|
||||
options?: { readonly emitLifecycleEvent?: boolean },
|
||||
) => void;
|
||||
},
|
||||
"disposeSession",
|
||||
)
|
||||
.mockImplementation(() => {
|
||||
throw new Error("dispose failed");
|
||||
});
|
||||
const assertSupportedCodexCliVersion = vi
|
||||
.spyOn(
|
||||
manager as unknown as {
|
||||
assertSupportedCodexCliVersion: (input: {
|
||||
binaryPath: string;
|
||||
cwd: string;
|
||||
homePath?: string;
|
||||
}) => void;
|
||||
},
|
||||
"assertSupportedCodexCliVersion",
|
||||
)
|
||||
.mockImplementation(() => {});
|
||||
const processCwd = vi.spyOn(process, "cwd").mockImplementation(() => {
|
||||
throw new Error("cwd missing");
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
|
||||
expect(disposeSession).toHaveBeenCalledWith(existingContext, {
|
||||
emitLifecycleEvent: false,
|
||||
});
|
||||
expect(assertSupportedCodexCliVersion).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
disposeSession.mockRestore();
|
||||
assertSupportedCodexCliVersion.mockRestore();
|
||||
processCwd.mockRestore();
|
||||
(
|
||||
manager as unknown as {
|
||||
sessions: Map<ThreadId, typeof existingContext>;
|
||||
}
|
||||
).sessions.clear();
|
||||
manager.stopAll();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("sendTurn", () => {
|
||||
@@ -891,7 +743,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: "All request methods",
|
||||
compat: "Keep current envelope",
|
||||
@@ -928,7 +780,7 @@ describe("respondToUserInput", () => {
|
||||
|
||||
await manager.respondToUserInput(
|
||||
asThreadId("thread_1"),
|
||||
ApprovalRequestId.make("req-user-input-1"),
|
||||
ApprovalRequestId.makeUnsafe("req-user-input-1"),
|
||||
{
|
||||
scope: [],
|
||||
},
|
||||
|
||||
@@ -19,22 +19,22 @@ import {
|
||||
ProviderInteractionMode,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { Effect, Context } from "effect";
|
||||
import { Effect, ServiceMap } from "effect";
|
||||
|
||||
import {
|
||||
formatCodexCliUpgradeMessage,
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion.ts";
|
||||
} from "./provider/codexCliVersion";
|
||||
import {
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
type CodexAccountSnapshot,
|
||||
} from "./provider/codexAccount.ts";
|
||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer.ts";
|
||||
} from "./provider/codexAccount";
|
||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
||||
|
||||
export { buildCodexInitializeParams } from "./provider/codexAppServer.ts";
|
||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount.ts";
|
||||
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -439,7 +439,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
|
||||
|
||||
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
|
||||
constructor(services?: Context.Context<never>) {
|
||||
constructor(services?: ServiceMap.ServiceMap<never>) {
|
||||
super();
|
||||
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
|
||||
}
|
||||
@@ -450,25 +450,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
let context: CodexSessionContext | undefined;
|
||||
|
||||
try {
|
||||
const existingContext = this.sessions.get(threadId);
|
||||
if (existingContext) {
|
||||
await Effect.logWarning("codex app-server replacing existing session", {
|
||||
threadId,
|
||||
existingStatus: existingContext.session.status,
|
||||
}).pipe(this.runPromise);
|
||||
try {
|
||||
this.disposeSession(existingContext, {
|
||||
emitLifecycleEvent: false,
|
||||
});
|
||||
} catch (error) {
|
||||
await Effect.logWarning("codex app-server failed to dispose existing session", {
|
||||
threadId,
|
||||
existingStatus: existingContext.session.status,
|
||||
cause: error instanceof Error ? error.message : String(error),
|
||||
}).pipe(this.runPromise);
|
||||
}
|
||||
}
|
||||
|
||||
const resolvedCwd = input.cwd ?? process.cwd();
|
||||
|
||||
const session: ProviderSession = {
|
||||
@@ -659,7 +640,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
this.stopSession(threadId);
|
||||
} else {
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId,
|
||||
@@ -758,7 +739,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
if (!turnIdRaw) {
|
||||
throw new Error("turn/start response did not include a turn id.");
|
||||
}
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
|
||||
this.updateSession(context, {
|
||||
status: "running",
|
||||
@@ -859,7 +840,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -898,7 +879,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
});
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -920,19 +901,6 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
return;
|
||||
}
|
||||
|
||||
this.disposeSession(context, {
|
||||
emitLifecycleEvent: true,
|
||||
});
|
||||
}
|
||||
|
||||
private disposeSession(
|
||||
context: CodexSessionContext,
|
||||
options?: { readonly emitLifecycleEvent?: boolean },
|
||||
): void {
|
||||
if (context.stopping) {
|
||||
return;
|
||||
}
|
||||
|
||||
context.stopping = true;
|
||||
|
||||
for (const pending of context.pending.values()) {
|
||||
@@ -953,10 +921,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
status: "closed",
|
||||
activeTurnId: undefined,
|
||||
});
|
||||
if (options?.emitLifecycleEvent !== false) {
|
||||
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
|
||||
}
|
||||
this.sessions.delete(context.session.threadId);
|
||||
this.emitLifecycleEvent(context, "session/closed", "Session stopped");
|
||||
this.sessions.delete(threadId);
|
||||
}
|
||||
|
||||
listSessions(): ProviderSession[] {
|
||||
@@ -1095,7 +1061,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
: undefined;
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1168,7 +1134,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const requestKind = this.requestKindForMethod(request.method);
|
||||
let requestId: ApprovalRequestId | undefined;
|
||||
if (requestKind) {
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
const pendingRequest: PendingApprovalRequest = {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1187,7 +1153,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
if (request.method === "item/tool/requestUserInput") {
|
||||
requestId = ApprovalRequestId.make(randomUUID());
|
||||
requestId = ApprovalRequestId.makeUnsafe(randomUUID());
|
||||
context.pendingUserInputs.set(requestId, {
|
||||
requestId,
|
||||
jsonRpcId: request.id,
|
||||
@@ -1198,7 +1164,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
}
|
||||
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "request",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1288,7 +1254,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitLifecycleEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "session",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1300,7 +1266,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
|
||||
private emitErrorEvent(context: CodexSessionContext, method: string, message: string): void {
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "error",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1316,7 +1282,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
message: string,
|
||||
): void {
|
||||
this.emitEvent({
|
||||
id: EventId.make(randomUUID()),
|
||||
id: EventId.makeUnsafe(randomUUID()),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: context.session.threadId,
|
||||
@@ -1375,7 +1341,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
const turns = turnsRaw.map((turnValue, index) => {
|
||||
const turn = this.readObject(turnValue);
|
||||
const turnIdRaw = this.readString(turn, "id") ?? `${threadIdRaw}:turn:${index + 1}`;
|
||||
const turnId = TurnId.make(turnIdRaw);
|
||||
const turnId = TurnId.makeUnsafe(turnIdRaw);
|
||||
const items = this.readArray(turn, "items") ?? [];
|
||||
return {
|
||||
id: turnId,
|
||||
@@ -1624,9 +1590,9 @@ function readResumeThreadId(input: {
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return brandIfNonEmpty(value, TurnId.make);
|
||||
return brandIfNonEmpty(value, TurnId.makeUnsafe);
|
||||
}
|
||||
|
||||
function toProviderItemId(value: string | undefined): ProviderItemId | undefined {
|
||||
return brandIfNonEmpty(value, ProviderItemId.make);
|
||||
return brandIfNonEmpty(value, ProviderItemId.makeUnsafe);
|
||||
}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ServerConfig
|
||||
*/
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
|
||||
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
|
||||
|
||||
export const DEFAULT_PORT = 3773;
|
||||
|
||||
@@ -24,7 +24,6 @@ export interface ServerDerivedPaths {
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly providerStatusCacheDir: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -77,13 +76,11 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
const attachmentsDir = join(stateDir, "attachments");
|
||||
const logsDir = join(stateDir, "logs");
|
||||
const providerLogsDir = join(logsDir, "provider");
|
||||
const providerStatusCacheDir = join(baseDir, "caches");
|
||||
return {
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
settingsPath: join(stateDir, "settings.json"),
|
||||
providerStatusCacheDir,
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
@@ -113,7 +110,6 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
|
||||
fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
|
||||
fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
|
||||
],
|
||||
@@ -124,7 +120,7 @@ export const ensureServerDirectories = Effect.fn(function* (derivedPaths: Server
|
||||
/**
|
||||
* ServerConfig - Service tag for server runtime configuration.
|
||||
*/
|
||||
export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShape>()(
|
||||
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
|
||||
"t3/config/ServerConfig",
|
||||
) {
|
||||
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Effect, FileSystem, Layer, Path, Random } from "effect";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
|
||||
import packageJson from "../../../package.json" with { type: "json" };
|
||||
import { version } from "../../../package.json" with { type: "json" };
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
|
||||
function platformOs(): ExecutionEnvironmentDescriptor["platform"]["os"] {
|
||||
@@ -64,7 +64,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
return generated;
|
||||
});
|
||||
|
||||
const environmentId = EnvironmentId.make(environmentIdRaw);
|
||||
const environmentId = EnvironmentId.makeUnsafe(environmentIdRaw);
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({
|
||||
cwdBaseName,
|
||||
@@ -77,7 +77,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
os: platformOs(),
|
||||
arch: platformArch(),
|
||||
},
|
||||
serverVersion: packageJson.version,
|
||||
serverVersion: version,
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
|
||||
@@ -51,13 +51,11 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
) {
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
catch: () => null,
|
||||
}).pipe(Effect.orElseSucceed(() => null));
|
||||
const result = yield* Effect.tryPromise(() =>
|
||||
runProcess(command, args, {
|
||||
allowNonZeroExit: true,
|
||||
}),
|
||||
).pipe(Effect.orElseSucceed(() => null));
|
||||
|
||||
if (!result || result.code !== 0) {
|
||||
return null;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
export interface ServerEnvironmentShape {
|
||||
@@ -7,6 +7,7 @@ export interface ServerEnvironmentShape {
|
||||
readonly getDescriptor: Effect.Effect<ExecutionEnvironmentDescriptor>;
|
||||
}
|
||||
|
||||
export class ServerEnvironment extends Context.Service<ServerEnvironment, ServerEnvironmentShape>()(
|
||||
"t3/environment/Services/ServerEnvironment",
|
||||
) {}
|
||||
export class ServerEnvironment extends ServiceMap.Service<
|
||||
ServerEnvironment,
|
||||
ServerEnvironmentShape
|
||||
>()("t3/environment/Services/ServerEnvironment") {}
|
||||
@@ -166,7 +166,6 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"--skip-git-repo-check",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
|
||||
@@ -40,24 +40,6 @@ function writeTextFile(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
/** Run a raw git command for test setup (not under test). */
|
||||
function git(
|
||||
cwd: string,
|
||||
@@ -237,10 +219,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
const seenChunks: string[][] = [];
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args.join(" ") !==
|
||||
"-c core.fsmonitor=false -c core.untrackedCache=false check-ignore --no-index -z --stdin"
|
||||
) {
|
||||
if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
@@ -273,35 +252,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
expect(result).toEqual(expectedPaths);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("listWorkspaceFiles disables fsmonitor and untracked cache helpers", () =>
|
||||
Effect.gen(function* () {
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
expect(input.args).toEqual([
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
]);
|
||||
return Effect.succeed({
|
||||
code: 0,
|
||||
stdout: "src/index.ts\0README.md\0",
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
});
|
||||
|
||||
const result = yield* core.listWorkspaceFiles("/virtual/repo");
|
||||
expect(result.paths).toEqual(["src/index.ts", "README.md"]);
|
||||
expect(result.truncated).toBe(false);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
// ── listGitBranches ──
|
||||
@@ -317,21 +267,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns isRepo: false for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
|
||||
const result = yield* (yield* GitCore).listBranches({ cwd: deletedDir });
|
||||
|
||||
expect(result.isRepo).toBe(false);
|
||||
expect(result.hasOriginRemote).toBe(false);
|
||||
expect(result.branches).toEqual([]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns the current branch with current: true", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
@@ -682,8 +617,8 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
|
||||
it.effect("refreshes upstream behind count after checkout when remote branch advanced", () =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* Effect.context<never>();
|
||||
const runPromise = Effect.runPromiseWith(context);
|
||||
const services = yield* Effect.services();
|
||||
const runPromise = Effect.runPromiseWith(services);
|
||||
|
||||
const remote = yield* makeTmpDir();
|
||||
const source = yield* makeTmpDir();
|
||||
@@ -826,7 +761,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("coalesces upstream refreshes across sibling worktrees on the same remote", () =>
|
||||
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
@@ -845,9 +780,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123" ? "origin/feature/pr-123\n" : "origin/main\n",
|
||||
);
|
||||
return ok("origin/main\n");
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
@@ -858,22 +791,10 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
expect(input.cwd).toBe("/repo");
|
||||
expect(input.args).toEqual([
|
||||
"--git-dir",
|
||||
"/repo/.git",
|
||||
"fetch",
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
"origin",
|
||||
]);
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
@@ -900,80 +821,70 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect(
|
||||
"briefly backs off failed upstream refreshes across sibling worktrees on one remote",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
|
||||
Effect.gen(function* () {
|
||||
const ok = (stdout = "") =>
|
||||
Effect.succeed({
|
||||
code: 0,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
});
|
||||
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "origin/feature/pr-123\n"
|
||||
: "origin/main\n",
|
||||
);
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "simulated fetch timeout",
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok(
|
||||
input.cwd === "/repo/worktrees/pr-123"
|
||||
? "# branch.head feature/pr-123\n# branch.upstream origin/feature/pr-123\n# branch.ab +0 -0\n"
|
||||
: "# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n",
|
||||
);
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
let fetchCount = 0;
|
||||
const core = yield* makeIsolatedGitCore((input) => {
|
||||
if (
|
||||
input.args[0] === "rev-parse" &&
|
||||
input.args[1] === "--abbrev-ref" &&
|
||||
input.args[2] === "--symbolic-full-name" &&
|
||||
input.args[3] === "@{upstream}"
|
||||
) {
|
||||
return ok("origin/main\n");
|
||||
}
|
||||
if (input.args[0] === "remote") {
|
||||
return ok("origin\n");
|
||||
}
|
||||
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
|
||||
return ok("/repo/.git\n");
|
||||
}
|
||||
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
|
||||
fetchCount += 1;
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
detail: "simulated fetch timeout",
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.status") {
|
||||
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
|
||||
}
|
||||
if (
|
||||
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
|
||||
input.operation === "GitCore.statusDetails.stagedNumstat"
|
||||
) {
|
||||
return ok();
|
||||
}
|
||||
if (input.operation === "GitCore.statusDetails.defaultRef") {
|
||||
return ok("refs/remotes/origin/main\n");
|
||||
}
|
||||
return Effect.fail(
|
||||
new GitCommandError({
|
||||
operation: input.operation,
|
||||
command: `git ${input.args.join(" ")}`,
|
||||
cwd: input.cwd,
|
||||
detail: "Unexpected git command in refresh failure cooldown test.",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
yield* core.statusDetails("/repo/worktrees/main");
|
||||
yield* core.statusDetails("/repo/worktrees/pr-123");
|
||||
expect(fetchCount).toBe(1);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("throws when branch does not exist", () =>
|
||||
@@ -1071,6 +982,7 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
"--quiet",
|
||||
"--no-tags",
|
||||
remoteName,
|
||||
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
|
||||
]);
|
||||
}),
|
||||
);
|
||||
@@ -1682,37 +1594,6 @@ it.layer(TestLayer)("git integration", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a non-repo status for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
const deletedDir = path.join(tmp, "deleted-repo");
|
||||
yield* makeDirectory(deletedDir);
|
||||
yield* removePath(deletedDir);
|
||||
const core = yield* GitCore;
|
||||
|
||||
const status = yield* core.statusDetails(deletedDir);
|
||||
const localStatus = yield* core.statusDetailsLocal(deletedDir);
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
expect(localStatus).toEqual(status);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("computes ahead count against base branch when no upstream is configured", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
|
||||
@@ -27,7 +27,6 @@ import {
|
||||
type ExecuteGitProgress,
|
||||
type GitCommitOptions,
|
||||
type GitCoreShape,
|
||||
type GitStatusDetails,
|
||||
type ExecuteGitInput,
|
||||
type ExecuteGitResult,
|
||||
} from "../Services/GitCore.ts";
|
||||
@@ -48,39 +47,23 @@ const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
|
||||
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
|
||||
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
|
||||
const WORKSPACE_GIT_HARDENED_CONFIG_ARGS = [
|
||||
"-c",
|
||||
"core.fsmonitor=false",
|
||||
"-c",
|
||||
"core.untrackedCache=false",
|
||||
] as const;
|
||||
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
|
||||
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
|
||||
const NON_REPOSITORY_STATUS_DETAILS = Object.freeze<GitStatusDetails>({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
upstreamRef: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
});
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusRemoteRefreshCacheKey extends Data.Class<{
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
gitCommonDir: string;
|
||||
upstreamRef: string;
|
||||
remoteName: string;
|
||||
upstreamBranch: string;
|
||||
}> {}
|
||||
|
||||
interface ExecuteGitOptions {
|
||||
@@ -370,16 +353,6 @@ function quoteGitCommand(args: ReadonlyArray<string>): string {
|
||||
return `git ${args.join(" ")}`;
|
||||
}
|
||||
|
||||
function isMissingGitCwdError(error: GitCommandError): boolean {
|
||||
const normalized = `${error.detail}\n${error.message}`.toLowerCase();
|
||||
return (
|
||||
normalized.includes("no such file or directory") ||
|
||||
normalized.includes("notfound: filesystem.access") ||
|
||||
normalized.includes("enoent") ||
|
||||
normalized.includes("not a directory")
|
||||
);
|
||||
}
|
||||
|
||||
function toGitCommandError(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
detail: string,
|
||||
@@ -917,16 +890,17 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
});
|
||||
|
||||
const fetchRemoteForStatus = (
|
||||
const fetchUpstreamRefForStatus = (
|
||||
gitCommonDir: string,
|
||||
remoteName: string,
|
||||
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
|
||||
): Effect.Effect<void, GitCommandError> => {
|
||||
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
|
||||
const fetchCwd =
|
||||
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
|
||||
return executeGit(
|
||||
"GitCore.fetchRemoteForStatus",
|
||||
"GitCore.fetchUpstreamRefForStatus",
|
||||
fetchCwd,
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName],
|
||||
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
|
||||
@@ -942,15 +916,20 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
|
||||
});
|
||||
|
||||
const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* (
|
||||
cacheKey: StatusRemoteRefreshCacheKey,
|
||||
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
|
||||
cacheKey: StatusUpstreamRefreshCacheKey,
|
||||
) {
|
||||
yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName);
|
||||
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
|
||||
upstreamRef: cacheKey.upstreamRef,
|
||||
remoteName: cacheKey.remoteName,
|
||||
upstreamBranch: cacheKey.upstreamBranch,
|
||||
});
|
||||
return true as const;
|
||||
});
|
||||
|
||||
const statusRemoteRefreshCache = yield* Cache.makeWith(refreshStatusRemoteCacheEntry, {
|
||||
const statusUpstreamRefreshCache = yield* Cache.makeWith({
|
||||
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
|
||||
lookup: refreshStatusUpstreamCacheEntry,
|
||||
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
|
||||
timeToLive: (exit) =>
|
||||
Exit.isSuccess(exit)
|
||||
@@ -965,10 +944,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
if (!upstream) return;
|
||||
const gitCommonDir = yield* resolveGitCommonDir(cwd);
|
||||
yield* Cache.get(
|
||||
statusRemoteRefreshCache,
|
||||
new StatusRemoteRefreshCacheKey({
|
||||
statusUpstreamRefreshCache,
|
||||
new StatusUpstreamRefreshCacheKey({
|
||||
gitCommonDir,
|
||||
upstreamRef: upstream.upstreamRef,
|
||||
remoteName: upstream.remoteName,
|
||||
upstreamBranch: upstream.upstreamBranch,
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1204,11 +1185,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(Effect.catchIf(isMissingGitCwdError, () => Effect.succeed(null)));
|
||||
|
||||
if (statusResult === null) {
|
||||
return NON_REPOSITORY_STATUS_DETAILS;
|
||||
}
|
||||
);
|
||||
|
||||
if (statusResult.code !== 0) {
|
||||
const stderr = statusResult.stderr.trim();
|
||||
@@ -1340,10 +1317,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
);
|
||||
|
||||
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () => Effect.void),
|
||||
Effect.ignoreCause({ log: true }),
|
||||
);
|
||||
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
|
||||
return yield* readStatusDetailsLocal(cwd);
|
||||
});
|
||||
|
||||
@@ -1645,14 +1619,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
executeGit(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
[
|
||||
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
],
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
{
|
||||
allowNonZeroExit: true,
|
||||
timeoutMs: 20_000,
|
||||
@@ -1670,14 +1637,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
createGitCommandError(
|
||||
"GitCore.listWorkspaceFiles",
|
||||
cwd,
|
||||
[
|
||||
...WORKSPACE_GIT_HARDENED_CONFIG_ARGS,
|
||||
"ls-files",
|
||||
"--cached",
|
||||
"--others",
|
||||
"--exclude-standard",
|
||||
"-z",
|
||||
],
|
||||
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
|
||||
),
|
||||
),
|
||||
@@ -1697,7 +1657,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
const result = yield* executeGit(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
{
|
||||
stdin: `${chunk.join("\0")}\0`,
|
||||
allowNonZeroExit: true,
|
||||
@@ -1711,7 +1671,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
return yield* createGitCommandError(
|
||||
"GitCore.filterIgnoredPaths",
|
||||
cwd,
|
||||
[...WORKSPACE_GIT_HARDENED_CONFIG_ARGS, "check-ignore", "--no-index", "-z", "--stdin"],
|
||||
["check-ignore", "--no-index", "-z", "--stdin"],
|
||||
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
|
||||
);
|
||||
}
|
||||
@@ -1740,16 +1700,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
timeoutMs: 10_000,
|
||||
allowNonZeroExit: true,
|
||||
},
|
||||
).pipe(
|
||||
Effect.catchIf(isMissingGitCwdError, () =>
|
||||
Effect.succeed({
|
||||
code: 128,
|
||||
stdout: "",
|
||||
stderr: "fatal: not a git repository",
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
if (localBranchResult.code !== 0) {
|
||||
@@ -2032,7 +1982,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
|
||||
"GitCore.removeWorktree",
|
||||
input.cwd,
|
||||
args,
|
||||
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error.message}`,
|
||||
`${commandLabel(args)} failed (cwd: ${input.cwd}): ${error instanceof Error ? error.message : String(error)}`,
|
||||
error,
|
||||
),
|
||||
),
|
||||
|
||||
@@ -6,7 +6,7 @@ vi.mock("../../processRunner", () => ({
|
||||
runProcess: vi.fn(),
|
||||
}));
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { GitHubCliLive } from "./GitHubCli.ts";
|
||||
|
||||
@@ -76,105 +76,6 @@ layer("GitHubCliLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("trims pull request fields decoded from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify({
|
||||
number: 42,
|
||||
title: " Add PR thread creation \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/42 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/pr-threads\t",
|
||||
state: "OPEN",
|
||||
mergedAt: null,
|
||||
isCrossRepository: true,
|
||||
headRepository: {
|
||||
nameWithOwner: " octocat/codething-mvp ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " octocat ",
|
||||
},
|
||||
}),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.getPullRequest({
|
||||
cwd: "/repo",
|
||||
reference: "#42",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, {
|
||||
number: 42,
|
||||
title: "Add PR thread creation",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/42",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-threads",
|
||||
state: "open",
|
||||
isCrossRepository: true,
|
||||
headRepositoryNameWithOwner: "octocat/codething-mvp",
|
||||
headRepositoryOwnerLogin: "octocat",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips invalid entries when parsing pr lists", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
stdout: JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 43,
|
||||
title: " Valid PR ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/43 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: " feature/pr-list ",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
stderr: "",
|
||||
code: 0,
|
||||
signal: null,
|
||||
timedOut: false,
|
||||
});
|
||||
|
||||
const result = yield* Effect.gen(function* () {
|
||||
const gh = yield* GitHubCli;
|
||||
return yield* gh.listOpenPullRequests({
|
||||
cwd: "/repo",
|
||||
headSelector: "feature/pr-list",
|
||||
});
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(result, [
|
||||
{
|
||||
number: 43,
|
||||
title: "Valid PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/43",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/pr-list",
|
||||
state: "open",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads repository clone URLs", () =>
|
||||
Effect.gen(function* () {
|
||||
mockedRunProcess.mockResolvedValueOnce({
|
||||
|
||||
@@ -1,18 +1,14 @@
|
||||
import { Effect, Layer, Result, Schema, SchemaIssue } from "effect";
|
||||
import { TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
|
||||
import { runProcess } from "../../processRunner.ts";
|
||||
import { runProcess } from "../../processRunner";
|
||||
import { GitHubCliError } from "@t3tools/contracts";
|
||||
import {
|
||||
GitHubCli,
|
||||
type GitHubRepositoryCloneUrls,
|
||||
type GitHubCliShape,
|
||||
type GitHubPullRequestSummary,
|
||||
} from "../Services/GitHubCli.ts";
|
||||
import {
|
||||
decodeGitHubPullRequestJson,
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
|
||||
@@ -67,12 +63,76 @@ function normalizeGitHubCliError(operation: "execute" | "stdout", error: unknown
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const mergedAt = input.mergedAt;
|
||||
const state = input.state;
|
||||
if ((typeof mergedAt === "string" && mergedAt.trim().length > 0) || state === "MERGED") {
|
||||
return "merged";
|
||||
}
|
||||
if (state === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
const RawGitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
const RawGitHubRepositoryCloneUrlsSchema = Schema.Struct({
|
||||
nameWithOwner: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
sshUrl: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
function normalizePullRequestSummary(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubPullRequestSchema>,
|
||||
): GitHubPullRequestSummary {
|
||||
const headRepositoryNameWithOwner = raw.headRepository?.nameWithOwner ?? null;
|
||||
const headRepositoryOwnerLogin =
|
||||
raw.headRepositoryOwner?.login ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizePullRequestState(raw),
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeRepositoryCloneUrls(
|
||||
raw: Schema.Schema.Type<typeof RawGitHubRepositoryCloneUrlsSchema>,
|
||||
): GitHubRepositoryCloneUrls {
|
||||
@@ -94,7 +154,7 @@ function decodeGitHubJson<S extends Schema.Top>(
|
||||
(error) =>
|
||||
new GitHubCliError({
|
||||
operation,
|
||||
detail: `${invalidDetail}: ${SchemaIssue.makeFormatterDefault()(error.issue)}`,
|
||||
detail: error instanceof Error ? `${invalidDetail}: ${error.message}` : invalidDetail,
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
@@ -108,6 +168,7 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
runProcess("gh", input.args, {
|
||||
cwd: input.cwd,
|
||||
timeoutMs: input.timeoutMs ?? DEFAULT_TIMEOUT_MS,
|
||||
shell: false,
|
||||
}),
|
||||
catch: (error) => normalizeGitHubCliError("execute", error),
|
||||
});
|
||||
@@ -134,24 +195,14 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
Effect.flatMap((raw) =>
|
||||
raw.length === 0
|
||||
? Effect.succeed([])
|
||||
: Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "listOpenPullRequests",
|
||||
detail: `GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
decoded.success.map(({ updatedAt: _updatedAt, ...summary }) => summary),
|
||||
);
|
||||
}),
|
||||
: decodeGitHubJson(
|
||||
raw,
|
||||
Schema.Array(RawGitHubPullRequestSchema),
|
||||
"listOpenPullRequests",
|
||||
"GitHub CLI returned invalid PR list JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map((pullRequests) => pullRequests.map(normalizePullRequestSummary)),
|
||||
),
|
||||
getPullRequest: (input) =>
|
||||
execute({
|
||||
@@ -166,24 +217,14 @@ const makeGitHubCli = Effect.sync(() => {
|
||||
}).pipe(
|
||||
Effect.map((result) => result.stdout.trim()),
|
||||
Effect.flatMap((raw) =>
|
||||
Effect.sync(() => decodeGitHubPullRequestJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
new GitHubCliError({
|
||||
operation: "getPullRequest",
|
||||
detail: `GitHub CLI returned invalid pull request JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
cause: decoded.failure,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return Effect.succeed(
|
||||
(({ updatedAt: _updatedAt, ...summary }) => summary)(decoded.success),
|
||||
);
|
||||
}),
|
||||
decodeGitHubJson(
|
||||
raw,
|
||||
RawGitHubPullRequestSchema,
|
||||
"getPullRequest",
|
||||
"GitHub CLI returned invalid pull request JSON.",
|
||||
),
|
||||
),
|
||||
Effect.map(normalizePullRequestSummary),
|
||||
),
|
||||
getRepositoryCloneUrls: (input) =>
|
||||
execute({
|
||||
|
||||
@@ -186,24 +186,6 @@ function makeTempDir(
|
||||
});
|
||||
}
|
||||
|
||||
function removePath(
|
||||
targetPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.remove(targetPath, { recursive: true, force: true });
|
||||
});
|
||||
}
|
||||
|
||||
function makeDirectory(
|
||||
dirPath: string,
|
||||
): Effect.Effect<void, PlatformError.PlatformError, FileSystem.FileSystem> {
|
||||
return Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
yield* fileSystem.makeDirectory(dirPath, { recursive: true });
|
||||
});
|
||||
}
|
||||
|
||||
function runGit(
|
||||
cwd: string,
|
||||
args: readonly string[],
|
||||
@@ -712,144 +694,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status trims PR metadata returned by gh before publishing it", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-trimmed-pr"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-trimmed-pr"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 14,
|
||||
title: " Existing PR title \n",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/14 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-trimmed-pr\t",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 14,
|
||||
title: "Existing PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/14",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-trimmed-pr",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status ignores invalid gh pr list entries and keeps valid ones", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-valid-pr-entry"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-valid-pr-entry"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 0,
|
||||
title: "invalid",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/0",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/invalid",
|
||||
},
|
||||
{
|
||||
number: 15,
|
||||
title: " Valid PR title ",
|
||||
url: " https://github.com/pingdotgg/codething-mvp/pull/15 ",
|
||||
baseRefName: " main ",
|
||||
headRefName: "\tfeature/status-valid-pr-entry\t",
|
||||
headRepository: {
|
||||
nameWithOwner: " ",
|
||||
},
|
||||
headRepositoryOwner: {
|
||||
login: " ",
|
||||
},
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 15,
|
||||
title: "Valid PR title",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/15",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-valid-pr-entry",
|
||||
state: "open",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status preserves lowercase merged and closed PR states from gh json", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
yield* initRepo(repoDir);
|
||||
yield* runGit(repoDir, ["checkout", "-b", "feature/status-lowercase-state"]);
|
||||
const remoteDir = yield* createBareRemote();
|
||||
yield* runGit(repoDir, ["remote", "add", "origin", remoteDir]);
|
||||
yield* runGit(repoDir, ["push", "-u", "origin", "feature/status-lowercase-state"]);
|
||||
|
||||
const { manager } = yield* makeManager({
|
||||
ghScenario: {
|
||||
prListSequence: [
|
||||
JSON.stringify([
|
||||
{
|
||||
number: 16,
|
||||
title: "Closed PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/16",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "closed",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
},
|
||||
{
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseRefName: "main",
|
||||
headRefName: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
updatedAt: "2026-01-02T00:00:00.000Z",
|
||||
},
|
||||
]),
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const status = yield* manager.status({ cwd: repoDir });
|
||||
|
||||
expect(status.pr).toEqual({
|
||||
number: 17,
|
||||
title: "Merged PR",
|
||||
url: "https://github.com/pingdotgg/codething-mvp/pull/17",
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/status-lowercase-state",
|
||||
state: "merged",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for non-git directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeTempDir("t3code-git-manager-non-repo-");
|
||||
@@ -876,35 +720,6 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status returns an explicit non-repo result for deleted directories", () =>
|
||||
Effect.gen(function* () {
|
||||
const rootDir = yield* makeTempDir("t3code-git-manager-missing-dir-");
|
||||
const cwd = path.join(rootDir, "deleted-repo");
|
||||
yield* makeDirectory(cwd);
|
||||
yield* removePath(cwd);
|
||||
const { manager } = yield* makeManager();
|
||||
|
||||
const status = yield* manager.status({ cwd });
|
||||
|
||||
expect(status).toEqual({
|
||||
isRepo: false,
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: false,
|
||||
branch: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("status briefly caches repeated lookups for the same cwd", () =>
|
||||
Effect.gen(function* () {
|
||||
const repoDir = yield* makeTempDir("t3code-git-manager-");
|
||||
|
||||
@@ -1,18 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import {
|
||||
Cache,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
Ref,
|
||||
Result,
|
||||
} from "effect";
|
||||
import { Cache, Duration, Effect, Exit, FileSystem, Layer, Option, Path, Ref } from "effect";
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitActionProgressPhase,
|
||||
@@ -38,18 +27,13 @@ import {
|
||||
type GitManagerShape,
|
||||
type GitRunStackedActionOptions,
|
||||
} from "../Services/GitManager.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import type { GitStatusDetails } from "../Services/GitCore.ts";
|
||||
import { GitCore, GitStatusDetails } from "../Services/GitCore.ts";
|
||||
import { GitHubCli, type GitHubPullRequestSummary } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ProjectSetupScriptRunner } from "../../project/Services/ProjectSetupScriptRunner.ts";
|
||||
import { extractBranchNameFromRemoteRef } from "../remoteRefs.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
import {
|
||||
decodeGitHubPullRequestListJson,
|
||||
formatGitHubJsonDecodeError,
|
||||
} from "../githubPullRequests.ts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
@@ -256,6 +240,85 @@ function matchesBranchHeadContext(
|
||||
return true;
|
||||
}
|
||||
|
||||
function parsePullRequestList(raw: unknown): PullRequestInfo[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
const parsed: PullRequestInfo[] = [];
|
||||
for (const entry of raw) {
|
||||
if (!entry || typeof entry !== "object") continue;
|
||||
const record = entry as Record<string, unknown>;
|
||||
const number = record.number;
|
||||
const title = record.title;
|
||||
const url = record.url;
|
||||
const baseRefName = record.baseRefName;
|
||||
const headRefName = record.headRefName;
|
||||
const state = record.state;
|
||||
const mergedAt = record.mergedAt;
|
||||
const updatedAt = record.updatedAt;
|
||||
const isCrossRepository = record.isCrossRepository;
|
||||
const headRepositoryRecord =
|
||||
typeof record.headRepository === "object" && record.headRepository !== null
|
||||
? (record.headRepository as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryOwnerRecord =
|
||||
typeof record.headRepositoryOwner === "object" && record.headRepositoryOwner !== null
|
||||
? (record.headRepositoryOwner as Record<string, unknown>)
|
||||
: null;
|
||||
const headRepositoryNameWithOwner =
|
||||
typeof record.headRepositoryNameWithOwner === "string"
|
||||
? record.headRepositoryNameWithOwner
|
||||
: typeof headRepositoryRecord?.nameWithOwner === "string"
|
||||
? headRepositoryRecord.nameWithOwner
|
||||
: null;
|
||||
const headRepositoryOwnerLogin =
|
||||
typeof record.headRepositoryOwnerLogin === "string"
|
||||
? record.headRepositoryOwnerLogin
|
||||
: typeof headRepositoryOwnerRecord?.login === "string"
|
||||
? headRepositoryOwnerRecord.login
|
||||
: null;
|
||||
if (typeof number !== "number" || !Number.isInteger(number) || number <= 0) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
typeof title !== "string" ||
|
||||
typeof url !== "string" ||
|
||||
typeof baseRefName !== "string" ||
|
||||
typeof headRefName !== "string"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let normalizedState: "open" | "closed" | "merged";
|
||||
if (
|
||||
(typeof mergedAt === "string" && mergedAt.trim().length > 0) ||
|
||||
state === "MERGED" ||
|
||||
state === "merged"
|
||||
) {
|
||||
normalizedState = "merged";
|
||||
} else if (state === "OPEN" || state === "open" || state === undefined || state === null) {
|
||||
normalizedState = "open";
|
||||
} else if (state === "CLOSED" || state === "closed") {
|
||||
normalizedState = "closed";
|
||||
} else {
|
||||
continue;
|
||||
}
|
||||
|
||||
parsed.push({
|
||||
number,
|
||||
title,
|
||||
url,
|
||||
baseRefName,
|
||||
headRefName,
|
||||
state: normalizedState,
|
||||
updatedAt: typeof updatedAt === "string" && updatedAt.trim().length > 0 ? updatedAt : null,
|
||||
...(typeof isCrossRepository === "boolean" ? { isCrossRepository } : {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
});
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function toPullRequestInfo(summary: GitHubPullRequestSummary): PullRequestInfo {
|
||||
return {
|
||||
number: summary.number,
|
||||
@@ -668,8 +731,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
workingTree: details.workingTree,
|
||||
} satisfies GitStatusLocalResult;
|
||||
});
|
||||
const localStatusResultCache = yield* Cache.makeWith(readLocalStatus, {
|
||||
const localStatusResultCache = yield* Cache.makeWith({
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
lookup: readLocalStatus,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateLocalStatusResultCache = (cwd: string) =>
|
||||
@@ -700,8 +764,9 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
pr,
|
||||
} satisfies GitStatusRemoteResult;
|
||||
});
|
||||
const remoteStatusResultCache = yield* Cache.makeWith(readRemoteStatus, {
|
||||
const remoteStatusResultCache = yield* Cache.makeWith({
|
||||
capacity: STATUS_RESULT_CACHE_CAPACITY,
|
||||
lookup: readRemoteStatus,
|
||||
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_RESULT_CACHE_TTL : Duration.zero),
|
||||
});
|
||||
const invalidateRemoteStatusResultCache = (cwd: string) =>
|
||||
@@ -884,23 +949,13 @@ export const makeGitManager = Effect.fn("makeGitManager")(function* () {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pullRequests = yield* Effect.sync(() => decodeGitHubPullRequestListJson(raw)).pipe(
|
||||
Effect.flatMap((decoded) => {
|
||||
if (!Result.isSuccess(decoded)) {
|
||||
return Effect.fail(
|
||||
gitManagerError(
|
||||
"findLatestPr",
|
||||
`GitHub CLI returned invalid PR list JSON: ${formatGitHubJsonDecodeError(decoded.failure)}`,
|
||||
decoded.failure,
|
||||
),
|
||||
);
|
||||
}
|
||||
const parsedJson = yield* Effect.try({
|
||||
try: () => JSON.parse(raw) as unknown,
|
||||
catch: (cause) =>
|
||||
gitManagerError("findLatestPr", "GitHub CLI returned invalid PR list JSON.", cause),
|
||||
});
|
||||
|
||||
return Effect.succeed(decoded.success);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const pr of pullRequests) {
|
||||
for (const pr of parsePullRequestList(parsedJson)) {
|
||||
if (!matchesBranchHeadContext(pr, headContext)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
*
|
||||
* @module RoutingTextGeneration
|
||||
*/
|
||||
import { Effect, Layer, Context } from "effect";
|
||||
import { Effect, Layer, ServiceMap } from "effect";
|
||||
|
||||
import {
|
||||
TextGeneration,
|
||||
@@ -23,11 +23,11 @@ import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
// Internal service tags so both concrete layers can coexist.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class CodexTextGen extends Context.Service<CodexTextGen, TextGenerationShape>()(
|
||||
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
|
||||
) {}
|
||||
|
||||
class ClaudeTextGen extends Context.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
|
||||
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
|
||||
) {}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module GitCore
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type {
|
||||
GitCheckoutInput,
|
||||
@@ -310,4 +310,6 @@ export interface GitCoreShape {
|
||||
/**
|
||||
* GitCore - Service tag for low-level Git repository operations.
|
||||
*/
|
||||
export class GitCore extends Context.Service<GitCore, GitCoreShape>()("t3/git/Services/GitCore") {}
|
||||
export class GitCore extends ServiceMap.Service<GitCore, GitCoreShape>()(
|
||||
"t3/git/Services/GitCore",
|
||||
) {}
|
||||
@@ -5,10 +5,10 @@
|
||||
*
|
||||
* @module GitHubCli
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { ProcessRunResult } from "../../processRunner.ts";
|
||||
import type { ProcessRunResult } from "../../processRunner";
|
||||
import type { GitHubCliError } from "@t3tools/contracts";
|
||||
|
||||
export interface GitHubPullRequestSummary {
|
||||
@@ -98,6 +98,6 @@ export interface GitHubCliShape {
|
||||
/**
|
||||
* GitHubCli - Service tag for GitHub CLI process execution.
|
||||
*/
|
||||
export class GitHubCli extends Context.Service<GitHubCli, GitHubCliShape>()(
|
||||
export class GitHubCli extends ServiceMap.Service<GitHubCli, GitHubCliShape>()(
|
||||
"t3/git/Services/GitHubCli",
|
||||
) {}
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
GitStatusInput,
|
||||
GitStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { GitManagerServiceError } from "@t3tools/contracts";
|
||||
|
||||
@@ -99,6 +99,6 @@ export interface GitManagerShape {
|
||||
/**
|
||||
* GitManager - Service tag for stacked Git workflow orchestration.
|
||||
*/
|
||||
export class GitManager extends Context.Service<GitManager, GitManagerShape>()(
|
||||
export class GitManager extends ServiceMap.Service<GitManager, GitManagerShape>()(
|
||||
"t3/git/Services/GitManager",
|
||||
) {}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect, Stream } from "effect";
|
||||
import type {
|
||||
GitManagerServiceError,
|
||||
@@ -21,7 +21,7 @@ export interface GitStatusBroadcasterShape {
|
||||
) => Stream.Stream<GitStatusStreamEvent, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitStatusBroadcaster extends Context.Service<
|
||||
export class GitStatusBroadcaster extends ServiceMap.Service<
|
||||
GitStatusBroadcaster,
|
||||
GitStatusBroadcasterShape
|
||||
>()("t3/git/Services/GitStatusBroadcaster") {}
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module TextGeneration
|
||||
*/
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
@@ -118,6 +118,6 @@ export interface TextGenerationShape {
|
||||
/**
|
||||
* TextGeneration - Service tag for commit and PR text generation.
|
||||
*/
|
||||
export class TextGeneration extends Context.Service<TextGeneration, TextGenerationShape>()(
|
||||
export class TextGeneration extends ServiceMap.Service<TextGeneration, TextGenerationShape>()(
|
||||
"t3/git/Services/TextGeneration",
|
||||
) {}
|
||||
@@ -1,128 +0,0 @@
|
||||
import { Cause, Exit, Result, Schema } from "effect";
|
||||
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export interface NormalizedGitHubPullRequestRecord {
|
||||
readonly number: number;
|
||||
readonly title: string;
|
||||
readonly url: string;
|
||||
readonly baseRefName: string;
|
||||
readonly headRefName: string;
|
||||
readonly state: "open" | "closed" | "merged";
|
||||
readonly updatedAt: string | null;
|
||||
readonly isCrossRepository?: boolean;
|
||||
readonly headRepositoryNameWithOwner?: string | null;
|
||||
readonly headRepositoryOwnerLogin?: string | null;
|
||||
}
|
||||
|
||||
const GitHubPullRequestSchema = Schema.Struct({
|
||||
number: PositiveInt,
|
||||
title: TrimmedNonEmptyString,
|
||||
url: TrimmedNonEmptyString,
|
||||
baseRefName: TrimmedNonEmptyString,
|
||||
headRefName: TrimmedNonEmptyString,
|
||||
state: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
mergedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
updatedAt: Schema.optional(Schema.NullOr(Schema.String)),
|
||||
isCrossRepository: Schema.optional(Schema.Boolean),
|
||||
headRepository: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
nameWithOwner: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
headRepositoryOwner: Schema.optional(
|
||||
Schema.NullOr(
|
||||
Schema.Struct({
|
||||
login: Schema.String,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
|
||||
function trimOptionalString(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim() ?? "";
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestState(input: {
|
||||
state?: string | null | undefined;
|
||||
mergedAt?: string | null | undefined;
|
||||
}): "open" | "closed" | "merged" {
|
||||
const normalizedState = input.state?.trim().toUpperCase();
|
||||
if (
|
||||
(typeof input.mergedAt === "string" && input.mergedAt.trim().length > 0) ||
|
||||
normalizedState === "MERGED"
|
||||
) {
|
||||
return "merged";
|
||||
}
|
||||
if (normalizedState === "CLOSED") {
|
||||
return "closed";
|
||||
}
|
||||
return "open";
|
||||
}
|
||||
|
||||
function normalizeGitHubPullRequestRecord(
|
||||
raw: Schema.Schema.Type<typeof GitHubPullRequestSchema>,
|
||||
): NormalizedGitHubPullRequestRecord {
|
||||
const headRepositoryNameWithOwner = trimOptionalString(raw.headRepository?.nameWithOwner);
|
||||
const headRepositoryOwnerLogin =
|
||||
trimOptionalString(raw.headRepositoryOwner?.login) ??
|
||||
(typeof headRepositoryNameWithOwner === "string" && headRepositoryNameWithOwner.includes("/")
|
||||
? (headRepositoryNameWithOwner.split("/")[0] ?? null)
|
||||
: null);
|
||||
|
||||
return {
|
||||
number: raw.number,
|
||||
title: raw.title,
|
||||
url: raw.url,
|
||||
baseRefName: raw.baseRefName,
|
||||
headRefName: raw.headRefName,
|
||||
state: normalizeGitHubPullRequestState(raw),
|
||||
updatedAt:
|
||||
typeof raw.updatedAt === "string" && raw.updatedAt.trim().length > 0 ? raw.updatedAt : null,
|
||||
...(typeof raw.isCrossRepository === "boolean"
|
||||
? { isCrossRepository: raw.isCrossRepository }
|
||||
: {}),
|
||||
...(headRepositoryNameWithOwner ? { headRepositoryNameWithOwner } : {}),
|
||||
...(headRepositoryOwnerLogin ? { headRepositoryOwnerLogin } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const decodeGitHubPullRequestList = decodeJsonResult(Schema.Array(Schema.Unknown));
|
||||
const decodeGitHubPullRequest = decodeJsonResult(GitHubPullRequestSchema);
|
||||
const decodeGitHubPullRequestEntry = Schema.decodeUnknownExit(GitHubPullRequestSchema);
|
||||
|
||||
export const formatGitHubJsonDecodeError = formatSchemaError;
|
||||
|
||||
export function decodeGitHubPullRequestListJson(
|
||||
raw: string,
|
||||
): Result.Result<
|
||||
ReadonlyArray<NormalizedGitHubPullRequestRecord>,
|
||||
Cause.Cause<Schema.SchemaError>
|
||||
> {
|
||||
const result = decodeGitHubPullRequestList(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
const pullRequests: NormalizedGitHubPullRequestRecord[] = [];
|
||||
for (const entry of result.success) {
|
||||
const decodedEntry = decodeGitHubPullRequestEntry(entry);
|
||||
if (Exit.isFailure(decodedEntry)) {
|
||||
continue;
|
||||
}
|
||||
pullRequests.push(normalizeGitHubPullRequestRecord(decodedEntry.value));
|
||||
}
|
||||
return Result.succeed(pullRequests);
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
|
||||
export function decodeGitHubPullRequestJson(
|
||||
raw: string,
|
||||
): Result.Result<NormalizedGitHubPullRequestRecord, Cause.Cause<Schema.SchemaError>> {
|
||||
const result = decodeGitHubPullRequest(raw);
|
||||
if (Result.isSuccess(result)) {
|
||||
return Result.succeed(normalizeGitHubPullRequestRecord(result.success));
|
||||
}
|
||||
return Result.fail(result.failure);
|
||||
}
|
||||
@@ -15,12 +15,12 @@ import {
|
||||
ATTACHMENTS_ROUTE_PREFIX,
|
||||
normalizeAttachmentRelativePath,
|
||||
resolveAttachmentRelativePath,
|
||||
} from "./attachmentPaths.ts";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore.ts";
|
||||
import { resolveStaticDir, ServerConfig } from "./config.ts";
|
||||
} from "./attachmentPaths";
|
||||
import { resolveAttachmentPathById } from "./attachmentStore";
|
||||
import { resolveStaticDir, ServerConfig } from "./config";
|
||||
import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
|
||||
import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver.ts";
|
||||
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
|
||||
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
|
||||
import { respondToAuthError } from "./auth/http.ts";
|
||||
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
|
||||
@@ -226,7 +226,6 @@ export const staticAndDevRouteLayer = HttpRouter.add(
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
const url = HttpServerRequest.toURL(request);
|
||||
|
||||
if (Option.isNone(url)) {
|
||||
return HttpServerResponse.text("Bad Request", { status: 400 });
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { assertFailure } from "@effect/vitest/utils";
|
||||
import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { ServerConfig } from "./config";
|
||||
|
||||
import {
|
||||
DEFAULT_KEYBINDINGS,
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
compileResolvedKeybindingRule,
|
||||
compileResolvedKeybindingsConfig,
|
||||
parseKeybindingShortcut,
|
||||
} from "./keybindings.ts";
|
||||
} from "./keybindings";
|
||||
import { KeybindingsConfigError } from "@t3tools/contracts";
|
||||
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
THREAD_JUMP_KEYBINDING_COMMANDS,
|
||||
type ServerConfigIssue,
|
||||
} from "@t3tools/contracts";
|
||||
import type { Mutable } from "effect/Types";
|
||||
import { Mutable } from "effect/Types";
|
||||
import {
|
||||
Array,
|
||||
Cache,
|
||||
@@ -39,12 +39,12 @@ import {
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
Ref,
|
||||
Context,
|
||||
ServiceMap,
|
||||
Scope,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config.ts";
|
||||
import { ServerConfig } from "./config";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
type WhenToken =
|
||||
@@ -61,7 +61,6 @@ export const DEFAULT_KEYBINDINGS: ReadonlyArray<KeybindingRule> = [
|
||||
{ key: "mod+n", command: "terminal.new", when: "terminalFocus" },
|
||||
{ key: "mod+w", command: "terminal.close", when: "terminalFocus" },
|
||||
{ key: "mod+d", command: "diff.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+k", command: "commandPalette.toggle", when: "!terminalFocus" },
|
||||
{ key: "mod+n", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+o", command: "chat.new", when: "!terminalFocus" },
|
||||
{ key: "mod+shift+n", command: "chat.newLocal", when: "!terminalFocus" },
|
||||
@@ -522,7 +521,7 @@ export interface KeybindingsShape {
|
||||
/**
|
||||
* Keybindings - Service tag for keybinding configuration operations.
|
||||
*/
|
||||
export class Keybindings extends Context.Service<Keybindings, KeybindingsShape>()(
|
||||
export class Keybindings extends ServiceMap.Service<Keybindings, KeybindingsShape>()(
|
||||
"t3/keybindings",
|
||||
) {}
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import type * as Exit from "effect/Exit";
|
||||
import { Effect, Option, Tracer } from "effect";
|
||||
|
||||
import { spanToTraceRecord } from "./TraceRecord.ts";
|
||||
import type { EffectTraceRecord } from "./TraceRecord.ts";
|
||||
import { EffectTraceRecord, spanToTraceRecord } from "./TraceRecord.ts";
|
||||
import { makeTraceSink, type TraceSink } from "./TraceSink.ts";
|
||||
|
||||
export interface LocalFileTracerOptions {
|
||||
@@ -28,16 +27,12 @@ class LocalFileSpan implements Tracer.Span {
|
||||
status: Tracer.SpanStatus;
|
||||
attributes: Map<string, unknown>;
|
||||
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
|
||||
private readonly delegate: Tracer.Span;
|
||||
private readonly push: (record: EffectTraceRecord) => void;
|
||||
|
||||
constructor(
|
||||
options: Parameters<Tracer.Tracer["span"]>[0],
|
||||
delegate: Tracer.Span,
|
||||
push: (record: EffectTraceRecord) => void,
|
||||
private readonly delegate: Tracer.Span,
|
||||
private readonly push: (record: EffectTraceRecord) => void,
|
||||
) {
|
||||
this.delegate = delegate;
|
||||
this.push = push;
|
||||
this.name = delegate.name;
|
||||
this.spanId = delegate.spanId;
|
||||
this.traceId = delegate.traceId;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Context } from "effect";
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
|
||||
import type { TraceRecord } from "../TraceRecord.ts";
|
||||
@@ -7,7 +7,7 @@ export interface BrowserTraceCollectorShape {
|
||||
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
export class BrowserTraceCollector extends Context.Service<
|
||||
export class BrowserTraceCollector extends ServiceMap.Service<
|
||||
BrowserTraceCollector,
|
||||
BrowserTraceCollectorShape
|
||||
>()("t3/observability/Services/BrowserTraceCollector") {}
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
launchDetached,
|
||||
resolveAvailableEditors,
|
||||
resolveEditorLaunch,
|
||||
} from "./open.ts";
|
||||
} from "./open";
|
||||
|
||||
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
it.effect("returns commands for command-based editors", () =>
|
||||
@@ -42,16 +42,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const kiroLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLaunch, {
|
||||
command: "kiro",
|
||||
args: ["ide", "/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -132,16 +122,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const kiroLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
|
||||
"darwin",
|
||||
{ PATH: "" },
|
||||
);
|
||||
assert.deepEqual(kiroLineAndColumn, {
|
||||
command: "kiro",
|
||||
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
|
||||
"darwin",
|
||||
@@ -374,7 +354,6 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "kiro.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
@@ -382,7 +361,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["trae", "kiro", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
+120
-23
@@ -7,17 +7,17 @@
|
||||
* @module Open
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { accessSync, constants, statSync } from "node:fs";
|
||||
import { extname, join } from "node:path";
|
||||
|
||||
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
|
||||
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
import { ServiceMap, Effect, Layer } from "effect";
|
||||
|
||||
// ==============================
|
||||
// Definitions
|
||||
// ==============================
|
||||
|
||||
export { OpenError };
|
||||
export { isCommandAvailable } from "@t3tools/shared/shell";
|
||||
|
||||
export interface OpenInEditorInput {
|
||||
readonly cwd: string;
|
||||
@@ -29,6 +29,11 @@ interface EditorLaunch {
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}
|
||||
|
||||
interface CommandAvailabilityOptions {
|
||||
readonly platform?: NodeJS.Platform;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
}
|
||||
|
||||
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
|
||||
|
||||
function parseTargetPathAndPosition(target: string): {
|
||||
@@ -70,14 +75,6 @@ function resolveCommandEditorArgs(
|
||||
}
|
||||
}
|
||||
|
||||
function resolveEditorArgs(
|
||||
editor: (typeof EDITORS)[number],
|
||||
target: string,
|
||||
): ReadonlyArray<string> {
|
||||
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
|
||||
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
|
||||
}
|
||||
|
||||
function resolveAvailableCommand(
|
||||
commands: ReadonlyArray<string>,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
@@ -101,6 +98,111 @@ function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
}
|
||||
}
|
||||
|
||||
function stripWrappingQuotes(value: string): string {
|
||||
return value.replace(/^"+|"+$/g, "");
|
||||
}
|
||||
|
||||
function resolvePathEnvironmentVariable(env: NodeJS.ProcessEnv): string {
|
||||
return env.PATH ?? env.Path ?? env.path ?? "";
|
||||
}
|
||||
|
||||
function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<string> {
|
||||
const rawValue = env.PATHEXT;
|
||||
const fallback = [".COM", ".EXE", ".BAT", ".CMD"];
|
||||
if (!rawValue) return fallback;
|
||||
|
||||
const parsed = rawValue
|
||||
.split(";")
|
||||
.map((entry) => entry.trim())
|
||||
.filter((entry) => entry.length > 0)
|
||||
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
|
||||
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
|
||||
}
|
||||
|
||||
function resolveCommandCandidates(
|
||||
command: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): ReadonlyArray<string> {
|
||||
if (platform !== "win32") return [command];
|
||||
const extension = extname(command);
|
||||
const normalizedExtension = extension.toUpperCase();
|
||||
|
||||
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
|
||||
const commandWithoutExtension = command.slice(0, -extension.length);
|
||||
return Array.from(
|
||||
new Set([
|
||||
command,
|
||||
`${commandWithoutExtension}${normalizedExtension}`,
|
||||
`${commandWithoutExtension}${normalizedExtension.toLowerCase()}`,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
const candidates: string[] = [];
|
||||
for (const extension of windowsPathExtensions) {
|
||||
candidates.push(`${command}${extension}`);
|
||||
candidates.push(`${command}${extension.toLowerCase()}`);
|
||||
}
|
||||
return Array.from(new Set(candidates));
|
||||
}
|
||||
|
||||
function isExecutableFile(
|
||||
filePath: string,
|
||||
platform: NodeJS.Platform,
|
||||
windowsPathExtensions: ReadonlyArray<string>,
|
||||
): boolean {
|
||||
try {
|
||||
const stat = statSync(filePath);
|
||||
if (!stat.isFile()) return false;
|
||||
if (platform === "win32") {
|
||||
const extension = extname(filePath);
|
||||
if (extension.length === 0) return false;
|
||||
return windowsPathExtensions.includes(extension.toUpperCase());
|
||||
}
|
||||
accessSync(filePath, constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function resolvePathDelimiter(platform: NodeJS.Platform): string {
|
||||
return platform === "win32" ? ";" : ":";
|
||||
}
|
||||
|
||||
export function isCommandAvailable(
|
||||
command: string,
|
||||
options: CommandAvailabilityOptions = {},
|
||||
): boolean {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
|
||||
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
|
||||
|
||||
if (command.includes("/") || command.includes("\\")) {
|
||||
return commandCandidates.some((candidate) =>
|
||||
isExecutableFile(candidate, platform, windowsPathExtensions),
|
||||
);
|
||||
}
|
||||
|
||||
const pathValue = resolvePathEnvironmentVariable(env);
|
||||
if (pathValue.length === 0) return false;
|
||||
const pathEntries = pathValue
|
||||
.split(resolvePathDelimiter(platform))
|
||||
.map((entry) => stripWrappingQuotes(entry.trim()))
|
||||
.filter((entry) => entry.length > 0);
|
||||
|
||||
for (const pathEntry of pathEntries) {
|
||||
for (const candidate of commandCandidates) {
|
||||
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function resolveAvailableEditors(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
@@ -145,7 +247,7 @@ export interface OpenShape {
|
||||
/**
|
||||
* Open - Service tag for browser/editor launch operations.
|
||||
*/
|
||||
export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
|
||||
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
|
||||
|
||||
// ==============================
|
||||
// Implementations
|
||||
@@ -171,7 +273,7 @@ export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
|
||||
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
|
||||
return {
|
||||
command,
|
||||
args: resolveEditorArgs(editorDef, input.cwd),
|
||||
args: resolveCommandEditorArgs(editorDef, input.cwd),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -191,16 +293,11 @@ export const launchDetached = (launch: EditorLaunch) =>
|
||||
yield* Effect.callback<void, OpenError>((resume) => {
|
||||
let child;
|
||||
try {
|
||||
const isWin32 = process.platform === "win32";
|
||||
child = spawn(
|
||||
launch.command,
|
||||
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
|
||||
{
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
shell: isWin32,
|
||||
},
|
||||
);
|
||||
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 })),
|
||||
|
||||
@@ -44,8 +44,8 @@ import { ServerConfig } from "../../config.ts";
|
||||
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
|
||||
type LegacyProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
@@ -81,7 +81,7 @@ function createProviderServiceHarness(
|
||||
provider: providerName,
|
||||
status: "ready",
|
||||
runtimeMode: "full-access",
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
cwd: sessionCwd,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -130,7 +130,7 @@ async function waitForThread(
|
||||
activities: ReadonlyArray<{ kind: string }>;
|
||||
}> => {
|
||||
const readModel = await Effect.runPromise(engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
if (thread && predicate(thread)) {
|
||||
return thread;
|
||||
}
|
||||
@@ -310,7 +310,7 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||
@@ -324,8 +324,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -344,21 +344,21 @@ describe("CheckpointReactor", () => {
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v2\n", "utf8");
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
}),
|
||||
);
|
||||
fs.writeFileSync(path.join(cwd, "README.md"), "v3\n", "utf8");
|
||||
await runtime.runPromise(
|
||||
checkpointStore.captureCheckpoint({
|
||||
cwd,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -378,10 +378,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-capture"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -395,26 +395,26 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.make("evt-turn-started-1"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-1"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-1"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-1"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -426,22 +426,22 @@ describe("CheckpointReactor", () => {
|
||||
);
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v1\n");
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v2\n");
|
||||
@@ -456,10 +456,10 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-refresh-local-status"),
|
||||
provider: "codex",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-refresh-local-status"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -476,10 +476,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-primary-running"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-primary-running"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -493,43 +493,45 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.make("evt-turn-started-main"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-main"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-aux"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-aux"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-aux"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await harness.drain();
|
||||
const midReadModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const midThread = midReadModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
const midThread = midReadModel.threads.find(
|
||||
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
|
||||
);
|
||||
expect(midThread?.checkpoints).toHaveLength(0);
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-main"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-main"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-main"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -551,10 +553,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-capture-claude"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-capture-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -568,24 +570,24 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.make("evt-turn-started-claude-1"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-claude-1"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
});
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-claude-1"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-claude-1"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -598,7 +600,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -609,10 +611,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-missing-baseline-diff"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-missing-baseline-diff"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -626,11 +628,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-missing-baseline"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-baseline"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-missing-baseline"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
@@ -659,10 +661,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-for-baseline"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-for-baseline"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: MessageId.make("message-user-1"),
|
||||
messageId: MessageId.makeUnsafe("message-user-1"),
|
||||
role: "user",
|
||||
text: "start turn",
|
||||
attachments: [],
|
||||
@@ -675,12 +677,12 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v1\n");
|
||||
@@ -697,10 +699,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-missing-provider-cwd"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-missing-provider-cwd"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -715,23 +717,23 @@ describe("CheckpointReactor", () => {
|
||||
fs.writeFileSync(path.join(harness.cwd, "README.md"), "v2\n", "utf8");
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-completed-missing-provider-cwd"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-missing-cwd"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.turn-diff-completed");
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1)),
|
||||
).toBe(true);
|
||||
expect(
|
||||
gitShowFileAtRef(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
"README.md",
|
||||
),
|
||||
).toBe("v2\n");
|
||||
@@ -744,10 +746,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-checkpoint-captured"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-checkpoint-captured"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -761,11 +763,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "checkpoint.captured",
|
||||
eventId: EventId.make("evt-checkpoint-captured-3"),
|
||||
eventId: EventId.makeUnsafe("evt-checkpoint-captured-3"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-3"),
|
||||
turnCount: 3,
|
||||
status: "completed",
|
||||
@@ -773,7 +775,7 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
await harness.drain();
|
||||
const readModel = await Effect.runPromise(harness.engine.getReadModel());
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
|
||||
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
|
||||
expect(thread?.checkpoints.some((checkpoint) => checkpoint.checkpointTurnCount === 3)).toBe(
|
||||
false,
|
||||
);
|
||||
@@ -794,10 +796,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-non-repo-runtime"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-non-repo-runtime"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -811,31 +813,31 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make("evt-runtime-capture-failure"),
|
||||
eventId: EventId.makeUnsafe("evt-runtime-capture-failure"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-runtime-failure"),
|
||||
payload: { state: "completed" },
|
||||
});
|
||||
|
||||
harness.provider.emit({
|
||||
type: "turn.started",
|
||||
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
|
||||
eventId: EventId.makeUnsafe("evt-turn-started-after-runtime-failure"),
|
||||
provider: "codex",
|
||||
|
||||
createdAt: new Date().toISOString(),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-after-runtime-failure"),
|
||||
});
|
||||
|
||||
await waitForGitRefExists(
|
||||
harness.cwd,
|
||||
checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0),
|
||||
checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0),
|
||||
);
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 0)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 0)),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
@@ -846,10 +848,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -864,11 +866,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.make("cmd-diff-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
@@ -878,11 +880,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.make("cmd-diff-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
@@ -893,8 +895,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-revert-request"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -908,12 +910,12 @@ describe("CheckpointReactor", () => {
|
||||
expect(thread.checkpoints[0]?.checkpointTurnCount).toBe(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(fs.readFileSync(path.join(harness.cwd, "README.md"), "utf8")).toBe("v2\n");
|
||||
expect(
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2)),
|
||||
gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2)),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -924,10 +926,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-claude"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "claudeAgent",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -942,11 +944,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.make("cmd-diff-claude-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
@@ -956,11 +958,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.make("cmd-diff-claude-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-diff-claude-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-claude-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
@@ -971,8 +973,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-revert-request-claude"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-request-claude"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -981,7 +983,7 @@ describe("CheckpointReactor", () => {
|
||||
await waitForEvent(harness.engine, (event) => event.type === "thread.reverted");
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(1);
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledWith({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
@@ -993,10 +995,10 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.session.set",
|
||||
commandId: CommandId.make("cmd-session-set-inline-revert"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-session-set-inline-revert"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
session: {
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
status: "ready",
|
||||
providerName: "codex",
|
||||
runtimeMode: "approval-required",
|
||||
@@ -1011,11 +1013,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.make("cmd-inline-revert-diff-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 1),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 1,
|
||||
@@ -1025,11 +1027,11 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.make("cmd-inline-revert-diff-2"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-inline-revert-diff-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnId: asTurnId("turn-2"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.make("thread-1"), 2),
|
||||
checkpointRef: checkpointRefForThreadTurn(ThreadId.makeUnsafe("thread-1"), 2),
|
||||
status: "ready",
|
||||
files: [],
|
||||
checkpointTurnCount: 2,
|
||||
@@ -1040,8 +1042,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-sequenced-revert-request-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -1049,8 +1051,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-sequenced-revert-request-0"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-sequenced-revert-request-0"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 0,
|
||||
createdAt,
|
||||
}),
|
||||
@@ -1060,11 +1062,11 @@ describe("CheckpointReactor", () => {
|
||||
|
||||
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
|
||||
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
expect(harness.provider.rollbackConversation.mock.calls[1]?.[0]).toEqual({
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
numTurns: 1,
|
||||
});
|
||||
});
|
||||
@@ -1076,8 +1078,8 @@ describe("CheckpointReactor", () => {
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.checkpoint.revert",
|
||||
commandId: CommandId.make("cmd-revert-no-session"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-revert-no-session"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
turnCount: 1,
|
||||
createdAt,
|
||||
}),
|
||||
|
||||
@@ -21,8 +21,8 @@ import { ProviderService } from "../../provider/Services/ProviderService.ts";
|
||||
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
|
||||
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
|
||||
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
|
||||
import type { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import type { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
|
||||
import { OrchestrationDispatchError } from "../Errors.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
import { GitStatusBroadcaster } from "../../git/Services/GitStatusBroadcaster.ts";
|
||||
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
|
||||
@@ -38,7 +38,7 @@ type ReactorInput =
|
||||
};
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | null {
|
||||
return value === undefined ? null : TurnId.make(String(value));
|
||||
return value === undefined ? null : TurnId.makeUnsafe(String(value));
|
||||
}
|
||||
|
||||
function sameId(left: string | null | undefined, right: string | null | undefined): boolean {
|
||||
@@ -62,7 +62,7 @@ function checkpointStatusFromRuntime(status: string | undefined): "ready" | "mis
|
||||
}
|
||||
|
||||
const serverCommandId = (tag: string): CommandId =>
|
||||
CommandId.make(`server:${tag}:${crypto.randomUUID()}`);
|
||||
CommandId.makeUnsafe(`server:${tag}:${crypto.randomUUID()}`);
|
||||
|
||||
const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
@@ -83,7 +83,7 @@ const make = Effect.gen(function* () {
|
||||
commandId: serverCommandId("checkpoint-revert-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.revert.failed",
|
||||
summary: "Checkpoint revert failed",
|
||||
@@ -108,7 +108,7 @@ const make = Effect.gen(function* () {
|
||||
commandId: serverCommandId("checkpoint-capture-failure"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "error",
|
||||
kind: "checkpoint.capture.failed",
|
||||
summary: "Checkpoint capture failed",
|
||||
@@ -270,7 +270,7 @@ const make = Effect.gen(function* () {
|
||||
input.thread.messages
|
||||
.toReversed()
|
||||
.find((entry) => entry.role === "assistant" && entry.turnId === input.turnId)?.id ??
|
||||
MessageId.make(`assistant:${input.turnId}`);
|
||||
MessageId.makeUnsafe(`assistant:${input.turnId}`);
|
||||
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
@@ -307,7 +307,7 @@ const make = Effect.gen(function* () {
|
||||
commandId: serverCommandId("checkpoint-captured-activity"),
|
||||
threadId: input.threadId,
|
||||
activity: {
|
||||
id: EventId.make(crypto.randomUUID()),
|
||||
id: EventId.makeUnsafe(crypto.randomUUID()),
|
||||
tone: "info",
|
||||
kind: "checkpoint.captured",
|
||||
summary: "Checkpoint captured",
|
||||
|
||||
@@ -32,10 +32,10 @@ import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts"
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.make(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.make(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(value);
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
|
||||
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
|
||||
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
|
||||
|
||||
async function createOrchestrationSystem() {
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
@@ -115,7 +115,7 @@ describe("OrchestrationEngine", () => {
|
||||
],
|
||||
threads: [
|
||||
{
|
||||
id: ThreadId.make("thread-bootstrap"),
|
||||
id: ThreadId.makeUnsafe("thread-bootstrap"),
|
||||
projectId: asProjectId("project-bootstrap"),
|
||||
title: "Bootstrap Thread",
|
||||
modelSelection: {
|
||||
@@ -144,20 +144,10 @@ describe("OrchestrationEngine", () => {
|
||||
Layer.provide(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getSnapshot: () => Effect.succeed(projectionSnapshot),
|
||||
getShellSnapshot: () =>
|
||||
Effect.succeed({
|
||||
snapshotSequence: projectionSnapshot.snapshotSequence,
|
||||
projects: [],
|
||||
threads: [],
|
||||
updatedAt: projectionSnapshot.updatedAt,
|
||||
}),
|
||||
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
|
||||
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
|
||||
getProjectShellById: () => Effect.succeed(Option.none()),
|
||||
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
|
||||
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
|
||||
getThreadShellById: () => Effect.succeed(Option.none()),
|
||||
getThreadDetailById: () => Effect.succeed(Option.none()),
|
||||
}),
|
||||
),
|
||||
Layer.provide(
|
||||
@@ -193,7 +183,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-1-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-1-create"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
@@ -207,8 +197,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-1-create"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-1-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
@@ -225,8 +215,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-turn-start-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-1"),
|
||||
role: "user",
|
||||
@@ -253,7 +243,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-archive-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-archive-create"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Project Archive",
|
||||
workspaceRoot: "/tmp/project-archive",
|
||||
@@ -267,8 +257,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-archive-create"),
|
||||
threadId: ThreadId.make("thread-archive"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
projectId: asProjectId("project-archive"),
|
||||
title: "Archive me",
|
||||
modelSelection: {
|
||||
@@ -286,8 +276,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.archive",
|
||||
commandId: CommandId.make("cmd-thread-archive"),
|
||||
threadId: ThreadId.make("thread-archive"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-archive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
@@ -299,8 +289,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.unarchive",
|
||||
commandId: CommandId.make("cmd-thread-unarchive"),
|
||||
threadId: ThreadId.make("thread-archive"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-unarchive"),
|
||||
threadId: ThreadId.makeUnsafe("thread-archive"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
@@ -320,7 +310,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-replay-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-replay-create"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "Replay Project",
|
||||
workspaceRoot: "/tmp/project-replay",
|
||||
@@ -334,8 +324,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-replay-create"),
|
||||
threadId: ThreadId.make("thread-replay"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-replay-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
modelSelection: {
|
||||
@@ -352,8 +342,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.delete",
|
||||
commandId: CommandId.make("cmd-thread-replay-delete"),
|
||||
threadId: ThreadId.make("thread-replay"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-replay-delete"),
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -378,7 +368,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-stream-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-stream-create"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "Stream Project",
|
||||
workspaceRoot: "/tmp/project-stream",
|
||||
@@ -402,8 +392,8 @@ describe("OrchestrationEngine", () => {
|
||||
yield* Effect.sleep("10 millis");
|
||||
yield* engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-stream-thread-create"),
|
||||
threadId: ThreadId.make("thread-stream"),
|
||||
commandId: CommandId.makeUnsafe("cmd-stream-thread-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
modelSelection: {
|
||||
@@ -418,8 +408,8 @@ describe("OrchestrationEngine", () => {
|
||||
});
|
||||
yield* engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-stream-thread-update"),
|
||||
threadId: ThreadId.make("thread-stream"),
|
||||
commandId: CommandId.makeUnsafe("cmd-stream-thread-update"),
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
title: "domain-stream-updated",
|
||||
});
|
||||
eventTypes.push((yield* Queue.take(eventQueue)).type);
|
||||
@@ -439,7 +429,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-ack-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-ack-create"),
|
||||
projectId: asProjectId("project-ack"),
|
||||
title: "Ack Project",
|
||||
workspaceRoot: "/tmp/project-ack",
|
||||
@@ -454,8 +444,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-ack-create"),
|
||||
threadId: ThreadId.make("thread-ack"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-ack-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-ack"),
|
||||
projectId: asProjectId("project-ack"),
|
||||
title: "Ack Thread",
|
||||
modelSelection: {
|
||||
@@ -491,8 +481,8 @@ describe("OrchestrationEngine", () => {
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-missing-project"),
|
||||
threadId: ThreadId.make("thread-missing-project"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-missing-project"),
|
||||
threadId: ThreadId.makeUnsafe("thread-missing-project"),
|
||||
projectId: asProjectId("project-missing"),
|
||||
title: "Missing Project Thread",
|
||||
modelSelection: {
|
||||
@@ -528,7 +518,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-turn-diff-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-turn-diff-create"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn Diff Project",
|
||||
workspaceRoot: "/tmp/project-turn-diff",
|
||||
@@ -542,8 +532,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-turn-diff-create"),
|
||||
threadId: ThreadId.make("thread-turn-diff"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-turn-diff-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
modelSelection: {
|
||||
@@ -560,8 +550,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.diff.complete",
|
||||
commandId: CommandId.make("cmd-turn-diff-complete"),
|
||||
threadId: ThreadId.make("thread-turn-diff"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-diff-complete"),
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
completedAt: createdAt,
|
||||
checkpointRef: asCheckpointRef("refs/t3/checkpoints/thread-turn-diff/turn/1"),
|
||||
@@ -600,7 +590,7 @@ describe("OrchestrationEngine", () => {
|
||||
|
||||
const flakyStore: OrchestrationEventStoreShape = {
|
||||
append(event) {
|
||||
if (shouldFailFirstAppend && event.commandId === CommandId.make("cmd-flaky-1")) {
|
||||
if (shouldFailFirstAppend && event.commandId === CommandId.makeUnsafe("cmd-flaky-1")) {
|
||||
shouldFailFirstAppend = false;
|
||||
return Effect.fail(
|
||||
new PersistenceSqlError({
|
||||
@@ -647,7 +637,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-flaky-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-flaky-create"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "Flaky Project",
|
||||
workspaceRoot: "/tmp/project-flaky",
|
||||
@@ -663,8 +653,8 @@ describe("OrchestrationEngine", () => {
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-flaky-1"),
|
||||
threadId: ThreadId.make("thread-flaky-fail"),
|
||||
commandId: CommandId.makeUnsafe("cmd-flaky-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
modelSelection: {
|
||||
@@ -683,8 +673,8 @@ describe("OrchestrationEngine", () => {
|
||||
const result = await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-flaky-2"),
|
||||
threadId: ThreadId.make("thread-flaky-ok"),
|
||||
commandId: CommandId.makeUnsafe("cmd-flaky-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
modelSelection: {
|
||||
@@ -711,7 +701,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailRequestedProjection &&
|
||||
event.commandId === CommandId.make("cmd-turn-start-atomic") &&
|
||||
event.commandId === CommandId.makeUnsafe("cmd-turn-start-atomic") &&
|
||||
event.type === "thread.turn-start-requested"
|
||||
) {
|
||||
shouldFailRequestedProjection = false;
|
||||
@@ -742,7 +732,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-atomic-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-atomic-create"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "Atomic Project",
|
||||
workspaceRoot: "/tmp/project-atomic",
|
||||
@@ -756,8 +746,8 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-atomic-create"),
|
||||
threadId: ThreadId.make("thread-atomic"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-atomic-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
modelSelection: {
|
||||
@@ -774,8 +764,8 @@ describe("OrchestrationEngine", () => {
|
||||
|
||||
const turnStartCommand = {
|
||||
type: "thread.turn.start" as const,
|
||||
commandId: CommandId.make("cmd-turn-start-atomic"),
|
||||
threadId: ThreadId.make("thread-atomic"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-atomic"),
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-atomic-1"),
|
||||
role: "user" as const,
|
||||
@@ -855,7 +845,7 @@ describe("OrchestrationEngine", () => {
|
||||
projectEvent: (event) => {
|
||||
if (
|
||||
shouldFailProjection &&
|
||||
event.commandId === CommandId.make("cmd-thread-meta-sync-fail")
|
||||
event.commandId === CommandId.makeUnsafe("cmd-thread-meta-sync-fail")
|
||||
) {
|
||||
shouldFailProjection = false;
|
||||
return Effect.fail(
|
||||
@@ -885,7 +875,7 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-sync-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-sync-create"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "Sync Project",
|
||||
workspaceRoot: "/tmp/project-sync",
|
||||
@@ -899,8 +889,8 @@ describe("OrchestrationEngine", () => {
|
||||
await runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-sync-create"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-sync-create"),
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
modelSelection: {
|
||||
@@ -919,8 +909,8 @@ describe("OrchestrationEngine", () => {
|
||||
runtime.runPromise(
|
||||
engine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: CommandId.make("cmd-thread-meta-sync-fail"),
|
||||
threadId: ThreadId.make("thread-sync"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-meta-sync-fail"),
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
title: "sync-after-failed-projection",
|
||||
}),
|
||||
),
|
||||
@@ -944,8 +934,8 @@ describe("OrchestrationEngine", () => {
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make("cmd-invariant-missing-thread"),
|
||||
threadId: ThreadId.make("thread-missing"),
|
||||
commandId: CommandId.makeUnsafe("cmd-invariant-missing-thread"),
|
||||
threadId: ThreadId.makeUnsafe("thread-missing"),
|
||||
message: {
|
||||
messageId: asMessageId("msg-missing"),
|
||||
role: "user",
|
||||
@@ -970,7 +960,7 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make("cmd-project-duplicate-create"),
|
||||
commandId: CommandId.makeUnsafe("cmd-project-duplicate-create"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project-duplicate",
|
||||
@@ -985,8 +975,8 @@ describe("OrchestrationEngine", () => {
|
||||
await system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-duplicate-1"),
|
||||
threadId: ThreadId.make("thread-duplicate"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
modelSelection: {
|
||||
@@ -1005,8 +995,8 @@ describe("OrchestrationEngine", () => {
|
||||
system.run(
|
||||
engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make("cmd-thread-duplicate-2"),
|
||||
threadId: ThreadId.make("thread-duplicate"),
|
||||
commandId: CommandId.makeUnsafe("cmd-thread-duplicate-2"),
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
modelSelection: {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -2,7 +2,6 @@ import {
|
||||
ApprovalRequestId,
|
||||
type ChatAttachment,
|
||||
type OrchestrationEvent,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -87,89 +86,7 @@ function extractActivityRequestId(payload: unknown): ApprovalRequestId | null {
|
||||
return null;
|
||||
}
|
||||
const requestId = (payload as Record<string, unknown>).requestId;
|
||||
return typeof requestId === "string" ? ApprovalRequestId.make(requestId) : null;
|
||||
}
|
||||
|
||||
function isStalePendingApprovalFailureDetail(detail: string | null): boolean {
|
||||
if (detail === null) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
detail.includes("stale pending approval request") ||
|
||||
detail.includes("unknown pending approval request") ||
|
||||
detail.includes("unknown pending permission request")
|
||||
);
|
||||
}
|
||||
|
||||
function derivePendingUserInputCountFromActivities(
|
||||
activities: ReadonlyArray<ProjectionThreadActivity>,
|
||||
): number {
|
||||
const openRequestIds = new Set<string>();
|
||||
const ordered = [...activities].toSorted(
|
||||
(left, right) =>
|
||||
left.createdAt.localeCompare(right.createdAt) ||
|
||||
left.activityId.localeCompare(right.activityId),
|
||||
);
|
||||
|
||||
for (const activity of ordered) {
|
||||
const requestId = extractActivityRequestId(activity.payload);
|
||||
if (requestId === null) {
|
||||
continue;
|
||||
}
|
||||
const payload =
|
||||
typeof activity.payload === "object" && activity.payload !== null
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
|
||||
if (activity.kind === "user-input.requested") {
|
||||
openRequestIds.add(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (activity.kind === "user-input.resolved") {
|
||||
openRequestIds.delete(requestId);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (
|
||||
activity.kind === "provider.user-input.respond.failed" &&
|
||||
detail !== null &&
|
||||
(detail.includes("stale pending user-input request") ||
|
||||
detail.includes("unknown pending user-input request"))
|
||||
) {
|
||||
openRequestIds.delete(requestId);
|
||||
}
|
||||
}
|
||||
|
||||
return openRequestIds.size;
|
||||
}
|
||||
|
||||
function deriveHasActionableProposedPlan(input: {
|
||||
readonly latestTurnId: string | null;
|
||||
readonly proposedPlans: ReadonlyArray<ProjectionThreadProposedPlan>;
|
||||
}): boolean {
|
||||
const sorted = [...input.proposedPlans].toSorted(
|
||||
(left, right) =>
|
||||
left.updatedAt.localeCompare(right.updatedAt) || left.planId.localeCompare(right.planId),
|
||||
);
|
||||
|
||||
let latestForTurn: ProjectionThreadProposedPlan | null = null;
|
||||
if (input.latestTurnId !== null) {
|
||||
for (let index = sorted.length - 1; index >= 0; index -= 1) {
|
||||
const plan = sorted[index];
|
||||
if (plan?.turnId === input.latestTurnId) {
|
||||
latestForTurn = plan;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (latestForTurn !== null) {
|
||||
return latestForTurn.implementedAt === null;
|
||||
}
|
||||
|
||||
const latestPlan = sorted.at(-1) ?? null;
|
||||
return latestPlan !== null && latestPlan.implementedAt === null;
|
||||
return typeof requestId === "string" ? ApprovalRequestId.makeUnsafe(requestId) : null;
|
||||
}
|
||||
|
||||
function retainProjectionMessagesAfterRevert(
|
||||
@@ -515,48 +432,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
}
|
||||
});
|
||||
|
||||
const refreshThreadShellSummary = Effect.fn("refreshThreadShellSummary")(function* (
|
||||
threadId: ThreadId,
|
||||
) {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId,
|
||||
});
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const [messages, proposedPlans, activities, pendingApprovals] = yield* Effect.all([
|
||||
projectionThreadMessageRepository.listByThreadId({ threadId }),
|
||||
projectionThreadProposedPlanRepository.listByThreadId({ threadId }),
|
||||
projectionThreadActivityRepository.listByThreadId({ threadId }),
|
||||
projectionPendingApprovalRepository.listByThreadId({ threadId }),
|
||||
]);
|
||||
|
||||
const latestUserMessageAt =
|
||||
messages
|
||||
.filter((message) => message.role === "user")
|
||||
.map((message) => message.createdAt)
|
||||
.toSorted()
|
||||
.at(-1) ?? null;
|
||||
|
||||
const pendingApprovalCount = pendingApprovals.filter(
|
||||
(approval) => approval.status === "pending",
|
||||
).length;
|
||||
const pendingUserInputCount = derivePendingUserInputCountFromActivities(activities);
|
||||
const hasActionableProposedPlan = deriveHasActionableProposedPlan({
|
||||
latestTurnId: existingRow.value.latestTurnId,
|
||||
proposedPlans,
|
||||
});
|
||||
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
latestUserMessageAt,
|
||||
pendingApprovalCount,
|
||||
pendingUserInputCount,
|
||||
hasActionableProposedPlan: hasActionableProposedPlan ? 1 : 0,
|
||||
});
|
||||
});
|
||||
|
||||
const applyThreadsProjection: ProjectorDefinition["apply"] = Effect.fn(
|
||||
"applyThreadsProjection",
|
||||
)(function* (event, attachmentSideEffects) {
|
||||
@@ -575,10 +450,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
archivedAt: null,
|
||||
latestUserMessageAt: null,
|
||||
pendingApprovalCount: 0,
|
||||
pendingUserInputCount: 0,
|
||||
hasActionableProposedPlan: 0,
|
||||
deletedAt: null,
|
||||
});
|
||||
return;
|
||||
@@ -683,9 +554,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
|
||||
case "thread.message-sent":
|
||||
case "thread.proposed-plan-upserted":
|
||||
case "thread.activity-appended":
|
||||
case "thread.approval-response-requested":
|
||||
case "thread.user-input-response-requested": {
|
||||
case "thread.activity-appended": {
|
||||
const existingRow = yield* projectionThreadRepository.getById({
|
||||
threadId: event.payload.threadId,
|
||||
});
|
||||
@@ -696,7 +565,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
...existingRow.value,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -712,7 +580,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.session.activeTurnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -728,7 +595,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: event.payload.turnId,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -744,7 +610,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
latestTurnId: null,
|
||||
updatedAt: event.occurredAt,
|
||||
});
|
||||
yield* refreshThreadShellSummary(event.payload.threadId);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1256,42 +1121,6 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (event.payload.activity.kind === "provider.approval.respond.failed") {
|
||||
const payload =
|
||||
typeof event.payload.activity.payload === "object" &&
|
||||
event.payload.activity.payload !== null
|
||||
? (event.payload.activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
const detail =
|
||||
typeof payload?.detail === "string" ? payload.detail.toLowerCase() : null;
|
||||
if (isStalePendingApprovalFailureDetail(detail)) {
|
||||
if (Option.isNone(existingRow)) {
|
||||
return;
|
||||
}
|
||||
if (existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
yield* projectionPendingApprovalRepository.upsert({
|
||||
requestId,
|
||||
threadId: existingRow.value.threadId,
|
||||
turnId: existingRow.value.turnId,
|
||||
status: "resolved",
|
||||
decision: null,
|
||||
createdAt: existingRow.value.createdAt,
|
||||
resolvedAt: event.payload.activity.createdAt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Only approval-requested activities should create pending-approval
|
||||
// rows. Other activity kinds that happen to carry a requestId
|
||||
// (e.g. user-input.requested / user-input.resolved) must not
|
||||
// pollute this projection — they have their own accounting via
|
||||
// derivePendingUserInputCountFromActivities.
|
||||
if (event.payload.activity.kind !== "approval.requested") {
|
||||
return;
|
||||
}
|
||||
if (Option.isSome(existingRow) && existingRow.value.status === "resolved") {
|
||||
return;
|
||||
}
|
||||
|
||||
Loaded 100 of 493 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user