Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
84b54f7284 | ||
|
|
acd1abbd66 |
No files matched your search
@@ -1 +0,0 @@
|
||||
plans/
|
||||
@@ -2,22 +2,15 @@
|
||||
"name": "T3 Code Dev",
|
||||
"image": "debian:bookworm",
|
||||
"features": {
|
||||
"ghcr.io/devcontainers/features/git:1": {},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {
|
||||
"version": "1.3.11"
|
||||
},
|
||||
"ghcr.io/devcontainers-extra/features/bun:1": {},
|
||||
"ghcr.io/devcontainers/features/node:1": {
|
||||
"version": "24.13.1"
|
||||
"version": "24",
|
||||
"nodeGypDependencies": true
|
||||
},
|
||||
"ghcr.io/devcontainers/features/python:1": {
|
||||
"version": "3.10",
|
||||
"installTools": false
|
||||
"version": "3.12"
|
||||
}
|
||||
},
|
||||
"overrideFeatureInstallOrder": [
|
||||
"ghcr.io/devcontainers/features/git",
|
||||
"ghcr.io/devcontainers-extra/features/bun"
|
||||
],
|
||||
"postCreateCommand": {
|
||||
"bun-install": "bun install --backend=copyfile --frozen-lockfile"
|
||||
},
|
||||
|
||||
@@ -93,8 +93,6 @@ Examples:
|
||||
|
||||
A known environment may or may not know the target `environmentId` before first successful connect.
|
||||
|
||||
In the hosted web app, known environments are browser-local. A hosted pairing URL can create the saved entry, but it does not give the hosted app a server-side control plane or a copy of the session state.
|
||||
|
||||
### AccessEndpoint
|
||||
|
||||
An `AccessEndpoint` is one concrete way to reach a known environment.
|
||||
@@ -110,67 +108,6 @@ A single environment may have many endpoints:
|
||||
|
||||
The environment stays the same. Only the access path changes.
|
||||
|
||||
### AdvertisedEndpoint
|
||||
|
||||
An `AdvertisedEndpoint` is a server or desktop-authored candidate endpoint for an environment. It is how the backend tells the client which URLs may be useful for pairing and reconnecting.
|
||||
|
||||
`AdvertisedEndpoint` is deliberately narrower than the full access model:
|
||||
|
||||
- it describes a concrete HTTP and WebSocket base URL pair
|
||||
- it can mark the endpoint as default, available, or unavailable
|
||||
- it includes reachability hints such as loopback, LAN, private, public, or tunnel
|
||||
- it includes compatibility hints such as whether the endpoint can be used from the hosted HTTPS app
|
||||
|
||||
Clients should treat advertised endpoints as hints, not as proof that a route works from the current device. The final connection attempt still decides whether the endpoint is reachable.
|
||||
|
||||
The UI presents one default advertised endpoint in the network-access summary and keeps the rest behind an expandable advanced list. The default controls pairing QR codes and primary copy actions. Users can override it, but that override is a UI preference, not backend configuration.
|
||||
|
||||
Persist the override by stable endpoint kind rather than raw URL whenever possible. For example, a LAN endpoint should be stored as the desktop LAN endpoint preference, not as `192.168.x.y`, because the address can change when the user switches networks. Provider endpoints should use provider-specific stable keys such as Tailscale IP or Tailscale MagicDNS HTTPS. Custom endpoints may fall back to their concrete identity.
|
||||
|
||||
When no user default is saved, endpoint selection should prefer:
|
||||
|
||||
1. endpoints compatible with the hosted HTTPS app
|
||||
2. explicitly default endpoints
|
||||
3. non-loopback endpoints
|
||||
4. loopback endpoints only for same-machine clients
|
||||
|
||||
This keeps endpoint discovery centralized without making any one provider, such as Tailscale or a future tunnel service, part of the core environment model.
|
||||
|
||||
### Endpoint providers
|
||||
|
||||
Endpoint providers are add-ons that contribute advertised endpoints for the current environment.
|
||||
|
||||
The provider boundary is intentionally outside the core environment model:
|
||||
|
||||
- core owns `ExecutionEnvironment`, saved environments, pairing, and connection lifecycle
|
||||
- providers discover or synthesize endpoints
|
||||
- providers return normalized `AdvertisedEndpoint` records
|
||||
- the UI and pairing logic select from those records without knowing provider-specific commands
|
||||
|
||||
The first provider is Tailscale. It can discover Tailnet IP and MagicDNS addresses from the local machine and publish them as additional endpoint candidates. Future providers, such as a hosted tunnel service, should plug into the same shape rather than adding a separate remote environment path.
|
||||
|
||||
Provider-specific confidence should remain a hint. A Tailscale endpoint still needs a successful browser or desktop connection before the client treats it as connected.
|
||||
|
||||
### Hosted pairing request
|
||||
|
||||
A hosted pairing request is a bootstrap URL for the static web app, not a transport.
|
||||
|
||||
Example:
|
||||
|
||||
```text
|
||||
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
|
||||
```
|
||||
|
||||
The hosted app reads the `host` parameter and pairing token, exchanges the token directly with that backend, then saves the resulting environment record in browser local storage.
|
||||
|
||||
Important constraints:
|
||||
|
||||
- the hosted app does not proxy HTTP or WebSocket traffic
|
||||
- the backend must still be reachable directly from the browser
|
||||
- HTTPS pages can only connect to HTTPS/WSS backends
|
||||
- HTTP LAN endpoints should keep using direct desktop or CLI pairing URLs
|
||||
- the token belongs in the URL hash so it is not sent to the hosted app origin
|
||||
|
||||
### RepositoryIdentity
|
||||
|
||||
`RepositoryIdentity` remains a best-effort logical repo grouping mechanism across environments.
|
||||
@@ -214,8 +151,6 @@ Benefits:
|
||||
- no client-specific process management required
|
||||
- best fit for hosted or self-managed remote T3 deployments
|
||||
|
||||
Browser security rules are part of this access method. A hosted HTTPS web client can connect to `wss://` backends, but it cannot connect to plain `ws://` or `http://` LAN backends because that would be mixed content.
|
||||
|
||||
### 2. Tunneled WebSocket access
|
||||
|
||||
Examples:
|
||||
@@ -235,8 +170,6 @@ This is especially useful when:
|
||||
- mobile must reach a desktop-hosted environment
|
||||
- a machine should be reachable without exposing raw LAN or public ports
|
||||
|
||||
Tailscale-backed access sits here architecturally even though the current implementation is endpoint discovery rather than a T3-managed tunnel. It contributes private-network endpoints and lets the existing HTTP/WebSocket client path do the actual connection.
|
||||
|
||||
### 3. Desktop-managed SSH access
|
||||
|
||||
SSH is an access and launch helper, not a separate environment type.
|
||||
@@ -252,8 +185,6 @@ After that, the renderer should still connect using an ordinary WebSocket URL ag
|
||||
|
||||
This keeps the renderer transport model consistent with every other access method.
|
||||
|
||||
The desktop main process owns the SSH bridge because it can spawn local SSH processes, manage askpass prompts, write temporary launch scripts, and clean up forwards. The renderer receives a saved environment record and connects through the forwarded URL; it should not need SSH-specific RPC paths for normal environment traffic.
|
||||
|
||||
## Launch methods
|
||||
|
||||
Launch methods answer a different question:
|
||||
@@ -296,15 +227,6 @@ The recommended T3 flow is:
|
||||
4. Desktop establishes local port forwarding.
|
||||
5. Renderer connects to the forwarded WebSocket endpoint as a normal environment.
|
||||
|
||||
The saved environment should remember that it was created by desktop SSH launch only for reconnect and lifecycle UX. That metadata should not change the server protocol or the environment identity model.
|
||||
|
||||
Failure handling should be explicit:
|
||||
|
||||
- SSH authentication failure should surface before any environment is saved
|
||||
- remote launch failure should include remote logs or the launcher command output when available
|
||||
- forwarded-port failure should leave the saved environment disconnected rather than falling back to an unrelated endpoint
|
||||
- reconnect should attempt to restore the SSH bridge before reconnecting the normal WebSocket client
|
||||
|
||||
### 3. Client-managed local publish
|
||||
|
||||
This is the inverse of remote launch: a local T3 server is already running, and the client publishes it through a tunnel.
|
||||
@@ -345,8 +267,6 @@ T3 already supports a WebSocket auth token on the server. That should become a f
|
||||
|
||||
For publicly reachable environments, authenticated access should be treated as required.
|
||||
|
||||
Hosted pairing should be treated as a client-side convenience only. The hosted app must not receive pairing tokens through query parameters, must not store pairing state server-side, and must not imply that an HTTP backend is safe or reachable from an HTTPS browser context.
|
||||
|
||||
## Relationship to Zed
|
||||
|
||||
Zed is a useful reference implementation for managed remote launch and reconnect behavior.
|
||||
|
||||
@@ -30,6 +30,3 @@ github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
github:shivamhwp
|
||||
github:jappyjan
|
||||
github:justsomelegs
|
||||
github:UtkarshUsername
|
||||
@@ -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
|
||||
+50
-315
@@ -1,25 +1,14 @@
|
||||
name: Release
|
||||
name: Release Desktop
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*.*.*"
|
||||
- "!v*-nightly.*"
|
||||
schedule:
|
||||
- cron: "0 */3 * * *"
|
||||
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:
|
||||
@@ -27,63 +16,45 @@ permissions:
|
||||
id-token: write
|
||||
|
||||
jobs:
|
||||
check_changes:
|
||||
name: Check for changes since last nightly
|
||||
if: github.event_name == 'schedule'
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
outputs:
|
||||
has_changes: ${{ steps.check.outputs.has_changes }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: check
|
||||
name: Compare HEAD to last nightly tag
|
||||
run: |
|
||||
last_nightly_tag=$(git tag --list 'v*-nightly.*' 'nightly-v*' --sort=-creatordate | head -n 1)
|
||||
if [[ -z "$last_nightly_tag" ]]; then
|
||||
echo "No previous nightly tag found. Proceeding with release."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
last_nightly_sha=$(git rev-parse "$last_nightly_tag^{commit}")
|
||||
head_sha=$(git rev-parse HEAD)
|
||||
|
||||
if [[ "$last_nightly_sha" == "$head_sha" ]]; then
|
||||
echo "No changes on main since last nightly release ($last_nightly_tag). Skipping."
|
||||
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "Changes detected on main since $last_nightly_tag ($last_nightly_sha → $head_sha). Proceeding."
|
||||
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
preflight:
|
||||
name: Preflight
|
||||
needs: [check_changes]
|
||||
if: |
|
||||
!failure() && !cancelled() &&
|
||||
(github.event_name != 'schedule' || needs.check_changes.outputs.has_changes == 'true')
|
||||
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
|
||||
@@ -98,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
|
||||
|
||||
@@ -161,18 +78,9 @@ 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
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' }}
|
||||
runs-on: ${{ matrix.runner }}
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
@@ -180,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: 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
|
||||
@@ -227,23 +130,6 @@ jobs:
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Install Spectre-mitigated MSVC libs
|
||||
if: matrix.platform == 'win'
|
||||
shell: pwsh
|
||||
run: |
|
||||
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
|
||||
$installPath = & $vswhere -products * -latest -property installationPath
|
||||
$setupExe = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\setup.exe"
|
||||
$proc = Start-Process -FilePath $setupExe `
|
||||
-ArgumentList "modify", "--installPath", "`"$installPath`"", "--add", `
|
||||
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64.Spectre", "--quiet", "--norestart" `
|
||||
-Wait -PassThru -NoNewWindow
|
||||
if ($null -eq $proc -or $proc.ExitCode -ne 0) {
|
||||
$code = if ($null -ne $proc) { $proc.ExitCode } else { 1 }
|
||||
Write-Error "Visual Studio Installer failed with exit code $code"
|
||||
exit $code
|
||||
}
|
||||
|
||||
- name: Build desktop artifact
|
||||
shell: bash
|
||||
env:
|
||||
@@ -320,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:
|
||||
@@ -355,8 +228,7 @@ jobs:
|
||||
publish_cli:
|
||||
name: Publish CLI to npm
|
||||
needs: [preflight, build]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
@@ -376,53 +248,33 @@ jobs:
|
||||
registry-url: https://registry.npmjs.org
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=t3 --filter=@t3tools/web --filter=@t3tools/scripts
|
||||
run: bun install --frozen-lockfile
|
||||
|
||||
- name: Align package versions to release version
|
||||
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
|
||||
|
||||
- name: Build web package
|
||||
run: bun --filter=@t3tools/web run build
|
||||
|
||||
- name: Build CLI package
|
||||
run: bun --filter=t3 run build
|
||||
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]
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- id: app_token
|
||||
name: Mint release app token
|
||||
uses: actions/create-github-app-token@v2
|
||||
with:
|
||||
app-id: ${{ secrets.RELEASE_APP_ID }}
|
||||
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
|
||||
owner: ${{ github.repository_owner }}
|
||||
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- name: Download all desktop artifacts
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
@@ -432,72 +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
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
- 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 }}
|
||||
@@ -507,15 +304,13 @@ jobs:
|
||||
release-assets/*.AppImage
|
||||
release-assets/*.exe
|
||||
release-assets/*.blockmap
|
||||
release-assets/*.yml
|
||||
release-assets/latest*.yml
|
||||
fail_on_unmatched_files: true
|
||||
token: ${{ steps.app_token.outputs.token }}
|
||||
|
||||
finalize:
|
||||
name: Finalize release
|
||||
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && 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
|
||||
@@ -554,9 +349,6 @@ jobs:
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- id: update_versions
|
||||
name: Update version strings
|
||||
env:
|
||||
@@ -565,7 +357,7 @@ jobs:
|
||||
|
||||
- name: Format package.json files
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
run: bunx oxfmt@0.40.0 apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
run: bunx oxfmt apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json
|
||||
|
||||
- name: Refresh lockfile
|
||||
if: steps.update_versions.outputs.changed == 'true'
|
||||
@@ -588,60 +380,3 @@ jobs:
|
||||
git add apps/server/package.json apps/desktop/package.json apps/web/package.json packages/contracts/package.json bun.lock
|
||||
git commit -m "chore(release): prepare $RELEASE_TAG"
|
||||
git push origin HEAD:main
|
||||
|
||||
announce_discord:
|
||||
name: Announce release on Discord
|
||||
if: |
|
||||
always() && !cancelled() &&
|
||||
needs.preflight.result == 'success' &&
|
||||
needs.release.result == 'success' &&
|
||||
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
|
||||
needs: [preflight, release, finalize]
|
||||
runs-on: blacksmith-8vcpu-ubuntu-2404
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ needs.preflight.outputs.ref }}
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version-file: package.json
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version-file: package.json
|
||||
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile --filter=@t3tools/scripts
|
||||
|
||||
- name: Announce prerelease on Discord
|
||||
if: needs.preflight.outputs.is_prerelease == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_NIGHTLY_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts prerelease \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
|
||||
- name: Announce latest release on Discord
|
||||
if: needs.preflight.outputs.make_latest == 'true'
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISCORD_MENTION_ROLE_ID: ${{ secrets.DISCORD_RELEASE_LATEST_ROLE_ID }}
|
||||
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_RELEASE_WEBHOOK_URL }}
|
||||
run: |
|
||||
node scripts/notify-discord-release.ts latest \
|
||||
--role-id "$DISCORD_MENTION_ROLE_ID" \
|
||||
--release-name "${{ needs.preflight.outputs.release_name }}" \
|
||||
--release-version "${{ needs.preflight.outputs.version }}" \
|
||||
--tag "${{ needs.preflight.outputs.tag }}" \
|
||||
--release-url "https://github.com/${{ github.repository }}/releases/tag/${{ needs.preflight.outputs.tag }}"
|
||||
@@ -22,4 +22,3 @@ apps/web/src/components/__screenshots__
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
squashfs-root/
|
||||
.vercel
|
||||
+2
-11
@@ -10,16 +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": {},
|
||||
"overrides": [
|
||||
{
|
||||
"files": [".devcontainer/devcontainer.json"],
|
||||
"options": {
|
||||
"trailingComma": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
"sortPackageJson": {}
|
||||
}
|
||||
@@ -1,350 +0,0 @@
|
||||
# Remote Endpoints and Hosted Static App Plan
|
||||
|
||||
## Purpose
|
||||
|
||||
Make remote access feel first-class while keeping the free DIY path open.
|
||||
|
||||
The immediate product goal is:
|
||||
|
||||
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
|
||||
- users can generate a hosted pairing link for `app.t3.codes`
|
||||
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
|
||||
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
|
||||
|
||||
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
|
||||
|
||||
## Current State
|
||||
|
||||
Already present or in progress:
|
||||
|
||||
- Server auth distinguishes bootstrap credentials from session credentials.
|
||||
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
|
||||
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
|
||||
- Remote environment WebSocket connections use a short-lived WebSocket token.
|
||||
- Pairing URLs can carry tokens in the URL fragment.
|
||||
- Hosted `/pair?host=...#token=...` can add a saved environment.
|
||||
- Hosted static startup can avoid assuming the page origin is the backend.
|
||||
|
||||
Main gaps:
|
||||
|
||||
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
|
||||
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
|
||||
- Tailscale/MagicDNS endpoints are not detected or surfaced.
|
||||
- Hosted-static empty/offline states are still thin.
|
||||
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
|
||||
|
||||
## Core Decision: Add `AdvertisedEndpoint`
|
||||
|
||||
Add a new first-class contract instead of extending the environment descriptor.
|
||||
|
||||
### Why not extend `ExecutionEnvironmentDescriptor`
|
||||
|
||||
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
|
||||
|
||||
Examples:
|
||||
|
||||
- environment id
|
||||
- label
|
||||
- platform
|
||||
- server version
|
||||
- capabilities
|
||||
|
||||
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
|
||||
|
||||
Examples:
|
||||
|
||||
- loopback URL
|
||||
- LAN URL
|
||||
- Tailscale IP URL
|
||||
- MagicDNS/Serve URL
|
||||
- manual URL
|
||||
- future T3 Tunnel URL
|
||||
- browser compatibility and exposure level
|
||||
|
||||
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
|
||||
|
||||
### Target Contract
|
||||
|
||||
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
|
||||
|
||||
```ts
|
||||
type AdvertisedEndpointProvider =
|
||||
| "loopback"
|
||||
| "lan"
|
||||
| "tailscale-ip"
|
||||
| "tailscale-magicdns"
|
||||
| "manual"
|
||||
| "t3-tunnel";
|
||||
|
||||
type AdvertisedEndpointVisibility = "local" | "private-network" | "tailnet" | "public";
|
||||
|
||||
type AdvertisedEndpointCompatibility = {
|
||||
hostedHttpsApp: "compatible" | "mixed-content-blocked" | "untrusted-certificate" | "unknown";
|
||||
desktopApp: "compatible" | "unknown";
|
||||
};
|
||||
|
||||
type AdvertisedEndpoint = {
|
||||
id: string;
|
||||
provider: AdvertisedEndpointProvider;
|
||||
label: string;
|
||||
httpBaseUrl: string;
|
||||
wsBaseUrl: string;
|
||||
visibility: AdvertisedEndpointVisibility;
|
||||
compatibility: AdvertisedEndpointCompatibility;
|
||||
source: "server" | "desktop" | "user";
|
||||
status: "available" | "unavailable" | "unknown";
|
||||
isDefault?: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
Keep the contract schema-only. All classification logic belongs in `packages/shared`, `apps/server`, `apps/desktop`, or `apps/web`.
|
||||
|
||||
## HTTP/WS and HTTPS/WSS Readiness
|
||||
|
||||
The codebase is partially ready, but the UX and compatibility model are not explicit enough.
|
||||
|
||||
What is ready:
|
||||
|
||||
- Remote target parsing already derives `ws://` from `http://` and `wss://` from `https://`.
|
||||
- Saved environments store both HTTP and WebSocket base URLs.
|
||||
- Remote auth uses bearer tokens instead of cookies, so cross-origin hosted clients are viable.
|
||||
- WebSocket connections can use a dynamically issued `wsToken`.
|
||||
- Server CORS support exists for browser remote auth endpoints.
|
||||
|
||||
What is not solved by code alone:
|
||||
|
||||
- `https://app.t3.codes` cannot reliably call `http://...` or `ws://...` endpoints because browsers block mixed content.
|
||||
- `wss://100.x.y.z:3773` needs a certificate the browser trusts. A raw Tailscale IP does not solve certificate trust.
|
||||
- LAN `http://192.168.x.y:3773` is usable from another desktop/native context but not from the hosted HTTPS app.
|
||||
- The UI needs to explain why an endpoint is copyable for desktop pairing but not hosted-app compatible.
|
||||
|
||||
Policy:
|
||||
|
||||
- Support both HTTP/WS and HTTPS/WSS at the runtime layer.
|
||||
- Mark endpoint compatibility at the product layer.
|
||||
- Generate `app.t3.codes` links only from endpoints that are likely hosted-browser compatible, or show a warning with an explicit fallback.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Endpoint Sources
|
||||
|
||||
Endpoint records can come from several providers:
|
||||
|
||||
1. **Server runtime**
|
||||
- headless bind host and port
|
||||
- server-known explicit advertised host config
|
||||
|
||||
2. **Desktop shell**
|
||||
- loopback backend URL
|
||||
- LAN exposure state
|
||||
- network interface discovery
|
||||
- Tailscale CLI/status discovery
|
||||
|
||||
3. **User configuration**
|
||||
- manually added hostnames
|
||||
- preferred endpoint labels
|
||||
- hidden/disabled endpoints
|
||||
|
||||
4. **Future cloud provider**
|
||||
- T3 Tunnel endpoint
|
||||
- billing/account status
|
||||
- tunnel lifecycle state
|
||||
|
||||
### Endpoint Registry
|
||||
|
||||
Create a central runtime registry:
|
||||
|
||||
- `packages/contracts/src/remoteAccess.ts`
|
||||
- `packages/shared/src/remoteAccess.ts` for URL normalization and compatibility classification
|
||||
- `apps/server/src/remoteAccess/*` for server/headless endpoints
|
||||
- `apps/desktop/src/remoteAccess/*` for desktop-discovered endpoints
|
||||
- `apps/web/src/environments/endpoints/*` for client-side display and pairing selection
|
||||
|
||||
The web app should consume endpoint records and not care whether they came from LAN, Tailscale, or a future tunnel.
|
||||
|
||||
### Pairing Link Generation
|
||||
|
||||
Move hosted pairing link generation to endpoint-driven input:
|
||||
|
||||
```ts
|
||||
buildHostedPairingUrl({
|
||||
endpoint: AdvertisedEndpoint,
|
||||
token,
|
||||
});
|
||||
```
|
||||
|
||||
Generated URL:
|
||||
|
||||
```text
|
||||
https://app.t3.codes/pair?host=<encoded endpoint httpBaseUrl>#token=<one-time token>
|
||||
```
|
||||
|
||||
Use fragment tokens by default. Continue accepting `?token=` for compatibility.
|
||||
|
||||
## Phase 1: Endpoint Abstraction
|
||||
|
||||
### Goals
|
||||
|
||||
- Centralize URL normalization, protocol derivation, and compatibility checks.
|
||||
- Replace ad hoc desktop `endpointUrl` pairing logic with endpoint selection.
|
||||
- Preserve all current remote behavior.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Add `AdvertisedEndpoint` schemas to `packages/contracts`.
|
||||
2. Add shared helpers:
|
||||
- normalize HTTP base URL
|
||||
- derive WebSocket base URL
|
||||
- classify loopback/private/LAN/Tailscale/public host
|
||||
- classify hosted HTTPS compatibility
|
||||
3. Add server endpoint discovery:
|
||||
- loopback endpoint
|
||||
- configured non-loopback endpoint
|
||||
- explicit advertised host override
|
||||
4. Add desktop endpoint discovery:
|
||||
- local loopback
|
||||
- LAN exposure endpoint
|
||||
- endpoint status labels
|
||||
5. Add WebSocket/API method or existing config field for endpoint snapshots.
|
||||
6. Refactor settings connections UI:
|
||||
- render endpoint rows
|
||||
- endpoint picker for pairing link copy
|
||||
- show compatibility warnings
|
||||
7. Refactor hosted link builder to accept endpoint records.
|
||||
8. Add tests for URL normalization and compatibility classification.
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- Existing LAN/network access UI still works.
|
||||
- Pairing links are generated from endpoint records.
|
||||
- Loopback endpoints never produce hosted pairing links silently.
|
||||
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
|
||||
- No remote environment runtime changes are required for existing saved environments.
|
||||
|
||||
## Phase 2: BYO Tailscale/MagicDNS
|
||||
|
||||
### Goals
|
||||
|
||||
- Detect free DIY Tailscale reachability.
|
||||
- Surface Tailscale endpoints as normal advertised endpoints.
|
||||
- Keep users in control of their own tailnet.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Detect Tailscale IPs from network interfaces:
|
||||
- IPv4 `100.64.0.0/10`
|
||||
- mark as `provider: "tailscale-ip"`
|
||||
2. Add optional desktop-side `tailscale status --json` discovery:
|
||||
- MagicDNS hostname
|
||||
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
|
||||
- graceful failure if CLI is missing
|
||||
3. Add manual Tailscale endpoint override:
|
||||
- hostname
|
||||
- label
|
||||
- preferred/default flag
|
||||
4. Show Tailscale endpoint rows in settings:
|
||||
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
|
||||
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
|
||||
5. Generate pairing links using selected Tailscale endpoint.
|
||||
6. Document DIY setup:
|
||||
- local desktop-to-desktop over Tailscale
|
||||
- hosted app requirements
|
||||
- why HTTPS matters
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- A machine on Tailscale shows a Tailscale endpoint without paid features.
|
||||
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
|
||||
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
|
||||
- Tailscale is optional and never required for regular LAN/loopback use.
|
||||
|
||||
## Phase 3: Hosted Static App Completion
|
||||
|
||||
### Goals
|
||||
|
||||
- `app.t3.codes` works as a real client shell.
|
||||
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
|
||||
|
||||
### Tasks
|
||||
|
||||
1. Finish hosted-static root behavior:
|
||||
- no primary backend required
|
||||
- saved environment hydration before initial routing decisions
|
||||
- first saved environment selected as active
|
||||
2. Add hosted empty state:
|
||||
- no saved environments
|
||||
- paste pairing URL
|
||||
- add host + token
|
||||
3. Add offline saved environment UI:
|
||||
- last connected
|
||||
- reconnect
|
||||
- remove
|
||||
- copy/add alternate endpoint
|
||||
4. Audit primary-backend assumptions:
|
||||
- command palette
|
||||
- settings pages
|
||||
- server config atom defaults
|
||||
- keybindings
|
||||
- provider/model lists
|
||||
- update/desktop-only affordances
|
||||
5. Add route tests for:
|
||||
- hosted `/pair?host=...#token=...`
|
||||
- hosted root with no saved environments
|
||||
- hosted root with saved environment
|
||||
- primary backend unavailable but saved environment present
|
||||
6. Add deployment hardening:
|
||||
- SPA fallback
|
||||
- strict CSP
|
||||
- no third-party scripts
|
||||
- no query token logging
|
||||
- disable or hide source maps in production if needed
|
||||
7. Add browser error messages:
|
||||
- mixed content
|
||||
- unreachable backend
|
||||
- CORS failure
|
||||
- certificate failure
|
||||
|
||||
### Acceptance Criteria
|
||||
|
||||
- `app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
|
||||
- A saved environment can be used without any backend at `app.t3.codes`.
|
||||
- Offline machines show a useful state instead of a generic boot error.
|
||||
- HTTP endpoints are still supported in desktop/native/local contexts.
|
||||
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
|
||||
|
||||
## Phase 4: Future T3 Tunnel Provider
|
||||
|
||||
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
|
||||
|
||||
Future tunnel provider responsibilities:
|
||||
|
||||
- create endpoint with `provider: "t3-tunnel"`
|
||||
- surface tunnel status
|
||||
- provide stable HTTPS URL
|
||||
- use existing backend pairing/session auth
|
||||
- never bypass server auth
|
||||
|
||||
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
|
||||
|
||||
## Security Checklist
|
||||
|
||||
- Pairing tokens are short-lived and one-time.
|
||||
- Generated hosted pairing links put tokens in the fragment.
|
||||
- The backend remains the authorization boundary.
|
||||
- Endpoint discovery never disables backend auth.
|
||||
- Hosted app does not silently downgrade to HTTP.
|
||||
- Tunnel/public endpoints require explicit user action.
|
||||
- Client sessions remain revocable.
|
||||
- Endpoint URLs and request logs must avoid recording pairing tokens.
|
||||
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
|
||||
|
||||
## Verification
|
||||
|
||||
Each implementation PR should run:
|
||||
|
||||
- `bun fmt`
|
||||
- `bun lint`
|
||||
- `bun typecheck`
|
||||
- focused tests for changed backend/web behavior
|
||||
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
# Version Control Phase 1: VCS Driver Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
|
||||
|
||||
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
|
||||
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
|
||||
- Add server services under `apps/server/src/vcs`:
|
||||
- `Services/VcsDriver.ts`
|
||||
- `Services/VcsRepositoryResolver.ts`
|
||||
- `Services/VcsProcess.ts`
|
||||
- `Layers/GitVcsDriver.ts`
|
||||
- `errors.ts`
|
||||
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
|
||||
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
|
||||
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
|
||||
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
|
||||
- No T3 Review implementation yet.
|
||||
- No broad UI redesign.
|
||||
|
||||
## Driver Model
|
||||
|
||||
Use provider-neutral nouns in new APIs:
|
||||
|
||||
- `VcsDriver`: local repository mechanics.
|
||||
- `RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
|
||||
- `WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
|
||||
- `ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
|
||||
- `RefName`: branch, bookmark, tag, or provider-specific ref.
|
||||
|
||||
The initial driver capabilities should be explicit:
|
||||
|
||||
```ts
|
||||
export interface VcsDriverCapabilities {
|
||||
readonly kind: "git" | "jj" | "sapling" | "unknown";
|
||||
readonly supportsWorktrees: boolean;
|
||||
readonly supportsBookmarks: boolean;
|
||||
readonly supportsAtomicSnapshot: boolean;
|
||||
readonly supportsPushDefaultRemote: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
|
||||
|
||||
- `detectRepository(cwd)`
|
||||
- `status(cwd, options)`
|
||||
- `listRefs(cwd, query/pagination)`
|
||||
- `checkoutRef(cwd, ref)`
|
||||
- `createRef(cwd, ref, from?)`
|
||||
- `createWorkspace(cwd, ref, path?)`
|
||||
- `removeWorkspace(path)`
|
||||
- `prepareChangeContext(cwd, filePaths?)`
|
||||
- `createChange(cwd, message, options)`
|
||||
- `push(cwd, target?)`
|
||||
- `rangeContext(cwd, base, head)`
|
||||
- `listWorkspaceFiles(cwd, options)`
|
||||
|
||||
## Effect Process Layer
|
||||
|
||||
Create a small reusable `VcsProcess` service instead of using `runProcess`.
|
||||
|
||||
Requirements:
|
||||
|
||||
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
|
||||
- Support scoped acquisition/release for long-running commands and interruption.
|
||||
- Support bounded stdout/stderr collection with truncation markers.
|
||||
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
|
||||
- Support stdin.
|
||||
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
|
||||
- Stream output lines to progress callbacks as Effects.
|
||||
- Return a typed `ProcessOutput` value for successful execution.
|
||||
- Fail with typed errors, not generic thrown exceptions.
|
||||
|
||||
Errors should be schema-backed tagged classes, for example:
|
||||
|
||||
- `VcsProcessSpawnError`
|
||||
- `VcsProcessExitError`
|
||||
- `VcsProcessTimeoutError`
|
||||
- `VcsOutputDecodeError`
|
||||
- `VcsRepositoryDetectionError`
|
||||
- `VcsUnsupportedOperationError`
|
||||
|
||||
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
|
||||
|
||||
## Git Driver Rewrite
|
||||
|
||||
Rewrite Git support against `VcsProcess`.
|
||||
|
||||
Carry forward current behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitCore.ts`
|
||||
- `apps/server/src/git/Layers/GitCore.test.ts`
|
||||
- current Git status/branch/worktree contracts
|
||||
|
||||
But split the implementation into smaller modules:
|
||||
|
||||
- command execution and hardening config
|
||||
- repository detection
|
||||
- status parsing
|
||||
- branch/ref parsing
|
||||
- worktree operations
|
||||
- commit/range context generation
|
||||
- push/pull operations
|
||||
|
||||
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
|
||||
|
||||
## Freshness and Local Caching
|
||||
|
||||
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
|
||||
|
||||
Treat these as live/local:
|
||||
|
||||
- repository detection for the active cwd
|
||||
- working copy dirty state
|
||||
- staged/unstaged/untracked file summaries
|
||||
- current branch/bookmark/change name
|
||||
- local branch/bookmark lists
|
||||
- local worktree/workspace lists
|
||||
|
||||
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
|
||||
|
||||
Treat these as cached or explicit-refresh only:
|
||||
|
||||
- remote tracking branch refreshes
|
||||
- ahead/behind counts that require network fetches
|
||||
- default branch discovery from a remote provider
|
||||
- remote branch lists beyond locally known refs
|
||||
|
||||
The VCS driver should expose freshness metadata with status results:
|
||||
|
||||
```ts
|
||||
export interface VcsFreshness {
|
||||
readonly source: "live-local" | "cached-local" | "cached-remote" | "explicit-remote";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
}
|
||||
```
|
||||
|
||||
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
|
||||
|
||||
Use Effect `Cache` for repository identity and expensive local metadata:
|
||||
|
||||
- key by resolved repository root plus VCS kind
|
||||
- invalidate on cwd/root changes and workspace mutation operations
|
||||
- use short TTLs for local status caches when filesystem events are unavailable
|
||||
- never hide command failures behind stale values unless the caller explicitly accepts stale data
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
Prefer direct migration and deletion over compatibility wrappers.
|
||||
|
||||
Rules:
|
||||
|
||||
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
|
||||
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
|
||||
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
|
||||
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
|
||||
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
|
||||
- No new feature work may depend on transitional modules.
|
||||
|
||||
Expected transitional candidates:
|
||||
|
||||
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
|
||||
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
|
||||
|
||||
## Tests
|
||||
|
||||
Add integration-style tests with real temporary Git repositories for the new Git driver:
|
||||
|
||||
- non-repository detection
|
||||
- status for clean/dirty/untracked/staged states
|
||||
- branch/ref list with pagination
|
||||
- checkout/create branch
|
||||
- worktree create/remove
|
||||
- commit context generation with file filters
|
||||
- commit creation with hook progress events
|
||||
- push behavior against a local bare remote
|
||||
- status polling does not perform remote network refresh by default
|
||||
- concurrent duplicate status requests are coalesced
|
||||
- bounded output/truncation
|
||||
- timeout/interruption
|
||||
- typed error shape for command failure and missing executable
|
||||
|
||||
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `vcs` contracts and tagged errors.
|
||||
2. Add `VcsProcess` and unit tests around process execution semantics.
|
||||
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
|
||||
4. Implement `GitVcsDriver` with real Git command integration tests.
|
||||
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
|
||||
6. Move commit/range/push callers to the VCS service directly.
|
||||
7. Delete migrated `GitCore` internals and tests as each caller group moves.
|
||||
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
|
||||
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Current Git branch/status/worktree/commit behavior remains intact.
|
||||
- New Git implementation does not depend on `processRunner.ts`.
|
||||
- New errors are typed and inspectable by tests.
|
||||
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
|
||||
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Background status refresh is local-only by default and cannot hit provider rate limits.
|
||||
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -1,268 +0,0 @@
|
||||
# Version Control Phase 2: Source Control Provider Foundation
|
||||
|
||||
## Goal
|
||||
|
||||
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
|
||||
|
||||
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
|
||||
|
||||
## Scope
|
||||
|
||||
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
|
||||
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
|
||||
- Add server services under `apps/server/src/sourceControl`:
|
||||
- `Services/SourceControlProvider.ts`
|
||||
- `Services/SourceControlProviderRegistry.ts`
|
||||
- `Services/SourceControlProcess.ts`
|
||||
- `Layers/GitHubSourceControlProvider.ts`
|
||||
- `errors.ts`
|
||||
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
|
||||
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
|
||||
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
|
||||
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
|
||||
- No in-app review UI yet.
|
||||
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
|
||||
|
||||
## Provider Model
|
||||
|
||||
Use provider-neutral names:
|
||||
|
||||
- `SourceControlProvider`: hosted repository and change-request mechanics.
|
||||
- `ChangeRequest`: GitHub pull request, GitLab merge request, Azure pull request.
|
||||
- `ChangeRequestThread`: review or discussion thread.
|
||||
- `ChangeRequestComment`: top-level or inline comment.
|
||||
- `ProviderRepository`: owner/project/repo identity plus clone URLs.
|
||||
|
||||
Core provider operations:
|
||||
|
||||
- `detectRemote(remoteUrl)`
|
||||
- `checkAuth(cwd)`
|
||||
- `getRepository(cwd | remoteUrl)`
|
||||
- `getDefaultTargetRef(repository)`
|
||||
- `listChangeRequests(repository, filters)`
|
||||
- `getChangeRequest(repository, reference)`
|
||||
- `createChangeRequest(repository, input)`
|
||||
- `checkoutChangeRequest(cwd, changeRequest, options)`
|
||||
- `getCloneUrls(repository)`
|
||||
|
||||
Review-facing operations should be designed now, even if unimplemented:
|
||||
|
||||
- `listReviewThreads(changeRequest)`
|
||||
- `createReviewComment(changeRequest, input)`
|
||||
- `replyToReviewThread(thread, input)`
|
||||
- `resolveReviewThread(thread)`
|
||||
- `submitReview(changeRequest, input)`
|
||||
|
||||
Each operation should be guarded by capabilities:
|
||||
|
||||
```ts
|
||||
export interface SourceControlProviderCapabilities {
|
||||
readonly kind: "github" | "gitlab" | "azure-devops" | "unknown";
|
||||
readonly supportsCreateChangeRequest: boolean;
|
||||
readonly supportsCheckoutChangeRequest: boolean;
|
||||
readonly supportsReviewThreads: boolean;
|
||||
readonly supportsInlineComments: boolean;
|
||||
readonly supportsDraftChangeRequests: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
## Provider Registry
|
||||
|
||||
Add a registry that resolves a provider from repository remotes and explicit user input.
|
||||
|
||||
Rules:
|
||||
|
||||
- Detection should be pure where possible and testable without spawning CLIs.
|
||||
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
|
||||
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
|
||||
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
|
||||
|
||||
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
|
||||
|
||||
## Rate Limits and Provider Caching
|
||||
|
||||
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
|
||||
|
||||
Default behavior:
|
||||
|
||||
- Pure URL/remote parsing is always live because it is local.
|
||||
- Provider detection from local remotes is live-local.
|
||||
- Authentication checks are cached.
|
||||
- Repository metadata is cached.
|
||||
- Default branch metadata is cached.
|
||||
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
|
||||
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
|
||||
- Create/update operations invalidate affected cache keys immediately after success.
|
||||
|
||||
The provider API should make freshness explicit:
|
||||
|
||||
```ts
|
||||
export interface SourceControlFreshness {
|
||||
readonly source: "live-local" | "cached-provider" | "live-provider";
|
||||
readonly observedAt: string;
|
||||
readonly expiresAt?: string;
|
||||
readonly stale?: boolean;
|
||||
}
|
||||
|
||||
export type ProviderRefreshPolicy =
|
||||
| "cache-first"
|
||||
| "stale-while-revalidate"
|
||||
| "force-refresh"
|
||||
| "local-only";
|
||||
```
|
||||
|
||||
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
|
||||
|
||||
Use Effect `Cache` for provider data:
|
||||
|
||||
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
|
||||
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
|
||||
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
|
||||
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
|
||||
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
|
||||
|
||||
Provider drivers should surface rate-limit signals when available:
|
||||
|
||||
- remaining quota
|
||||
- reset time
|
||||
- retry-after duration
|
||||
- whether the limit is primary, secondary/abuse, or unknown
|
||||
|
||||
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
|
||||
|
||||
Avoid rate-limit footguns:
|
||||
|
||||
- no provider calls from render loops or fast status polling
|
||||
- no listing all PRs/MRs across all repos to infer one branch state
|
||||
- no silent GitHub fallback for unknown providers
|
||||
- no unbounded cache cardinality for branch names or free-form search queries
|
||||
- no per-thread duplicate provider refresh when multiple views observe the same repository
|
||||
|
||||
## GitHub Provider Rewrite
|
||||
|
||||
Rewrite GitHub support as `GitHubSourceControlProvider`.
|
||||
|
||||
Carry forward behavior from:
|
||||
|
||||
- `apps/server/src/git/Layers/GitHubCli.ts`
|
||||
- `apps/server/src/git/Layers/GitHubCli.test.ts`
|
||||
- `apps/server/src/git/githubPullRequests.ts`
|
||||
- GitHub-specific `GitManager` PR paths
|
||||
|
||||
Implementation requirements:
|
||||
|
||||
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
|
||||
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
|
||||
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
|
||||
- Keep stdout/stderr bounded.
|
||||
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
|
||||
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
|
||||
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
|
||||
|
||||
## GitManager Cutover
|
||||
|
||||
Refactor `GitManager` so it coordinates three independent services:
|
||||
|
||||
- `VcsDriver` for local repository mechanics.
|
||||
- `SourceControlProviderRegistry` for hosted provider selection.
|
||||
- `TextGeneration` for message/body generation.
|
||||
|
||||
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
|
||||
|
||||
The Commit + PR flow should become:
|
||||
|
||||
1. Resolve VCS repository and local status.
|
||||
2. Resolve source-control provider from remotes.
|
||||
3. Generate commit content through the existing text generation service.
|
||||
4. Create local change through `VcsDriver`.
|
||||
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
|
||||
6. Generate change-request title/body.
|
||||
7. Create the change request through `SourceControlProvider`.
|
||||
|
||||
## Cutover Policy
|
||||
|
||||
This phase should aggressively remove old GitHub-specific internals.
|
||||
|
||||
Rules:
|
||||
|
||||
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
|
||||
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
|
||||
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
|
||||
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
|
||||
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
|
||||
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
|
||||
|
||||
## GitLab and Azure Readiness
|
||||
|
||||
Use the triaged references as implementation inputs, not merge targets:
|
||||
|
||||
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
|
||||
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
|
||||
|
||||
The abstraction should let Phase 3 add:
|
||||
|
||||
- `GitLabSourceControlProvider` using `glab`.
|
||||
- `AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
|
||||
|
||||
No provider should need to edit GitHub code to join the registry.
|
||||
|
||||
## T3 Review Design Constraint
|
||||
|
||||
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
|
||||
|
||||
That means contracts should include stable IDs and enough metadata for:
|
||||
|
||||
- file-level diffs
|
||||
- inline review threads
|
||||
- resolved/unresolved state
|
||||
- top-level discussion comments
|
||||
- pending review submission
|
||||
- provider URL back-links
|
||||
|
||||
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
|
||||
|
||||
## Tests
|
||||
|
||||
Add tests at three levels:
|
||||
|
||||
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
|
||||
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
|
||||
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
|
||||
|
||||
Required cases:
|
||||
|
||||
- GitHub PR URL, number, and branch-ish references.
|
||||
- GitLab MR URL/reference parsing.
|
||||
- Azure DevOps PR URL parsing for same-repo URLs.
|
||||
- unknown provider returns unsupported-operation errors.
|
||||
- missing CLI and auth failures produce distinct typed errors.
|
||||
- invalid CLI JSON fails at decode boundary with useful context.
|
||||
|
||||
## Migration Steps
|
||||
|
||||
1. Add `sourceControl` contracts and provider-neutral schemas.
|
||||
2. Add shared remote/reference parser helpers and tests.
|
||||
3. Add `SourceControlProcess` and provider errors.
|
||||
4. Add provider registry with GitHub-only registration.
|
||||
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
|
||||
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
|
||||
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
|
||||
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
|
||||
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Existing GitHub Commit + PR and PR checkout flows still work.
|
||||
- `GitManager` no longer imports or depends on `GitHubCli`.
|
||||
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
|
||||
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
|
||||
- Unknown/unsupported providers fail explicitly and visibly.
|
||||
- GitHub command execution does not depend on `processRunner.ts`.
|
||||
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
|
||||
- Rate-limit responses become typed errors with retry/reset metadata where available.
|
||||
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
|
||||
- `bun fmt`, `bun lint`, and `bun typecheck` pass.
|
||||
@@ -10,5 +10,3 @@
|
||||
8. `08-precommit-format-and-lint.md`
|
||||
9. `09-event-state-test-expansion.md`
|
||||
10. `10-unify-process-session-abstraction.md`
|
||||
19. `19-version-control-phase-1-vcs-driver-foundation.md`
|
||||
20. `20-version-control-phase-2-source-control-provider-foundation.md`
|
||||
Vendored
+1
-1
@@ -5,5 +5,5 @@
|
||||
"source.fixAll.oxc": "always"
|
||||
},
|
||||
"oxc.unusedDisableDirectives": "warn",
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib"
|
||||
"typescript.tsdk": "node_modules/typescript/lib"
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
# T3 Code
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex, Claude, and OpenCode, more coming soon).
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> T3 Code currently supports Codex, Claude, and OpenCode.
|
||||
> T3 Code currently supports Codex and Claude.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://developers.openai.com/codex/cli) and run `codex login`
|
||||
> - Claude: install [Claude Code](https://claude.com/product/claude-code) and run `claude auth login`
|
||||
> - OpenCode: install [OpenCode](https://opencode.ai) and run `opencode auth login`
|
||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||
> - Claude: install Claude Code and run `claude auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
@@ -50,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).
|
||||
@@ -22,41 +22,9 @@ If you are already running the desktop app and want to make it reachable from ot
|
||||
|
||||
1. Open **Settings** → **Connections**.
|
||||
2. Under **Manage Local Backend**, toggle **Network access** on. This will restart the app and run the backend on all network interfaces.
|
||||
3. The settings panel will show the default reachable endpoint, with a `+N` control when more endpoints are available. Expand it to inspect alternatives such as loopback, LAN, private-network, or HTTPS endpoints.
|
||||
3. The settings panel will show the address the server is reachable at (e.g. `http://192.168.x.y:3773`).
|
||||
4. Use **Create Link** to generate a pairing link you can share with another device.
|
||||
|
||||
The default endpoint controls the QR code and primary copy action for pairing links. You can change it from the expanded endpoint list. The preference is stored by endpoint type, so choosing the local LAN endpoint survives normal IP address changes when you move between networks.
|
||||
|
||||
When no user default is saved, the app uses the built-in LAN endpoint for pairing links when
|
||||
available. You can set another endpoint as the default from the expanded endpoint list.
|
||||
|
||||
- HTTPS/WSS-compatible endpoints work from `https://app.t3.codes`, but are not made the default
|
||||
automatically.
|
||||
- Non-loopback HTTP endpoints are useful for direct LAN pairing.
|
||||
- Loopback-only endpoints are not useful for another device unless that device is the same machine.
|
||||
|
||||
If the copied link points directly at `http://192.168.x.y:3773`, open it from a client that can reach that LAN address. If it points at `https://app.t3.codes/pair?...`, the hosted web app will save the environment and connect directly to the backend URL in the link.
|
||||
|
||||
### Tailscale Endpoints
|
||||
|
||||
When the desktop app can detect Tailscale, it adds Tailnet endpoints to the reachable endpoint list.
|
||||
|
||||
Depending on your Tailscale setup, this may include:
|
||||
|
||||
- the machine's `100.x.y.z` Tailnet IP
|
||||
- a MagicDNS name
|
||||
- an HTTPS MagicDNS endpoint when Tailscale Serve is configured for this backend
|
||||
|
||||
The Tailscale HTTPS endpoint uses the clean MagicDNS URL, such as
|
||||
`https://machine.tailnet.ts.net/`, and is disabled until the app verifies that the URL reaches this
|
||||
backend. Use **Setup** on the Tailscale HTTPS row to opt in. The desktop app restarts the backend
|
||||
with the same server-side behavior as `t3 serve --tailscale-serve`, then the server asks Tailscale
|
||||
Serve to proxy HTTPS traffic to the local backend.
|
||||
|
||||
The Tailscale support is an endpoint provider add-on. The core remote model still works without Tailscale: LAN HTTP endpoints, custom HTTPS endpoints, future tunnels, and SSH-launched environments all use the same saved environment and pairing flow.
|
||||
|
||||
For `https://app.t3.codes`, prefer an HTTPS Tailnet or other HTTPS endpoint. A plain `http://100.x.y.z:3773` endpoint can still work from a desktop client or another browser page served over HTTP, but it will not work from the hosted HTTPS app because of browser mixed-content rules.
|
||||
|
||||
### Option 2: Headless Server (CLI)
|
||||
|
||||
Use this when you want to run the server without a GUI, for example on a remote machine over SSH.
|
||||
@@ -79,42 +47,14 @@ From there, connect from another device in either of these ways:
|
||||
- scan the QR code on your phone
|
||||
- in the desktop app, enter the full pairing URL
|
||||
- in the desktop app, enter the host and token separately
|
||||
- in the hosted web app, open a hosted pairing URL when the backend is reachable over HTTPS
|
||||
|
||||
Use `t3 serve --help` for the full flag reference. It supports the same general startup options as the normal server command, including an optional `cwd` argument.
|
||||
|
||||
For hosted web pairing over Tailscale HTTPS, opt in to Tailscale Serve:
|
||||
|
||||
```bash
|
||||
npx t3 serve --tailscale-serve
|
||||
```
|
||||
|
||||
By default this configures Tailscale Serve on HTTPS port 443 and advertises
|
||||
`https://machine.tailnet.ts.net/`. Advanced users can choose a different HTTPS port:
|
||||
|
||||
```bash
|
||||
npx t3 serve --tailscale-serve --tailscale-serve-port 8443
|
||||
```
|
||||
|
||||
> Note
|
||||
> The GUIs do not currently support adding projects on remote environments.
|
||||
> For now, use `t3 project ...` on the server machine instead.
|
||||
> Full GUI support for remote project management is coming soon.
|
||||
|
||||
### Option 3: Desktop-Managed SSH Launch
|
||||
|
||||
Use this when you want the desktop app to start or reuse T3 Code on another machine over SSH.
|
||||
|
||||
1. Open **Settings** → **Connections**.
|
||||
2. Under **Remote Environments**, choose **Add environment**.
|
||||
3. Select the SSH launch flow.
|
||||
4. Enter the SSH target, such as `[email protected]`.
|
||||
5. Confirm the launch. The desktop app probes the host, starts or reuses a remote T3 server, opens a local port forward, and saves the environment.
|
||||
|
||||
After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint. The remote host still owns the actual T3 server, projects, files, git state, terminals, and provider sessions.
|
||||
|
||||
SSH launch is a desktop feature because it needs local process and SSH access. Once the environment is paired and saved, it uses the same environment list and connection model as direct LAN, Tailscale, HTTPS, or future tunnel-backed environments.
|
||||
|
||||
## How Pairing Works
|
||||
|
||||
The remote device does not need a long-lived secret up front.
|
||||
@@ -127,20 +67,6 @@ Instead:
|
||||
|
||||
After pairing, future access is session-based. You do not need to keep reusing the original token unless you are pairing a new device.
|
||||
|
||||
## Hosted Web App Pairing
|
||||
|
||||
The hosted web app at `https://app.t3.codes` can save a remote backend in browser local storage from a URL like:
|
||||
|
||||
```text
|
||||
https://app.t3.codes/pair?host=https://backend.example.com:3773#token=PAIRCODE
|
||||
```
|
||||
|
||||
Use hosted pairing when the backend is reachable from the browser over HTTPS/WSS. This includes a backend behind a trusted HTTPS tunnel or another HTTPS endpoint you operate.
|
||||
|
||||
Do not use hosted pairing for plain HTTP LAN URLs such as `http://192.168.x.y:3773`. Browsers block an HTTPS page from connecting to an insecure HTTP or WS backend. For those endpoints, use the direct pairing URL shown by the desktop app or CLI from a client that can open that HTTP URL directly.
|
||||
|
||||
Hosted pairing does not proxy traffic through T3 Code. The browser still connects directly to the backend URL in the pairing link.
|
||||
|
||||
## Managing Access Later
|
||||
|
||||
Use `t3 auth` to manage access after the initial pairing flow.
|
||||
@@ -158,5 +84,4 @@ Use `t3 auth --help` and the nested subcommand help pages for the full reference
|
||||
- Treat pairing URLs and pairing tokens like passwords.
|
||||
- Prefer binding `--host` to a trusted private address, such as a Tailnet IP, instead of exposing the server broadly.
|
||||
- Anyone with a valid pairing credential can create a session until that credential expires or is revoked.
|
||||
- Hosted pairing links keep the credential in the URL hash so it is not sent to the hosted app server, but it can still be exposed through browser history, screenshots, logs, or copy/paste.
|
||||
- Use `t3 auth` to revoke credentials or sessions you no longer trust.
|
||||
@@ -1,34 +1,27 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.17",
|
||||
"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"
|
||||
},
|
||||
"dependencies": {
|
||||
"@effect/platform-node": "catalog:",
|
||||
"effect": "catalog:",
|
||||
"electron": "40.9.3",
|
||||
"electron-updater": "^6.6.2",
|
||||
"jsonc-parser": "^3.3.1"
|
||||
"electron": "40.6.0",
|
||||
"electron-updater": "^6.6.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/ssh": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { BackendReadinessAbortedError } from "./backendReadiness.ts";
|
||||
import { waitForBackendStartupReady } from "./backendStartupReadiness.ts";
|
||||
|
||||
describe("waitForBackendStartupReady", () => {
|
||||
it("falls back to the HTTP probe when no listening signal exists", async () => {
|
||||
const waitForHttpReady = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
const cancelHttpWait = vi.fn();
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("http");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the listening signal and cancels the HTTP probe", async () => {
|
||||
let rejectHttpWait: ((error: unknown) => void) | null = null;
|
||||
const waitForHttpReady = vi.fn(
|
||||
() =>
|
||||
new Promise<void>((_resolve, reject) => {
|
||||
rejectHttpWait = reject;
|
||||
}),
|
||||
);
|
||||
const cancelHttpWait = vi.fn(() => {
|
||||
rejectHttpWait?.(new BackendReadinessAbortedError());
|
||||
});
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.resolve(),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait,
|
||||
}),
|
||||
).resolves.toBe("listening");
|
||||
|
||||
expect(waitForHttpReady).toHaveBeenCalledTimes(1);
|
||||
expect(cancelHttpWait).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("rejects when the listening signal fails before HTTP readiness", async () => {
|
||||
const error = new Error("backend exited");
|
||||
const waitForHttpReady = vi.fn(() => new Promise<void>(() => {}));
|
||||
|
||||
await expect(
|
||||
waitForBackendStartupReady({
|
||||
listeningPromise: Promise.reject(error),
|
||||
waitForHttpReady,
|
||||
cancelHttpWait: vi.fn(),
|
||||
}),
|
||||
).rejects.toBe(error);
|
||||
});
|
||||
});
|
||||
@@ -1,56 +0,0 @@
|
||||
import { isBackendReadinessAborted } from "./backendReadiness.ts";
|
||||
|
||||
export interface WaitForBackendStartupReadyOptions {
|
||||
readonly listeningPromise?: Promise<void> | null;
|
||||
readonly waitForHttpReady: () => Promise<void>;
|
||||
readonly cancelHttpWait: () => void;
|
||||
}
|
||||
|
||||
export async function waitForBackendStartupReady(
|
||||
options: WaitForBackendStartupReadyOptions,
|
||||
): Promise<"listening" | "http"> {
|
||||
const httpReadyPromise = options.waitForHttpReady();
|
||||
const listeningPromise = options.listeningPromise;
|
||||
|
||||
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") {
|
||||
options.cancelHttpWait();
|
||||
}
|
||||
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);
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -18,7 +18,7 @@ import {
|
||||
writeSavedEnvironmentRegistry,
|
||||
writeSavedEnvironmentSecret,
|
||||
type DesktopSecretStorage,
|
||||
} from "./clientPersistence.ts";
|
||||
} from "./clientPersistence";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
@@ -49,22 +49,12 @@ function makeSecretStorage(available: boolean): DesktopSecretStorage {
|
||||
}
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
diffIgnoreWhitespace: true,
|
||||
diffWordWrap: true,
|
||||
favorites: [],
|
||||
providerModelPreferences: {},
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
sidebarProjectGroupingOverrides: {
|
||||
"environment-1:/tmp/project-a": "separate",
|
||||
},
|
||||
sidebarProjectSortOrder: "manual",
|
||||
sidebarThreadSortOrder: "created_at",
|
||||
timestampFormat: "24-hour",
|
||||
themePreference: { mode: "system" },
|
||||
};
|
||||
|
||||
const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
@@ -74,12 +64,6 @@ const savedRegistryRecord: PersistedSavedEnvironmentRecord = {
|
||||
wsBaseUrl: "wss://remote.example.com/",
|
||||
createdAt: "2026-04-09T00:00:00.000Z",
|
||||
lastConnectedAt: "2026-04-09T01:00:00.000Z",
|
||||
desktopSsh: {
|
||||
alias: "devbox",
|
||||
hostname: "devbox.example.com",
|
||||
username: "julius",
|
||||
port: 22,
|
||||
},
|
||||
};
|
||||
|
||||
describe("clientPersistence", () => {
|
||||
|
||||
@@ -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;
|
||||
@@ -57,12 +52,6 @@ function isPersistedSavedEnvironmentStorageRecord(
|
||||
typeof value.wsBaseUrl === "string" &&
|
||||
typeof value.createdAt === "string" &&
|
||||
(value.lastConnectedAt === null || typeof value.lastConnectedAt === "string") &&
|
||||
(value.desktopSsh === undefined ||
|
||||
(Predicate.isObject(value.desktopSsh) &&
|
||||
typeof value.desktopSsh.alias === "string" &&
|
||||
typeof value.desktopSsh.hostname === "string" &&
|
||||
(value.desktopSsh.username === null || typeof value.desktopSsh.username === "string") &&
|
||||
(value.desktopSsh.port === null || typeof value.desktopSsh.port === "number"))) &&
|
||||
(value.encryptedBearerToken === undefined || typeof value.encryptedBearerToken === "string")
|
||||
);
|
||||
}
|
||||
@@ -83,7 +72,7 @@ function readSavedEnvironmentRegistryDocument(filePath: string): SavedEnvironmen
|
||||
function toPersistedSavedEnvironmentRecord(
|
||||
record: PersistedSavedEnvironmentStorageRecord,
|
||||
): PersistedSavedEnvironmentRecord {
|
||||
const nextRecord = {
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
@@ -91,19 +80,10 @@ function toPersistedSavedEnvironmentRecord(
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
};
|
||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
||||
}
|
||||
|
||||
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 {
|
||||
@@ -141,7 +121,6 @@ export function writeSavedEnvironmentRegistry(
|
||||
wsBaseUrl: record.wsBaseUrl,
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
...(record.desktopSsh ? { desktopSsh: record.desktopSsh } : {}),
|
||||
encryptedBearerToken,
|
||||
}
|
||||
: record;
|
||||
@@ -197,7 +176,7 @@ export function writeSavedEnvironmentSecret(input: {
|
||||
const encryptedBearerToken = input.secretStorage
|
||||
.encryptString(input.secret)
|
||||
.toString("base64");
|
||||
const nextRecord = {
|
||||
return {
|
||||
environmentId: record.environmentId,
|
||||
label: record.label,
|
||||
httpBaseUrl: record.httpBaseUrl,
|
||||
@@ -205,8 +184,7 @@ export function writeSavedEnvironmentSecret(input: {
|
||||
createdAt: record.createdAt,
|
||||
lastConnectedAt: record.lastConnectedAt,
|
||||
encryptedBearerToken,
|
||||
};
|
||||
return record.desktopSsh ? { ...nextRecord, desktopSsh: record.desktopSsh } : nextRecord;
|
||||
} satisfies PersistedSavedEnvironmentStorageRecord;
|
||||
}),
|
||||
} satisfies SavedEnvironmentRegistryDocument);
|
||||
return found;
|
||||
|
||||
@@ -11,7 +11,7 @@ vi.mock("electron", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog.ts";
|
||||
import { showDesktopConfirmDialog } from "./confirmDialog";
|
||||
|
||||
describe("showDesktopConfirmDialog", () => {
|
||||
beforeEach(() => {
|
||||
|
||||
@@ -7,12 +7,9 @@ import { afterEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_DESKTOP_SETTINGS,
|
||||
readDesktopSettings,
|
||||
resolveDefaultDesktopSettings,
|
||||
setDesktopServerExposurePreference,
|
||||
setDesktopTailscaleServePreference,
|
||||
setDesktopUpdateChannelPreference,
|
||||
writeDesktopSettings,
|
||||
} from "./desktopSettings.ts";
|
||||
} from "./desktopSettings";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
@@ -30,17 +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",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
expect(readDesktopSettings(makeSettingsPath())).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
|
||||
it("persists and reloads the configured server exposure mode", () => {
|
||||
@@ -48,18 +35,10 @@ describe("desktopSettings", () => {
|
||||
|
||||
writeDesktopSettings(settingsPath, {
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||
expect(readDesktopSettings(settingsPath)).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,82 +47,11 @@ describe("desktopSettings", () => {
|
||||
setDesktopServerExposurePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"network-accessible",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "network-accessible",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists the requested Tailscale Serve preference", () => {
|
||||
expect(
|
||||
setDesktopTailscaleServePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
{ enabled: true, port: 8443 },
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the configured Tailscale Serve port when no new port is requested", () => {
|
||||
expect(
|
||||
setDesktopTailscaleServePreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
{ enabled: true },
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("persists the requested nightly update channel", () => {
|
||||
expect(
|
||||
setDesktopUpdateChannelPreference(
|
||||
{
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
},
|
||||
"nightly",
|
||||
),
|
||||
).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "nightly",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -151,80 +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",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
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",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
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",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("falls back to the default Tailscale Serve port when the persisted port is invalid", () => {
|
||||
const settingsPath = makeSettingsPath();
|
||||
fs.writeFileSync(
|
||||
settingsPath,
|
||||
JSON.stringify({
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 0,
|
||||
}),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
expect(readDesktopSettings(settingsPath, "0.0.17")).toEqual({
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 443,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
});
|
||||
expect(readDesktopSettings(settingsPath)).toEqual(DEFAULT_DESKTOP_SETTINGS);
|
||||
});
|
||||
});
|
||||
@@ -1,34 +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 tailscaleServeEnabled: boolean;
|
||||
readonly tailscaleServePort: number;
|
||||
readonly updateChannel: DesktopUpdateChannel;
|
||||
readonly updateChannelConfiguredByUser: boolean;
|
||||
}
|
||||
|
||||
export const DEFAULT_TAILSCALE_SERVE_PORT = 443;
|
||||
|
||||
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
|
||||
serverExposureMode: "local-only",
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: DEFAULT_TAILSCALE_SERVE_PORT,
|
||||
updateChannel: "latest",
|
||||
updateChannelConfiguredByUser: false,
|
||||
};
|
||||
|
||||
export function resolveDefaultDesktopSettings(appVersion: string): DesktopSettings {
|
||||
return {
|
||||
...DEFAULT_DESKTOP_SETTINGS,
|
||||
updateChannel: resolveDefaultDesktopUpdateChannel(appVersion),
|
||||
};
|
||||
}
|
||||
|
||||
export function setDesktopServerExposurePreference(
|
||||
settings: DesktopSettings,
|
||||
requestedMode: DesktopServerExposureMode,
|
||||
@@ -41,78 +22,23 @@ export function setDesktopServerExposurePreference(
|
||||
};
|
||||
}
|
||||
|
||||
export function setDesktopTailscaleServePreference(
|
||||
settings: DesktopSettings,
|
||||
input: { readonly enabled: boolean; readonly port?: number },
|
||||
): DesktopSettings {
|
||||
const port =
|
||||
input.port === undefined
|
||||
? settings.tailscaleServePort
|
||||
: normalizeTailscaleServePort(input.port);
|
||||
return settings.tailscaleServeEnabled === input.enabled && settings.tailscaleServePort === port
|
||||
? settings
|
||||
: {
|
||||
...settings,
|
||||
tailscaleServeEnabled: input.enabled,
|
||||
tailscaleServePort: port,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeTailscaleServePort(value: unknown): number {
|
||||
return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65_535
|
||||
? value
|
||||
: DEFAULT_TAILSCALE_SERVE_PORT;
|
||||
}
|
||||
|
||||
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 tailscaleServeEnabled?: unknown;
|
||||
readonly tailscaleServePort?: 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",
|
||||
tailscaleServeEnabled: parsed.tailscaleServeEnabled === true,
|
||||
tailscaleServePort: normalizeTailscaleServePort(parsed.tailscaleServePort),
|
||||
updateChannel:
|
||||
updateChannelConfiguredByUser && parsedUpdateChannel !== null
|
||||
? parsedUpdateChannel
|
||||
: defaultSettings.updateChannel,
|
||||
updateChannelConfiguredByUser,
|
||||
};
|
||||
} catch {
|
||||
return defaultSettings;
|
||||
return DEFAULT_DESKTOP_SETTINGS;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+103
-540
File diff suppressed because it is too large.
Load diff
@@ -4,20 +4,14 @@ import type { DesktopBridge } from "@t3tools/contracts";
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const DISCOVER_COLOR_THEMES_CHANNEL = "desktop:discover-color-themes";
|
||||
const LOAD_COLOR_THEME_CHANNEL = "desktop:load-color-theme";
|
||||
const GET_EDITOR_THEME_PREFERENCES_CHANNEL = "desktop:get-editor-theme-preferences";
|
||||
const SET_WINDOW_THEME_COLORS_CHANNEL = "desktop:set-window-theme-colors";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
const UPDATE_STATE_CHANNEL = "desktop:update-state";
|
||||
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
|
||||
const UPDATE_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,45 +20,10 @@ const SET_SAVED_ENVIRONMENT_REGISTRY_CHANNEL = "desktop:set-saved-environment-re
|
||||
const GET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:get-saved-environment-secret";
|
||||
const SET_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:set-saved-environment-secret";
|
||||
const REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL = "desktop:remove-saved-environment-secret";
|
||||
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
|
||||
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
|
||||
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
|
||||
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
|
||||
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
|
||||
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
|
||||
const GET_SERVER_EXPOSURE_STATE_CHANNEL = "desktop:get-server-exposure-state";
|
||||
const SET_SERVER_EXPOSURE_MODE_CHANNEL = "desktop:set-server-exposure-mode";
|
||||
const SET_TAILSCALE_SERVE_ENABLED_CHANNEL = "desktop:set-tailscale-serve-enabled";
|
||||
const GET_ADVERTISED_ENDPOINTS_CHANNEL = "desktop:get-advertised-endpoints";
|
||||
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
|
||||
function unwrapEnsureSshEnvironmentResult(result: unknown) {
|
||||
if (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"type" in result &&
|
||||
result.type === SSH_PASSWORD_PROMPT_CANCELLED_RESULT
|
||||
) {
|
||||
const message =
|
||||
"message" in result && typeof result.message === "string"
|
||||
? result.message
|
||||
: "SSH authentication cancelled.";
|
||||
throw new Error(message);
|
||||
}
|
||||
return result as Awaited<ReturnType<DesktopBridge["ensureSshEnvironment"]>>;
|
||||
}
|
||||
|
||||
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) {
|
||||
@@ -83,46 +42,11 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
ipcRenderer.invoke(SET_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId, secret),
|
||||
removeSavedEnvironmentSecret: (environmentId) =>
|
||||
ipcRenderer.invoke(REMOVE_SAVED_ENVIRONMENT_SECRET_CHANNEL, environmentId),
|
||||
discoverSshHosts: () => ipcRenderer.invoke(DISCOVER_SSH_HOSTS_CHANNEL),
|
||||
ensureSshEnvironment: async (target, options) =>
|
||||
unwrapEnsureSshEnvironmentResult(
|
||||
await ipcRenderer.invoke(ENSURE_SSH_ENVIRONMENT_CHANNEL, target, options),
|
||||
),
|
||||
disconnectSshEnvironment: (target) =>
|
||||
ipcRenderer.invoke(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, target),
|
||||
fetchSshEnvironmentDescriptor: (httpBaseUrl) =>
|
||||
ipcRenderer.invoke(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, httpBaseUrl),
|
||||
bootstrapSshBearerSession: (httpBaseUrl, credential) =>
|
||||
ipcRenderer.invoke(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL, httpBaseUrl, credential),
|
||||
fetchSshSessionState: (httpBaseUrl, bearerToken) =>
|
||||
ipcRenderer.invoke(FETCH_SSH_SESSION_STATE_CHANNEL, httpBaseUrl, bearerToken),
|
||||
issueSshWebSocketToken: (httpBaseUrl, bearerToken) =>
|
||||
ipcRenderer.invoke(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL, httpBaseUrl, bearerToken),
|
||||
onSshPasswordPrompt: (listener) => {
|
||||
const wrappedListener = (_event: Electron.IpcRendererEvent, request: unknown) => {
|
||||
if (typeof request !== "object" || request === null) return;
|
||||
listener(request as Parameters<typeof listener>[0]);
|
||||
};
|
||||
|
||||
ipcRenderer.on(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
|
||||
return () => {
|
||||
ipcRenderer.removeListener(SSH_PASSWORD_PROMPT_CHANNEL, wrappedListener);
|
||||
};
|
||||
},
|
||||
resolveSshPasswordPrompt: (requestId, password) =>
|
||||
ipcRenderer.invoke(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL, requestId, password),
|
||||
getServerExposureState: () => ipcRenderer.invoke(GET_SERVER_EXPOSURE_STATE_CHANNEL),
|
||||
setServerExposureMode: (mode) => ipcRenderer.invoke(SET_SERVER_EXPOSURE_MODE_CHANNEL, mode),
|
||||
setTailscaleServeEnabled: (input) =>
|
||||
ipcRenderer.invoke(SET_TAILSCALE_SERVE_ENABLED_CHANNEL, input),
|
||||
getAdvertisedEndpoints: () => ipcRenderer.invoke(GET_ADVERTISED_ENDPOINTS_CHANNEL),
|
||||
pickFolder: (options) => ipcRenderer.invoke(PICK_FOLDER_CHANNEL, options),
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
discoverColorThemes: () => ipcRenderer.invoke(DISCOVER_COLOR_THEMES_CHANNEL),
|
||||
loadColorTheme: (themeId) => ipcRenderer.invoke(LOAD_COLOR_THEME_CHANNEL, themeId),
|
||||
getEditorThemePreferences: () => ipcRenderer.invoke(GET_EDITOR_THEME_PREFERENCES_CHANNEL),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
setWindowThemeColors: (input) => ipcRenderer.invoke(SET_WINDOW_THEME_COLORS_CHANNEL, input),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
@@ -137,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,10 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
resolveDesktopCoreAdvertisedEndpoints,
|
||||
resolveDesktopServerExposure,
|
||||
resolveLanAdvertisedHost,
|
||||
} from "./serverExposure.ts";
|
||||
import { resolveDesktopServerExposure, resolveLanAdvertisedHost } from "./serverExposure";
|
||||
|
||||
describe("resolveLanAdvertisedHost", () => {
|
||||
it("prefers an explicit host override", () => {
|
||||
@@ -78,121 +74,6 @@ describe("resolveLanAdvertisedHost", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopCoreAdvertisedEndpoints", () => {
|
||||
it("advertises loopback and LAN endpoints without provider-specific assumptions", () => {
|
||||
const exposure = resolveDesktopServerExposure({
|
||||
mode: "network-accessible",
|
||||
port: 3773,
|
||||
networkInterfaces: {
|
||||
en0: [
|
||||
{
|
||||
address: "192.168.1.44",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.255.255.0",
|
||||
cidr: "192.168.1.44/24",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveDesktopCoreAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
exposure,
|
||||
customHttpsEndpointUrls: [
|
||||
"https://desktop.example.ts.net",
|
||||
"http://desktop.example.test:3773",
|
||||
"not-a-url",
|
||||
],
|
||||
}),
|
||||
).toEqual([
|
||||
{
|
||||
id: "desktop-loopback:3773",
|
||||
label: "This machine",
|
||||
provider: {
|
||||
id: "desktop-core",
|
||||
label: "Desktop",
|
||||
kind: "core",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "http://127.0.0.1:3773/",
|
||||
wsBaseUrl: "ws://127.0.0.1:3773/",
|
||||
reachability: "loopback",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-core",
|
||||
status: "available",
|
||||
description: "Loopback endpoint for this desktop app.",
|
||||
},
|
||||
{
|
||||
id: "desktop-lan:http://192.168.1.44:3773",
|
||||
label: "Local network",
|
||||
provider: {
|
||||
id: "desktop-core",
|
||||
label: "Desktop",
|
||||
kind: "core",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "http://192.168.1.44:3773/",
|
||||
wsBaseUrl: "ws://192.168.1.44:3773/",
|
||||
reachability: "lan",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-core",
|
||||
status: "available",
|
||||
isDefault: true,
|
||||
description: "Reachable from devices on the same network.",
|
||||
},
|
||||
{
|
||||
id: "manual:https://desktop.example.ts.net",
|
||||
label: "Custom HTTPS",
|
||||
provider: {
|
||||
id: "manual",
|
||||
label: "Manual",
|
||||
kind: "manual",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "https://desktop.example.ts.net/",
|
||||
wsBaseUrl: "wss://desktop.example.ts.net/",
|
||||
reachability: "public",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "compatible",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "user",
|
||||
status: "unknown",
|
||||
description: "User-configured HTTPS endpoint for this desktop backend.",
|
||||
},
|
||||
{
|
||||
id: "manual:http://desktop.example.test:3773",
|
||||
label: "Custom endpoint",
|
||||
provider: {
|
||||
id: "manual",
|
||||
label: "Manual",
|
||||
kind: "manual",
|
||||
isAddon: false,
|
||||
},
|
||||
httpBaseUrl: "http://desktop.example.test:3773/",
|
||||
wsBaseUrl: "ws://desktop.example.test:3773/",
|
||||
reachability: "public",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "user",
|
||||
status: "unknown",
|
||||
description: "User-configured endpoint for this desktop backend.",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveDesktopServerExposure", () => {
|
||||
it("keeps the desktop server loopback-only when local-only mode is selected", () => {
|
||||
expect(
|
||||
|
||||
@@ -1,13 +1,5 @@
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type {
|
||||
AdvertisedEndpoint,
|
||||
AdvertisedEndpointProvider,
|
||||
DesktopServerExposureMode,
|
||||
} from "@t3tools/contracts";
|
||||
import type { DesktopServerExposureMode } from "@t3tools/contracts";
|
||||
|
||||
const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
|
||||
const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
|
||||
@@ -21,26 +13,6 @@ export interface DesktopServerExposure {
|
||||
readonly advertisedHost: string | null;
|
||||
}
|
||||
|
||||
export interface DesktopAdvertisedEndpointInput {
|
||||
readonly port: number;
|
||||
readonly exposure: DesktopServerExposure;
|
||||
readonly customHttpsEndpointUrls?: readonly string[];
|
||||
}
|
||||
|
||||
const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
id: "desktop-core",
|
||||
label: "Desktop",
|
||||
kind: "core",
|
||||
isAddon: false,
|
||||
};
|
||||
|
||||
const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
id: "manual",
|
||||
label: "Manual",
|
||||
kind: "manual",
|
||||
isAddon: false,
|
||||
};
|
||||
|
||||
const normalizeOptionalHost = (value: string | undefined): string | undefined => {
|
||||
const normalized = value?.trim();
|
||||
return normalized && normalized.length > 0 ? normalized : undefined;
|
||||
@@ -49,14 +21,6 @@ const normalizeOptionalHost = (value: string | undefined): string | undefined =>
|
||||
const isUsableLanIpv4Address = (address: string): boolean =>
|
||||
!address.startsWith("127.") && !address.startsWith("169.254.");
|
||||
|
||||
function isHttpsEndpointUrl(value: string): boolean {
|
||||
try {
|
||||
return new URL(value).protocol === "https:";
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function resolveLanAdvertisedHost(
|
||||
networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>,
|
||||
explicitHost: string | undefined,
|
||||
@@ -114,75 +78,3 @@ export function resolveDesktopServerExposure(input: {
|
||||
advertisedHost,
|
||||
};
|
||||
}
|
||||
|
||||
function createDesktopEndpoint(
|
||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
||||
): AdvertisedEndpoint {
|
||||
return createAdvertisedEndpoint({
|
||||
...input,
|
||||
provider: DESKTOP_CORE_ENDPOINT_PROVIDER,
|
||||
source: "desktop-core",
|
||||
});
|
||||
}
|
||||
|
||||
function createManualEndpoint(
|
||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
||||
): AdvertisedEndpoint {
|
||||
return createAdvertisedEndpoint({
|
||||
...input,
|
||||
provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER,
|
||||
source: "user",
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveDesktopCoreAdvertisedEndpoints(
|
||||
input: DesktopAdvertisedEndpointInput,
|
||||
): readonly AdvertisedEndpoint[] {
|
||||
const endpoints: AdvertisedEndpoint[] = [
|
||||
createDesktopEndpoint({
|
||||
id: `desktop-loopback:${input.port}`,
|
||||
label: "This machine",
|
||||
httpBaseUrl: input.exposure.localHttpUrl,
|
||||
reachability: "loopback",
|
||||
status: "available",
|
||||
description: "Loopback endpoint for this desktop app.",
|
||||
}),
|
||||
];
|
||||
|
||||
if (input.exposure.endpointUrl) {
|
||||
endpoints.push(
|
||||
createDesktopEndpoint({
|
||||
id: `desktop-lan:${input.exposure.endpointUrl}`,
|
||||
label: "Local network",
|
||||
httpBaseUrl: input.exposure.endpointUrl,
|
||||
reachability: "lan",
|
||||
status: "available",
|
||||
isDefault: true,
|
||||
description: "Reachable from devices on the same network.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
|
||||
try {
|
||||
const isHttpsEndpoint = isHttpsEndpointUrl(customEndpointUrl);
|
||||
endpoints.push(
|
||||
createManualEndpoint({
|
||||
id: `manual:${customEndpointUrl}`,
|
||||
label: isHttpsEndpoint ? "Custom HTTPS" : "Custom endpoint",
|
||||
httpBaseUrl: customEndpointUrl,
|
||||
reachability: "public",
|
||||
...(isHttpsEndpoint ? ({ hostedHttpsCompatibility: "compatible" } as const) : {}),
|
||||
status: "unknown",
|
||||
description: isHttpsEndpoint
|
||||
? "User-configured HTTPS endpoint for this desktop backend."
|
||||
: "User-configured endpoint for this desktop backend.",
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Ignore malformed user-configured endpoints without dropping valid endpoints.
|
||||
}
|
||||
}
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
@@ -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,98 +0,0 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
|
||||
|
||||
import { discoverDesktopSshHosts, isSshPasswordPromptCancellation } from "./sshEnvironment.ts";
|
||||
|
||||
const tempDirectories: string[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const directory of tempDirectories.splice(0)) {
|
||||
FS.rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function makeTempHomeDir(): string {
|
||||
const directory = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-ssh-env-test-"));
|
||||
tempDirectories.push(directory);
|
||||
return directory;
|
||||
}
|
||||
|
||||
describe("sshEnvironment", () => {
|
||||
it("treats password prompt timeouts as cancellable authentication prompts", () => {
|
||||
expect(
|
||||
isSshPasswordPromptCancellation(
|
||||
new SshPasswordPromptError({
|
||||
message: "SSH authentication timed out for devbox.",
|
||||
}),
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("wires desktop host discovery through the ssh package runtime", async () => {
|
||||
const homeDir = makeTempHomeDir();
|
||||
const sshDir = Path.join(homeDir, ".ssh");
|
||||
FS.mkdirSync(Path.join(sshDir, "config.d"), { recursive: true });
|
||||
FS.writeFileSync(
|
||||
Path.join(sshDir, "config"),
|
||||
["Host devbox", " HostName devbox.example.com", "Include config.d/*.conf", ""].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
FS.writeFileSync(
|
||||
Path.join(sshDir, "config.d", "team.conf"),
|
||||
[
|
||||
"Host staging",
|
||||
" HostName staging.example.com",
|
||||
"Host *",
|
||||
" ServerAliveInterval 30",
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
FS.writeFileSync(
|
||||
Path.join(sshDir, "known_hosts"),
|
||||
[
|
||||
"known.example.com ssh-ed25519 AAAA",
|
||||
"|1|hashed|entry ssh-ed25519 AAAA",
|
||||
"[bastion.example.com]:2222 ssh-ed25519 AAAA",
|
||||
"",
|
||||
].join("\n"),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
await expect(discoverDesktopSshHosts({ homeDir })).resolves.toEqual([
|
||||
{
|
||||
alias: "bastion.example.com",
|
||||
hostname: "bastion.example.com",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "known-hosts",
|
||||
},
|
||||
{
|
||||
alias: "devbox",
|
||||
hostname: "devbox",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "ssh-config",
|
||||
},
|
||||
{
|
||||
alias: "known.example.com",
|
||||
hostname: "known.example.com",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "known-hosts",
|
||||
},
|
||||
{
|
||||
alias: "staging",
|
||||
hostname: "staging",
|
||||
username: null,
|
||||
port: null,
|
||||
source: "ssh-config",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,420 +0,0 @@
|
||||
import * as Crypto from "node:crypto";
|
||||
|
||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import type {
|
||||
AuthBearerBootstrapResult,
|
||||
AuthSessionState,
|
||||
AuthWebSocketTokenResult,
|
||||
DesktopDiscoveredSshHost,
|
||||
DesktopSshEnvironmentTarget,
|
||||
DesktopSshPasswordPromptRequest,
|
||||
ExecutionEnvironmentDescriptor,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
SshPasswordPrompt,
|
||||
type SshPasswordPromptShape,
|
||||
type SshPasswordRequest,
|
||||
} from "@t3tools/ssh/auth";
|
||||
import { discoverSshHosts } from "@t3tools/ssh/config";
|
||||
import { SshPasswordPromptError } from "@t3tools/ssh/errors";
|
||||
import {
|
||||
fetchLoopbackSshJson,
|
||||
SshEnvironmentManager,
|
||||
type RemoteT3RunnerOptions,
|
||||
} from "@t3tools/ssh/tunnel";
|
||||
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
|
||||
|
||||
export { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
|
||||
|
||||
const DISCOVER_SSH_HOSTS_CHANNEL = "desktop:discover-ssh-hosts";
|
||||
const ENSURE_SSH_ENVIRONMENT_CHANNEL = "desktop:ensure-ssh-environment";
|
||||
const DISCONNECT_SSH_ENVIRONMENT_CHANNEL = "desktop:disconnect-ssh-environment";
|
||||
const FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL = "desktop:fetch-ssh-environment-descriptor";
|
||||
const BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL = "desktop:bootstrap-ssh-bearer-session";
|
||||
const FETCH_SSH_SESSION_STATE_CHANNEL = "desktop:fetch-ssh-session-state";
|
||||
const ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL = "desktop:issue-ssh-websocket-token";
|
||||
const SSH_PASSWORD_PROMPT_CHANNEL = "desktop:ssh-password-prompt";
|
||||
const RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL = "desktop:resolve-ssh-password-prompt";
|
||||
const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
|
||||
const SSH_PASSWORD_PROMPT_CANCELLED_RESULT = "ssh-password-prompt-cancelled";
|
||||
|
||||
interface DesktopSshEnvironmentManagerOptions {
|
||||
readonly passwordProvider?: (request: SshPasswordRequest) => Promise<string | null>;
|
||||
readonly resolveCliPackageSpec?: () => string;
|
||||
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
|
||||
}
|
||||
|
||||
const sshRuntime = ManagedRuntime.make(
|
||||
Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici, NetService.layer),
|
||||
);
|
||||
|
||||
function createDesktopSshRuntime(
|
||||
passwordPrompt: SshPasswordPromptShape,
|
||||
scope: Scope.Scope,
|
||||
options: DesktopSshEnvironmentManagerOptions,
|
||||
) {
|
||||
return ManagedRuntime.make(
|
||||
Layer.mergeAll(
|
||||
NodeServices.layer,
|
||||
NodeHttpClient.layerUndici,
|
||||
NetService.layer,
|
||||
Layer.succeed(Scope.Scope, scope),
|
||||
Layer.succeed(SshPasswordPrompt, SshPasswordPrompt.of(passwordPrompt)),
|
||||
SshEnvironmentManager.layer({
|
||||
...(options.resolveCliPackageSpec === undefined
|
||||
? {}
|
||||
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
|
||||
...(options.resolveCliRunner === undefined
|
||||
? {}
|
||||
: { resolveCliRunner: options.resolveCliRunner }),
|
||||
}),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export async function discoverDesktopSshHosts(input?: {
|
||||
readonly homeDir?: string;
|
||||
}): Promise<readonly DesktopDiscoveredSshHost[]> {
|
||||
return await sshRuntime.runPromise(discoverSshHosts(input ?? {}));
|
||||
}
|
||||
|
||||
export class DesktopSshEnvironmentManager {
|
||||
private readonly runtime: ReturnType<typeof createDesktopSshRuntime>;
|
||||
private readonly scope: Scope.Scope;
|
||||
|
||||
constructor(options: DesktopSshEnvironmentManagerOptions = {}) {
|
||||
const passwordPrompt: SshPasswordPromptShape = {
|
||||
isAvailable: options.passwordProvider !== undefined,
|
||||
request: (request) => {
|
||||
const passwordProvider = options.passwordProvider;
|
||||
if (!passwordProvider) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
|
||||
return Effect.tryPromise({
|
||||
try: () => passwordProvider(request),
|
||||
catch: (cause) =>
|
||||
new SshPasswordPromptError({
|
||||
message: cause instanceof Error ? cause.message : "SSH password prompt failed.",
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
},
|
||||
};
|
||||
this.scope = Effect.runSync(Scope.make());
|
||||
this.runtime = createDesktopSshRuntime(passwordPrompt, this.scope, options);
|
||||
}
|
||||
|
||||
async discoverHosts(): Promise<readonly DesktopDiscoveredSshHost[]> {
|
||||
return await discoverDesktopSshHosts();
|
||||
}
|
||||
|
||||
async ensureEnvironment(
|
||||
target: DesktopSshEnvironmentTarget,
|
||||
options?: { readonly issuePairingToken?: boolean },
|
||||
) {
|
||||
return await this.runtime.runPromise(
|
||||
Effect.service(SshEnvironmentManager).pipe(
|
||||
Effect.flatMap((manager) => manager.ensureEnvironment(target, options)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async disconnectEnvironment(target: DesktopSshEnvironmentTarget): Promise<void> {
|
||||
await this.runtime.runPromise(
|
||||
Effect.service(SshEnvironmentManager).pipe(
|
||||
Effect.flatMap((manager) => manager.disconnectEnvironment(target)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
await this.runtime.runPromise(Scope.close(this.scope, Exit.void));
|
||||
await this.runtime.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
function getSafeDesktopSshTarget(rawTarget: unknown): DesktopSshEnvironmentTarget | null {
|
||||
if (typeof rawTarget !== "object" || rawTarget === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const target = rawTarget as Partial<DesktopSshEnvironmentTarget>;
|
||||
if (typeof target.alias !== "string" || typeof target.hostname !== "string") {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
target.username !== null &&
|
||||
target.username !== undefined &&
|
||||
typeof target.username !== "string"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
if (target.port !== null && target.port !== undefined && !Number.isInteger(target.port)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const alias = target.alias.trim();
|
||||
const hostname = target.hostname.trim();
|
||||
if (alias.length === 0 || hostname.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
alias,
|
||||
hostname,
|
||||
username: target.username?.trim() || null,
|
||||
port: target.port ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Minimal subset of Electron's BrowserWindow used by the SSH bridge. */
|
||||
export interface DesktopSshBridgeWindow {
|
||||
isDestroyed(): boolean;
|
||||
isMinimized(): boolean;
|
||||
restore(): void;
|
||||
focus(): void;
|
||||
readonly webContents: {
|
||||
send(channel: string, ...args: readonly unknown[]): void;
|
||||
};
|
||||
}
|
||||
|
||||
/** Minimal subset of Electron's ipcMain used by the SSH bridge. */
|
||||
export interface DesktopSshBridgeIpcMain {
|
||||
removeHandler(channel: string): void;
|
||||
handle(
|
||||
channel: string,
|
||||
listener: (event: unknown, ...args: readonly unknown[]) => unknown | Promise<unknown>,
|
||||
): void;
|
||||
}
|
||||
|
||||
export interface DesktopSshEnvironmentBridgeOptions {
|
||||
readonly getMainWindow: () => DesktopSshBridgeWindow | null;
|
||||
readonly resolveCliPackageSpec?: () => string;
|
||||
readonly resolveCliRunner?: () => RemoteT3RunnerOptions;
|
||||
readonly passwordPromptTimeoutMs?: number;
|
||||
}
|
||||
|
||||
interface PendingSshPasswordPrompt {
|
||||
readonly resolve: (password: string | null) => void;
|
||||
readonly reject: (error: Error) => void;
|
||||
readonly timeout: ReturnType<typeof setTimeout>;
|
||||
}
|
||||
|
||||
export function isSshPasswordPromptCancellation(error: unknown): error is SshPasswordPromptError {
|
||||
const message = error instanceof SshPasswordPromptError ? error.message.toLowerCase() : "";
|
||||
return (
|
||||
error instanceof SshPasswordPromptError &&
|
||||
(message.includes("cancelled") || message.includes("timed out"))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wires the SSH environment manager to Electron IPC, owning the renderer-facing
|
||||
* password prompt state so `main.ts` only needs to register, cancel, and dispose.
|
||||
*/
|
||||
export class DesktopSshEnvironmentBridge {
|
||||
private readonly options: DesktopSshEnvironmentBridgeOptions;
|
||||
private readonly manager: DesktopSshEnvironmentManager;
|
||||
private readonly pendingPrompts = new Map<string, PendingSshPasswordPrompt>();
|
||||
private readonly passwordPromptTimeoutMs: number;
|
||||
|
||||
constructor(options: DesktopSshEnvironmentBridgeOptions) {
|
||||
this.options = options;
|
||||
this.passwordPromptTimeoutMs =
|
||||
options.passwordPromptTimeoutMs ?? DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS;
|
||||
this.manager = new DesktopSshEnvironmentManager({
|
||||
passwordProvider: (request) => this.requestPasswordFromRenderer(request),
|
||||
...(options.resolveCliPackageSpec === undefined
|
||||
? {}
|
||||
: { resolveCliPackageSpec: options.resolveCliPackageSpec }),
|
||||
...(options.resolveCliRunner === undefined
|
||||
? {}
|
||||
: { resolveCliRunner: options.resolveCliRunner }),
|
||||
});
|
||||
}
|
||||
|
||||
registerIpcHandlers(ipcMain: DesktopSshBridgeIpcMain): void {
|
||||
ipcMain.removeHandler(DISCOVER_SSH_HOSTS_CHANNEL);
|
||||
ipcMain.handle(DISCOVER_SSH_HOSTS_CHANNEL, async () => this.manager.discoverHosts());
|
||||
|
||||
ipcMain.removeHandler(ENSURE_SSH_ENVIRONMENT_CHANNEL);
|
||||
ipcMain.handle(ENSURE_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget, rawOptions) => {
|
||||
const target = getSafeDesktopSshTarget(rawTarget);
|
||||
if (!target) {
|
||||
throw new Error("Invalid desktop SSH target.");
|
||||
}
|
||||
|
||||
const issuePairingToken =
|
||||
typeof rawOptions === "object" &&
|
||||
rawOptions !== null &&
|
||||
"issuePairingToken" in rawOptions &&
|
||||
(rawOptions as { issuePairingToken?: unknown }).issuePairingToken === true;
|
||||
|
||||
try {
|
||||
return await this.manager.ensureEnvironment(target, {
|
||||
issuePairingToken,
|
||||
});
|
||||
} catch (error) {
|
||||
if (isSshPasswordPromptCancellation(error)) {
|
||||
return {
|
||||
type: SSH_PASSWORD_PROMPT_CANCELLED_RESULT,
|
||||
message: error.message,
|
||||
};
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(DISCONNECT_SSH_ENVIRONMENT_CHANNEL);
|
||||
ipcMain.handle(DISCONNECT_SSH_ENVIRONMENT_CHANNEL, async (_event, rawTarget) => {
|
||||
const target = getSafeDesktopSshTarget(rawTarget);
|
||||
if (!target) {
|
||||
throw new Error("Invalid desktop SSH target.");
|
||||
}
|
||||
|
||||
await this.manager.disconnectEnvironment(target);
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL);
|
||||
ipcMain.handle(FETCH_SSH_ENVIRONMENT_DESCRIPTOR_CHANNEL, async (_event, rawHttpBaseUrl) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<ExecutionEnvironmentDescriptor>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/.well-known/t3/environment",
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL);
|
||||
ipcMain.handle(
|
||||
BOOTSTRAP_SSH_BEARER_SESSION_CHANNEL,
|
||||
async (_event, rawHttpBaseUrl, rawCredential) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<AuthBearerBootstrapResult>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/api/auth/bootstrap/bearer",
|
||||
method: "POST",
|
||||
body: { credential: rawCredential },
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(FETCH_SSH_SESSION_STATE_CHANNEL);
|
||||
ipcMain.handle(
|
||||
FETCH_SSH_SESSION_STATE_CHANNEL,
|
||||
async (_event, rawHttpBaseUrl, rawBearerToken) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<AuthSessionState>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/api/auth/session",
|
||||
bearerToken: rawBearerToken,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL);
|
||||
ipcMain.handle(
|
||||
ISSUE_SSH_WEBSOCKET_TOKEN_CHANNEL,
|
||||
async (_event, rawHttpBaseUrl, rawBearerToken) =>
|
||||
sshRuntime.runPromise(
|
||||
fetchLoopbackSshJson<AuthWebSocketTokenResult>({
|
||||
httpBaseUrl: rawHttpBaseUrl,
|
||||
pathname: "/api/auth/ws-token",
|
||||
method: "POST",
|
||||
bearerToken: rawBearerToken,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
ipcMain.removeHandler(RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL);
|
||||
ipcMain.handle(
|
||||
RESOLVE_SSH_PASSWORD_PROMPT_CHANNEL,
|
||||
async (_event, rawRequestId, rawPassword) => {
|
||||
if (typeof rawRequestId !== "string" || rawRequestId.trim().length === 0) {
|
||||
throw new Error("Invalid SSH password prompt id.");
|
||||
}
|
||||
if (rawPassword !== null && typeof rawPassword !== "string") {
|
||||
throw new Error("Invalid SSH password prompt response.");
|
||||
}
|
||||
|
||||
const pending = this.pendingPrompts.get(rawRequestId);
|
||||
if (!pending) {
|
||||
throw new Error("SSH password prompt expired. Try connecting again.");
|
||||
}
|
||||
|
||||
clearTimeout(pending.timeout);
|
||||
this.pendingPrompts.delete(rawRequestId);
|
||||
pending.resolve(rawPassword);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
cancelPendingPasswordPrompts(reason: string): void {
|
||||
for (const [requestId, pending] of this.pendingPrompts) {
|
||||
clearTimeout(pending.timeout);
|
||||
this.pendingPrompts.delete(requestId);
|
||||
pending.reject(new Error(reason));
|
||||
}
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.cancelPendingPasswordPrompts("SSH environment bridge disposed.");
|
||||
await this.manager.dispose();
|
||||
}
|
||||
|
||||
private async requestPasswordFromRenderer(input: SshPasswordRequest): Promise<string | null> {
|
||||
const window = this.options.getMainWindow();
|
||||
if (!window || window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
|
||||
const request: DesktopSshPasswordPromptRequest = {
|
||||
requestId: Crypto.randomUUID(),
|
||||
destination: input.destination,
|
||||
username: input.username,
|
||||
prompt: input.prompt,
|
||||
expiresAt: new Date(Date.now() + this.passwordPromptTimeoutMs).toISOString(),
|
||||
};
|
||||
|
||||
return await new Promise<string | null>((resolve, reject) => {
|
||||
const rejectPrompt = (error: Error) => {
|
||||
clearTimeout(timeout);
|
||||
this.pendingPrompts.delete(request.requestId);
|
||||
reject(error);
|
||||
};
|
||||
const timeout = setTimeout(() => {
|
||||
this.pendingPrompts.delete(request.requestId);
|
||||
reject(new Error(`SSH authentication timed out for ${input.destination}.`));
|
||||
}, this.passwordPromptTimeoutMs);
|
||||
timeout.unref();
|
||||
|
||||
this.pendingPrompts.set(request.requestId, { resolve, reject, timeout });
|
||||
|
||||
try {
|
||||
if (window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
window.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, request);
|
||||
if (window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
if (window.isMinimized()) {
|
||||
window.restore();
|
||||
}
|
||||
if (window.isDestroyed()) {
|
||||
throw new Error("T3 Code window is not available for SSH authentication.");
|
||||
}
|
||||
window.focus();
|
||||
} catch (error) {
|
||||
rejectPrompt(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error("T3 Code window is not available for SSH authentication."),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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,122 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Effect } from "effect";
|
||||
|
||||
import {
|
||||
isTailscaleIpv4Address,
|
||||
parseTailscaleMagicDnsName,
|
||||
resolveTailscaleAdvertisedEndpoints,
|
||||
} from "./tailscaleEndpointProvider.ts";
|
||||
|
||||
describe("tailscale endpoint provider", () => {
|
||||
it("detects Tailnet IPv4 addresses", () => {
|
||||
expect(isTailscaleIpv4Address("100.64.0.1")).toBe(true);
|
||||
expect(isTailscaleIpv4Address("100.127.255.254")).toBe(true);
|
||||
expect(isTailscaleIpv4Address("100.128.0.1")).toBe(false);
|
||||
expect(isTailscaleIpv4Address("192.168.1.44")).toBe(false);
|
||||
});
|
||||
|
||||
it("parses MagicDNS names from tailscale status", async () => {
|
||||
expect(
|
||||
Effect.runSync(
|
||||
parseTailscaleMagicDnsName(JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } })),
|
||||
),
|
||||
).toBe("desktop.tail.ts.net");
|
||||
expect(Effect.runSync(parseTailscaleMagicDnsName("{}"))).toBeNull();
|
||||
await expect(Effect.runPromise(parseTailscaleMagicDnsName("not-json"))).rejects.toBeDefined();
|
||||
});
|
||||
|
||||
it("resolves Tailscale endpoints as add-on advertised endpoints", async () => {
|
||||
await expect(
|
||||
resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {
|
||||
tailscale0: [
|
||||
{
|
||||
address: "100.100.100.100",
|
||||
family: "IPv4",
|
||||
internal: false,
|
||||
netmask: "255.192.0.0",
|
||||
cidr: "100.100.100.100/10",
|
||||
mac: "00:00:00:00:00:00",
|
||||
},
|
||||
],
|
||||
},
|
||||
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
|
||||
}),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
id: "tailscale-ip:http://100.100.100.100:3773",
|
||||
label: "Tailscale IP",
|
||||
provider: {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
},
|
||||
httpBaseUrl: "http://100.100.100.100:3773/",
|
||||
wsBaseUrl: "ws://100.100.100.100:3773/",
|
||||
reachability: "private-network",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "mixed-content-blocked",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-addon",
|
||||
status: "available",
|
||||
description: "Reachable from devices on the same Tailnet.",
|
||||
},
|
||||
{
|
||||
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
|
||||
label: "Tailscale HTTPS",
|
||||
provider: {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
},
|
||||
httpBaseUrl: "https://desktop.tail.ts.net/",
|
||||
wsBaseUrl: "wss://desktop.tail.ts.net/",
|
||||
reachability: "private-network",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "requires-configuration",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-addon",
|
||||
status: "unavailable",
|
||||
description: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("marks the Tailscale HTTPS endpoint available after Serve is enabled and reachable", async () => {
|
||||
await expect(
|
||||
resolveTailscaleAdvertisedEndpoints({
|
||||
port: 3773,
|
||||
networkInterfaces: {},
|
||||
statusJson: JSON.stringify({ Self: { DNSName: "desktop.tail.ts.net." } }),
|
||||
serveEnabled: true,
|
||||
probe: async () => true,
|
||||
}),
|
||||
).resolves.toEqual([
|
||||
{
|
||||
id: "tailscale-magicdns:https://desktop.tail.ts.net/",
|
||||
label: "Tailscale HTTPS",
|
||||
provider: {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
},
|
||||
httpBaseUrl: "https://desktop.tail.ts.net/",
|
||||
wsBaseUrl: "wss://desktop.tail.ts.net/",
|
||||
reachability: "private-network",
|
||||
compatibility: {
|
||||
hostedHttpsApp: "compatible",
|
||||
desktopApp: "compatible",
|
||||
},
|
||||
source: "desktop-addon",
|
||||
status: "available",
|
||||
description: "HTTPS endpoint served by Tailscale Serve.",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,142 +0,0 @@
|
||||
import type { NetworkInterfaceInfo } from "node:os";
|
||||
|
||||
import * as NodeHttpClient from "@effect/platform-node/NodeHttpClient";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
createAdvertisedEndpoint,
|
||||
type CreateAdvertisedEndpointInput,
|
||||
} from "@t3tools/client-runtime";
|
||||
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
|
||||
import {
|
||||
buildTailscaleHttpsBaseUrl,
|
||||
isTailscaleIpv4Address,
|
||||
parseTailscaleMagicDnsName,
|
||||
probeTailscaleHttpsEndpoint,
|
||||
readTailscaleStatus,
|
||||
} from "@t3tools/tailscale";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
export { isTailscaleIpv4Address, parseTailscaleMagicDnsName } from "@t3tools/tailscale";
|
||||
|
||||
const TailscaleDesktopLayer = Layer.mergeAll(NodeServices.layer, NodeHttpClient.layerUndici);
|
||||
|
||||
const TAILSCALE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
|
||||
id: "tailscale",
|
||||
label: "Tailscale",
|
||||
kind: "private-network",
|
||||
isAddon: true,
|
||||
};
|
||||
|
||||
function createTailscaleEndpoint(
|
||||
input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
|
||||
): AdvertisedEndpoint {
|
||||
return createAdvertisedEndpoint({
|
||||
...input,
|
||||
provider: TAILSCALE_ENDPOINT_PROVIDER,
|
||||
source: "desktop-addon",
|
||||
});
|
||||
}
|
||||
|
||||
export function resolveTailscaleIpAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
}): readonly AdvertisedEndpoint[] {
|
||||
const seen = new Set<string>();
|
||||
const endpoints: AdvertisedEndpoint[] = [];
|
||||
|
||||
for (const interfaceAddresses of Object.values(input.networkInterfaces)) {
|
||||
if (!interfaceAddresses) continue;
|
||||
|
||||
for (const address of interfaceAddresses) {
|
||||
if (address.internal) continue;
|
||||
if (address.family !== "IPv4") continue;
|
||||
if (!isTailscaleIpv4Address(address.address)) continue;
|
||||
if (seen.has(address.address)) continue;
|
||||
seen.add(address.address);
|
||||
|
||||
endpoints.push(
|
||||
createTailscaleEndpoint({
|
||||
id: `tailscale-ip:http://${address.address}:${input.port}`,
|
||||
label: "Tailscale IP",
|
||||
httpBaseUrl: `http://${address.address}:${input.port}`,
|
||||
reachability: "private-network",
|
||||
status: "available",
|
||||
description: "Reachable from devices on the same Tailnet.",
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
export async function resolveTailscaleMagicDnsAdvertisedEndpoint(input: {
|
||||
readonly dnsName: string | null;
|
||||
readonly serveEnabled: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly probe?: (baseUrl: string) => Promise<boolean>;
|
||||
}): Promise<AdvertisedEndpoint | null> {
|
||||
if (!input.dnsName) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const httpBaseUrl = buildTailscaleHttpsBaseUrl({
|
||||
magicDnsName: input.dnsName,
|
||||
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
|
||||
});
|
||||
const isReachable = input.serveEnabled
|
||||
? await (input.probe?.(httpBaseUrl) ??
|
||||
Effect.runPromise(
|
||||
probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
|
||||
Effect.provide(TailscaleDesktopLayer),
|
||||
),
|
||||
))
|
||||
: false;
|
||||
|
||||
return createTailscaleEndpoint({
|
||||
id: `tailscale-magicdns:${httpBaseUrl}`,
|
||||
label: "Tailscale HTTPS",
|
||||
httpBaseUrl,
|
||||
reachability: "private-network",
|
||||
hostedHttpsCompatibility: isReachable ? "compatible" : "requires-configuration",
|
||||
status: isReachable ? "available" : "unavailable",
|
||||
description: isReachable
|
||||
? "HTTPS endpoint served by Tailscale Serve."
|
||||
: "MagicDNS hostname. Configure Tailscale Serve for HTTPS access.",
|
||||
});
|
||||
}
|
||||
|
||||
export async function resolveTailscaleAdvertisedEndpoints(input: {
|
||||
readonly port: number;
|
||||
readonly serveEnabled?: boolean;
|
||||
readonly servePort?: number;
|
||||
readonly networkInterfaces: NodeJS.Dict<NetworkInterfaceInfo[]>;
|
||||
readonly statusJson?: string | null;
|
||||
readonly probe?: (baseUrl: string) => Promise<boolean>;
|
||||
}): Promise<readonly AdvertisedEndpoint[]> {
|
||||
const ipEndpoints = resolveTailscaleIpAdvertisedEndpoints(input);
|
||||
const dnsName =
|
||||
input.statusJson === undefined
|
||||
? await Effect.runPromise(
|
||||
readTailscaleStatus.pipe(
|
||||
Effect.map((status) => status.magicDnsName),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.provide(TailscaleDesktopLayer),
|
||||
),
|
||||
)
|
||||
: input.statusJson
|
||||
? await Effect.runPromise(
|
||||
parseTailscaleMagicDnsName(input.statusJson).pipe(
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
const magicDnsEndpoint = await resolveTailscaleMagicDnsAdvertisedEndpoint({
|
||||
dnsName,
|
||||
serveEnabled: input.serveEnabled === true,
|
||||
...(input.servePort === undefined ? {} : { servePort: input.servePort }),
|
||||
...(input.probe === undefined ? {} : { probe: input.probe }),
|
||||
});
|
||||
|
||||
return magicDnsEndpoint ? [...ipEndpoints, magicDnsEndpoint] : ipEndpoints;
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
discoverEditorColorThemes,
|
||||
getEditorThemePreferences,
|
||||
loadEditorColorTheme,
|
||||
resolveEditorRoots,
|
||||
} from "./vscodeThemeDiscovery.ts";
|
||||
|
||||
let tempDir = "";
|
||||
|
||||
function writeJson(filePath: string, value: unknown) {
|
||||
FS.mkdirSync(Path.dirname(filePath), { recursive: true });
|
||||
FS.writeFileSync(filePath, JSON.stringify(value, null, 2));
|
||||
}
|
||||
|
||||
describe("vscodeThemeDiscovery", () => {
|
||||
beforeEach(() => {
|
||||
tempDir = FS.mkdtempSync(Path.join(OS.tmpdir(), "t3-vscode-themes-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
FS.rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("discovers contributed themes and ignores unsafe paths", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
publisher: "GitHub",
|
||||
displayName: "GitHub Theme",
|
||||
contributes: {
|
||||
themes: [
|
||||
{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" },
|
||||
{ label: "Escaped", uiTheme: "vs", path: "../escaped.json" },
|
||||
],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
colors: { "editor.background": "#0d1117" },
|
||||
});
|
||||
|
||||
expect(discoverEditorColorThemes(roots)).toMatchObject([
|
||||
{
|
||||
source: "vscode",
|
||||
label: "GitHub Dark Default",
|
||||
kind: "dark",
|
||||
publisher: "GitHub",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("loads JSONC settings overrides into the resolved app theme", () => {
|
||||
const roots = resolveEditorRoots({ platform: "darwin", homedir: tempDir });
|
||||
const vscodeRoot = roots.find((root) => root.source === "vscode");
|
||||
expect(vscodeRoot).toBeDefined();
|
||||
if (!vscodeRoot) return;
|
||||
|
||||
const extensionDir = Path.join(vscodeRoot.extensionsPath, "github.github-vscode-theme");
|
||||
writeJson(Path.join(extensionDir, "package.json"), {
|
||||
contributes: {
|
||||
themes: [{ label: "GitHub Dark Default", uiTheme: "vs-dark", path: "./themes/dark.json" }],
|
||||
},
|
||||
});
|
||||
writeJson(Path.join(extensionDir, "themes", "dark.json"), {
|
||||
semanticHighlighting: true,
|
||||
colors: {
|
||||
"editor.background": "#0d1117",
|
||||
"editor.foreground": "#e6edf3",
|
||||
},
|
||||
tokenColors: [],
|
||||
});
|
||||
FS.mkdirSync(Path.dirname(vscodeRoot.settingsPath), { recursive: true });
|
||||
FS.writeFileSync(
|
||||
vscodeRoot.settingsPath,
|
||||
`{
|
||||
"workbench.colorTheme": "GitHub Dark Default",
|
||||
"workbench.colorCustomizations": {
|
||||
"button.background": "#238636",
|
||||
"[GitHub Dark Default]": {
|
||||
"sideBar.background": "#010409"
|
||||
}
|
||||
}
|
||||
}`,
|
||||
);
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
expect(preferences[0]?.colorTheme).toBe("GitHub Dark Default");
|
||||
|
||||
const themeId = discoverEditorColorThemes(roots)[0]?.id;
|
||||
expect(themeId).toBeTruthy();
|
||||
const resolved = themeId ? loadEditorColorTheme(themeId, roots) : null;
|
||||
|
||||
expect(resolved?.colors["button.background"]).toBe("#238636");
|
||||
expect(resolved?.colors["sideBar.background"]).toBe("#010409");
|
||||
expect(resolved?.appVariables["--primary"]).toBe("#238636");
|
||||
});
|
||||
});
|
||||
@@ -1,284 +0,0 @@
|
||||
import * as FS from "node:fs";
|
||||
import * as OS from "node:os";
|
||||
import * as Path from "node:path";
|
||||
import { parse as parseJsonc } from "jsonc-parser";
|
||||
import type {
|
||||
DiscoveredColorTheme,
|
||||
EditorThemePreference,
|
||||
EditorThemeSource,
|
||||
ResolvedColorTheme,
|
||||
ThemeKind,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
mapVscodeColorsToAppVariables,
|
||||
normalizeCssColor,
|
||||
normalizeThemeColors,
|
||||
} from "@t3tools/shared/themeMapping";
|
||||
|
||||
interface EditorRoot {
|
||||
readonly source: EditorThemeSource;
|
||||
readonly extensionsPath: string;
|
||||
readonly settingsPath: string;
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function kindFromUiTheme(uiTheme: unknown): ThemeKind {
|
||||
if (uiTheme === "hc-light") return "high-contrast-light";
|
||||
if (uiTheme === "hc-black") return "high-contrast-dark";
|
||||
if (uiTheme === "vs") return "light";
|
||||
return "dark";
|
||||
}
|
||||
|
||||
function readJsonOrJsoncFile(filePath: string): unknown | null {
|
||||
try {
|
||||
return parseJsonc(FS.readFileSync(filePath, "utf8"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function safeResolveChild(root: string, relativePath: string): string | null {
|
||||
const resolved = Path.resolve(root, relativePath);
|
||||
const normalizedRoot = Path.resolve(root);
|
||||
if (resolved === normalizedRoot || resolved.startsWith(`${normalizedRoot}${Path.sep}`)) {
|
||||
return resolved;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveEditorRoots(input: {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly homedir: string;
|
||||
readonly appData?: string;
|
||||
}): readonly EditorRoot[] {
|
||||
const home = input.homedir;
|
||||
if (input.platform === "win32") {
|
||||
const appData = input.appData ?? Path.join(home, "AppData", "Roaming");
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(appData, "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(appData, "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (input.platform === "darwin") {
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Code - Insiders",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(
|
||||
home,
|
||||
"Library",
|
||||
"Application Support",
|
||||
"Cursor",
|
||||
"User",
|
||||
"settings.json",
|
||||
),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
source: "vscode",
|
||||
extensionsPath: Path.join(home, ".vscode", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "vscode-insiders",
|
||||
extensionsPath: Path.join(home, ".vscode-insiders", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Code - Insiders", "User", "settings.json"),
|
||||
},
|
||||
{
|
||||
source: "cursor",
|
||||
extensionsPath: Path.join(home, ".cursor", "extensions"),
|
||||
settingsPath: Path.join(home, ".config", "Cursor", "User", "settings.json"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function resolveDefaultEditorRoots() {
|
||||
const input: { platform: NodeJS.Platform; homedir: string; appData?: string } = {
|
||||
platform: process.platform,
|
||||
homedir: OS.homedir(),
|
||||
};
|
||||
if (process.env.APPDATA) input.appData = process.env.APPDATA;
|
||||
return resolveEditorRoots(input);
|
||||
}
|
||||
|
||||
function readEditorSettings(settingsPath: string): Record<string, unknown> {
|
||||
const parsed = readJsonOrJsoncFile(settingsPath);
|
||||
return isObject(parsed) ? parsed : {};
|
||||
}
|
||||
|
||||
export function getEditorThemePreferences(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly EditorThemePreference[] {
|
||||
return roots.map((root) => {
|
||||
const settings = readEditorSettings(root.settingsPath);
|
||||
const customizations = settings["workbench.colorCustomizations"];
|
||||
return {
|
||||
source: root.source,
|
||||
colorTheme:
|
||||
typeof settings["workbench.colorTheme"] === "string"
|
||||
? settings["workbench.colorTheme"]
|
||||
: null,
|
||||
preferredLightColorTheme:
|
||||
typeof settings["workbench.preferredLightColorTheme"] === "string"
|
||||
? settings["workbench.preferredLightColorTheme"]
|
||||
: null,
|
||||
preferredDarkColorTheme:
|
||||
typeof settings["workbench.preferredDarkColorTheme"] === "string"
|
||||
? settings["workbench.preferredDarkColorTheme"]
|
||||
: null,
|
||||
autoDetectColorScheme: settings["window.autoDetectColorScheme"] === true,
|
||||
workbenchColorCustomizations: isObject(customizations) ? customizations : {},
|
||||
editorTokenColorCustomizations: settings["editor.tokenColorCustomizations"],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function discoverEditorColorThemes(
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): readonly DiscoveredColorTheme[] {
|
||||
const themes: DiscoveredColorTheme[] = [];
|
||||
|
||||
for (const root of roots) {
|
||||
if (!FS.existsSync(root.extensionsPath)) continue;
|
||||
|
||||
for (const entry of FS.readdirSync(root.extensionsPath, { withFileTypes: true })) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
|
||||
const extensionDir = Path.join(root.extensionsPath, entry.name);
|
||||
const packagePath = Path.join(extensionDir, "package.json");
|
||||
const packageJson = readJsonOrJsoncFile(packagePath);
|
||||
if (!isObject(packageJson)) continue;
|
||||
|
||||
const contributes = packageJson.contributes;
|
||||
const contributedThemes = isObject(contributes) ? contributes.themes : null;
|
||||
if (!Array.isArray(contributedThemes)) continue;
|
||||
|
||||
for (const theme of contributedThemes) {
|
||||
if (!isObject(theme) || typeof theme.label !== "string" || typeof theme.path !== "string") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const themePath = safeResolveChild(extensionDir, theme.path);
|
||||
if (!themePath || !FS.existsSync(themePath)) continue;
|
||||
|
||||
themes.push({
|
||||
id: `${root.source}:${entry.name}:${theme.label}`,
|
||||
source: root.source,
|
||||
extensionId: entry.name,
|
||||
extensionDisplayName:
|
||||
typeof packageJson.displayName === "string" ? packageJson.displayName : undefined,
|
||||
label: theme.label,
|
||||
kind: kindFromUiTheme(theme.uiTheme),
|
||||
themePath,
|
||||
packagePath,
|
||||
publisher: typeof packageJson.publisher === "string" ? packageJson.publisher : undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return themes.toSorted((a, b) => a.label.localeCompare(b.label));
|
||||
}
|
||||
|
||||
function mergeWorkbenchOverrides(input: {
|
||||
readonly themeLabel: string;
|
||||
readonly themeColors: Record<string, string>;
|
||||
readonly customizations: Record<string, unknown>;
|
||||
}) {
|
||||
const next = { ...input.themeColors };
|
||||
|
||||
for (const [key, rawValue] of Object.entries(input.customizations)) {
|
||||
if (key.startsWith("[") && key.endsWith("]")) continue;
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
|
||||
const scoped = input.customizations[`[${input.themeLabel}]`];
|
||||
if (isObject(scoped)) {
|
||||
for (const [key, rawValue] of Object.entries(scoped)) {
|
||||
const color = normalizeCssColor(rawValue);
|
||||
if (color) next[key] = color;
|
||||
}
|
||||
}
|
||||
|
||||
return next;
|
||||
}
|
||||
|
||||
export function loadEditorColorTheme(
|
||||
themeId: string,
|
||||
roots = resolveDefaultEditorRoots(),
|
||||
): ResolvedColorTheme | null {
|
||||
const themes = discoverEditorColorThemes(roots);
|
||||
const theme = themes.find((entry) => entry.id === themeId);
|
||||
if (!theme) return null;
|
||||
|
||||
const rawTheme = readJsonOrJsoncFile(theme.themePath);
|
||||
if (!isObject(rawTheme)) return null;
|
||||
|
||||
const preferences = getEditorThemePreferences(roots);
|
||||
const preference = preferences.find((entry) => entry.source === theme.source);
|
||||
const colors = mergeWorkbenchOverrides({
|
||||
themeLabel: theme.label,
|
||||
themeColors: normalizeThemeColors(rawTheme.colors),
|
||||
customizations: preference?.workbenchColorCustomizations ?? {},
|
||||
});
|
||||
|
||||
return {
|
||||
id: theme.id,
|
||||
label: theme.label,
|
||||
source: theme.source,
|
||||
kind: theme.kind,
|
||||
colors,
|
||||
tokenColors: rawTheme.tokenColors ?? [],
|
||||
semanticHighlighting:
|
||||
typeof rawTheme.semanticHighlighting === "boolean"
|
||||
? rawTheme.semanticHighlighting
|
||||
: undefined,
|
||||
semanticTokenColors: rawTheme.semanticTokenColors,
|
||||
appVariables: mapVscodeColorsToAppVariables({ kind: theme.kind, colors }),
|
||||
};
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { bindFirstRevealTrigger } from "./windowReveal.ts";
|
||||
|
||||
describe("bindFirstRevealTrigger", () => {
|
||||
it("reveals when the first trigger fires", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reveals when only the fallback trigger fires (Wayland deadlock case)", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("only reveals once when multiple triggers fire", () => {
|
||||
const window = new EventEmitter();
|
||||
const webContents = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger(
|
||||
[
|
||||
(fire) => window.once("ready-to-show", fire),
|
||||
(fire) => webContents.once("did-finish-load", fire),
|
||||
],
|
||||
reveal,
|
||||
);
|
||||
|
||||
webContents.emit("did-finish-load");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("subscribers using `once` ignore re-emitted events after reveal", () => {
|
||||
const window = new EventEmitter();
|
||||
const reveal = vi.fn();
|
||||
|
||||
bindFirstRevealTrigger([(fire) => window.once("ready-to-show", fire)], reveal);
|
||||
|
||||
window.emit("ready-to-show");
|
||||
window.emit("ready-to-show");
|
||||
|
||||
expect(reveal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,28 +0,0 @@
|
||||
export type RevealSubscription = (listener: () => void) => void;
|
||||
|
||||
/**
|
||||
* Wire a reveal callback to fire exactly once, on whichever of the provided
|
||||
* event subscribers fires first. Each subscriber is responsible for binding
|
||||
* its own event source.
|
||||
*
|
||||
* Used by the desktop main window's first-paint reveal logic. The standard
|
||||
* Electron pattern is to wait for `ready-to-show` before calling `show()`,
|
||||
* but on Linux/Wayland with `show: false`, `ready-to-show` only fires after
|
||||
* `show()` is called, deadlocking that pattern. Subscribing to both
|
||||
* `ready-to-show` and `did-finish-load` (or any other "renderer is alive"
|
||||
* signal) lets the window surface reliably across platforms.
|
||||
*/
|
||||
export function bindFirstRevealTrigger(
|
||||
subscribers: readonly RevealSubscription[],
|
||||
reveal: () => void,
|
||||
): void {
|
||||
let revealed = false;
|
||||
const fire = () => {
|
||||
if (revealed) return;
|
||||
revealed = true;
|
||||
reveal();
|
||||
};
|
||||
for (const subscribe of subscribers) {
|
||||
subscribe(fire);
|
||||
}
|
||||
}
|
||||
@@ -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([
|
||||
@@ -12,7 +12,7 @@ export default defineConfig([
|
||||
...shared,
|
||||
entry: ["src/main.ts"],
|
||||
clean: true,
|
||||
noExternal: (id) => id.startsWith("@t3tools/") || id.startsWith("effect-acp"),
|
||||
noExternal: (id) => id.startsWith("@t3tools/"),
|
||||
},
|
||||
{
|
||||
...shared,
|
||||
|
||||
@@ -3,8 +3,7 @@ import { execFileSync } from "node:child_process";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CodexSettings,
|
||||
ProviderDriverKind,
|
||||
ProviderKind,
|
||||
type OrchestrationEvent,
|
||||
type OrchestrationThread,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -25,7 +24,10 @@ import {
|
||||
|
||||
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/textGeneration/TextGeneration.ts";
|
||||
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
|
||||
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
|
||||
import { GitStatusBroadcaster } from "../src/git/Services/GitStatusBroadcaster.ts";
|
||||
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
|
||||
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
|
||||
import { OrchestrationEventStoreLive } from "../src/persistence/Layers/OrchestrationEventStore.ts";
|
||||
import { ProjectionCheckpointRepositoryLive } from "../src/persistence/Layers/ProjectionCheckpoints.ts";
|
||||
@@ -34,16 +36,13 @@ import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/
|
||||
import { makeSqlitePersistenceLive } from "../src/persistence/Layers/Sqlite.ts";
|
||||
import { ProjectionCheckpointRepository } from "../src/persistence/Services/ProjectionCheckpoints.ts";
|
||||
import { ProjectionPendingApprovalRepository } from "../src/persistence/Services/ProjectionPendingApprovals.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import { makeCodexAdapter } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
|
||||
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
|
||||
import { ProviderService } from "../src/provider/Services/ProviderService.ts";
|
||||
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
|
||||
import { CheckpointReactorLive } from "../src/orchestration/Layers/CheckpointReactor.ts";
|
||||
@@ -59,7 +58,6 @@ import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
} from "../src/orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ThreadDeletionReactor } from "../src/orchestration/Services/ThreadDeletionReactor.ts";
|
||||
import { OrchestrationReactor } from "../src/orchestration/Services/OrchestrationReactor.ts";
|
||||
import { ProjectionSnapshotQuery } from "../src/orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import {
|
||||
@@ -74,11 +72,6 @@ import {
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
|
||||
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
|
||||
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
|
||||
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
|
||||
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
|
||||
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -220,7 +213,7 @@ export interface OrchestrationIntegrationHarness {
|
||||
}
|
||||
|
||||
interface MakeOrchestrationIntegrationHarnessOptions {
|
||||
readonly provider?: ProviderDriverKind;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly realCodex?: boolean;
|
||||
}
|
||||
|
||||
@@ -231,7 +224,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const path = yield* Path.Path;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
const provider = options?.provider ?? "codex";
|
||||
const useRealCodex = options?.realCodex === true;
|
||||
const adapterHarness = useRealCodex
|
||||
? null
|
||||
@@ -239,10 +232,13 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
provider,
|
||||
});
|
||||
const fakeRegistry = adapterHarness
|
||||
? Layer.succeed(
|
||||
ProviderAdapterRegistry,
|
||||
makeAdapterRegistryMock({ [adapterHarness.provider]: adapterHarness.adapter }),
|
||||
)
|
||||
? Layer.succeed(ProviderAdapterRegistry, {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === adapterHarness.provider
|
||||
? Effect.succeed(adapterHarness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed([adapterHarness.provider]),
|
||||
} as typeof ProviderAdapterRegistry.Service)
|
||||
: null;
|
||||
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-orchestration-integration-",
|
||||
@@ -267,33 +263,34 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const realCodexRegistry = Layer.effect(
|
||||
ProviderAdapterRegistry,
|
||||
Effect.gen(function* () {
|
||||
const codexSettings = Schema.decodeSync(CodexSettings)({});
|
||||
const codexAdapter = yield* makeCodexAdapter(codexSettings);
|
||||
return makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: codexAdapter,
|
||||
});
|
||||
const codexAdapter = yield* CodexAdapter;
|
||||
return {
|
||||
getByProvider: (resolvedProvider) =>
|
||||
resolvedProvider === "codex"
|
||||
? Effect.succeed(codexAdapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider: resolvedProvider })),
|
||||
listProviders: () => Effect.succeed(["codex"] as const),
|
||||
} as typeof ProviderAdapterRegistry.Service;
|
||||
}),
|
||||
).pipe(
|
||||
Layer.provide(makeCodexAdapterLive()),
|
||||
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(providerSessionDirectoryLayer),
|
||||
);
|
||||
const providerEventLoggersLayer = Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers);
|
||||
const providerLayer = useRealCodex
|
||||
? makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(realCodexRegistry),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
)
|
||||
: makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerSessionDirectoryLayer),
|
||||
Layer.provide(fakeRegistry!),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
Layer.provide(providerEventLoggersLayer),
|
||||
);
|
||||
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistry.layer));
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
|
||||
const runtimeServicesLayer = Layer.mergeAll(
|
||||
projectionSnapshotQueryLayer,
|
||||
@@ -309,31 +306,31 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
|
||||
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
|
||||
const gitCoreLayer = Layer.succeed(GitCore, {
|
||||
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
|
||||
Effect.succeed({ branch: input.newBranch }),
|
||||
});
|
||||
} as unknown as GitCoreShape);
|
||||
const textGenerationLayer = Layer.succeed(TextGeneration, {
|
||||
generateBranchName: () => Effect.succeed({ branch: "update" }),
|
||||
generateThreadTitle: () => Effect.succeed({ title: "New thread" }),
|
||||
} as unknown as TextGenerationShape);
|
||||
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitWorkflowLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(VcsStatusBroadcaster, {
|
||||
Layer.succeed(GitStatusBroadcaster, {
|
||||
getStatus: () => Effect.die("getStatus should not be called in this test"),
|
||||
refreshLocalStatus: () =>
|
||||
Effect.succeed({
|
||||
isRepo: true,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: true,
|
||||
refName: "main",
|
||||
hasOriginRemote: false,
|
||||
isDefaultBranch: true,
|
||||
branch: "main",
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: { files: [], insertions: 0, deletions: 0 },
|
||||
}),
|
||||
@@ -344,23 +341,16 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(
|
||||
WorkspaceEntriesLive.pipe(
|
||||
Layer.provide(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsDriverRegistry.layer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(WorkspacePathsLive),
|
||||
Layer.provideMerge(VcsProcess.layer),
|
||||
);
|
||||
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeIngestionLayer),
|
||||
Layer.provideMerge(providerCommandReactorLayer),
|
||||
Layer.provideMerge(checkpointReactorLayer),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ThreadDeletionReactor, {
|
||||
start: () => Effect.void,
|
||||
drain: Effect.void,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const layer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
ProviderTurnStartResult,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
ProviderDriverKind,
|
||||
ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Queue, Stream } from "effect";
|
||||
|
||||
@@ -36,7 +36,7 @@ export interface TestTurnResponse {
|
||||
export type FixtureProviderRuntimeEvent = {
|
||||
readonly type: string;
|
||||
readonly eventId: EventId;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly provider: ProviderKind;
|
||||
readonly createdAt: string;
|
||||
readonly threadId: string;
|
||||
readonly turnId?: string | undefined;
|
||||
@@ -178,7 +178,7 @@ function normalizeFixtureEvent(rawEvent: Record<string, unknown>): ProviderRunti
|
||||
|
||||
export interface TestProviderAdapterHarness {
|
||||
readonly adapter: ProviderAdapterShape<ProviderAdapterError>;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly provider: ProviderKind;
|
||||
readonly queueTurnResponse: (
|
||||
threadId: ThreadId,
|
||||
response: TestTurnResponse,
|
||||
@@ -198,7 +198,7 @@ export interface TestProviderAdapterHarness {
|
||||
}
|
||||
|
||||
interface MakeTestProviderAdapterHarnessOptions {
|
||||
readonly provider?: ProviderDriverKind;
|
||||
readonly provider?: ProviderKind;
|
||||
}
|
||||
|
||||
function nowIso(): string {
|
||||
@@ -206,7 +206,7 @@ function nowIso(): string {
|
||||
}
|
||||
|
||||
function sessionNotFound(
|
||||
provider: ProviderDriverKind,
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
): ProviderAdapterSessionNotFoundError {
|
||||
return new ProviderAdapterSessionNotFoundError({
|
||||
@@ -216,7 +216,7 @@ function sessionNotFound(
|
||||
}
|
||||
|
||||
function missingSessionEffect(
|
||||
provider: ProviderDriverKind,
|
||||
provider: ProviderKind,
|
||||
threadId: ThreadId,
|
||||
): Effect.Effect<never, ProviderAdapterError> {
|
||||
return Effect.fail(sessionNotFound(provider, threadId));
|
||||
@@ -224,7 +224,7 @@ function missingSessionEffect(
|
||||
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
const provider = options?.provider ?? "codex";
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
@@ -257,9 +257,6 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
...(input.providerInstanceId !== undefined
|
||||
? { providerInstanceId: input.providerInstanceId }
|
||||
: {}),
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
threadId,
|
||||
@@ -475,6 +472,15 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
sessions.clear();
|
||||
});
|
||||
|
||||
const compactThread: ProviderAdapterShape<ProviderAdapterError>["compactThread"] = (threadId) =>
|
||||
readThread(threadId).pipe(
|
||||
Effect.map((snapshot) => {
|
||||
const latestTurn = snapshot.turns.at(-1);
|
||||
const latestItem = latestTurn?.items.at(-1);
|
||||
return typeof latestItem === "string" ? latestItem : null;
|
||||
}),
|
||||
);
|
||||
|
||||
const adapter: ProviderAdapterShape<ProviderAdapterError> = {
|
||||
provider,
|
||||
capabilities: {
|
||||
@@ -489,6 +495,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
listSessions,
|
||||
hasSession,
|
||||
readThread,
|
||||
compactThread,
|
||||
rollbackThread,
|
||||
stopAll,
|
||||
streamEvents: Stream.fromQueue(runtimeEvents),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EventId, ProviderDriverKind, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import { EventId, RuntimeRequestId } from "@t3tools/contracts";
|
||||
import type { LegacyProviderRuntimeEvent } from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const PROVIDER = ProviderDriverKind.make("codex");
|
||||
const PROVIDER = "codex" as const;
|
||||
const SESSION_ID = "fixture-session";
|
||||
const THREAD_ID = "fixture-thread";
|
||||
const TURN_ID = "fixture-turn";
|
||||
|
||||
@@ -4,17 +4,14 @@ import path from "node:path";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
defaultInstanceIdForDriver,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
ModelSelection,
|
||||
ProviderInstanceId,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Option, Schema } from "effect";
|
||||
@@ -42,9 +39,7 @@ const PROJECT_ID = asProjectId("project-1");
|
||||
const THREAD_ID = ThreadId.make("thread-1");
|
||||
const FIXTURE_TURN_ID = "fixture-turn";
|
||||
const APPROVAL_REQUEST_ID = asApprovalRequestId("req-approval-1");
|
||||
type IntegrationProvider = ProviderDriverKind;
|
||||
const CODEX_PROVIDER = ProviderDriverKind.make("codex");
|
||||
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
|
||||
type IntegrationProvider = ProviderKind;
|
||||
|
||||
function nowIso() {
|
||||
return new Date().toISOString();
|
||||
@@ -79,11 +74,7 @@ function waitForSync<A>(
|
||||
});
|
||||
}
|
||||
|
||||
function runtimeBase(
|
||||
eventId: string,
|
||||
createdAt: string,
|
||||
provider: IntegrationProvider = CODEX_PROVIDER,
|
||||
) {
|
||||
function runtimeBase(eventId: string, createdAt: string, provider: IntegrationProvider = "codex") {
|
||||
return {
|
||||
eventId: asEventId(eventId),
|
||||
provider,
|
||||
@@ -93,7 +84,7 @@ function runtimeBase(
|
||||
|
||||
function withHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
provider: IntegrationProvider = CODEX_PROVIDER,
|
||||
provider: IntegrationProvider = "codex",
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness({ provider }),
|
||||
@@ -106,7 +97,7 @@ function withRealCodexHarness<A, E>(
|
||||
use: (harness: OrchestrationIntegrationHarness) => Effect.Effect<A, E>,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
makeOrchestrationIntegrationHarness({ provider: CODEX_PROVIDER, realCodex: true }),
|
||||
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
|
||||
use,
|
||||
(harness) => harness.dispose,
|
||||
).pipe(Effect.provide(NodeServices.layer));
|
||||
@@ -115,9 +106,8 @@ function withRealCodexHarness<A, E>(
|
||||
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
Effect.gen(function* () {
|
||||
const createdAt = nowIso();
|
||||
const provider = harness.adapterHarness?.provider ?? CODEX_PROVIDER;
|
||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL;
|
||||
const instanceId = defaultInstanceIdForDriver(provider);
|
||||
const provider = harness.adapterHarness?.provider ?? "codex";
|
||||
const defaultModel = DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
@@ -126,7 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModelSelection: {
|
||||
instanceId,
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
createdAt,
|
||||
@@ -139,7 +129,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
modelSelection: {
|
||||
instanceId,
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -275,7 +265,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt,
|
||||
@@ -288,7 +278,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("codex"),
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -506,7 +496,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 1),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(incrementalDiff.includes("README.md"), true);
|
||||
|
||||
@@ -515,7 +504,6 @@ it.live("runs multi-turn file edits and persists checkpoint diffs", () =>
|
||||
fromCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 0),
|
||||
toCheckpointRef: checkpointRefForThreadTurn(THREAD_ID, 2),
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
assert.equal(fullDiff.includes("README.md"), true);
|
||||
|
||||
@@ -924,32 +912,20 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase(
|
||||
"evt-claude-start-1",
|
||||
"2026-02-24T10:10:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-start-1", "2026-02-24T10:10:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase(
|
||||
"evt-claude-start-2",
|
||||
"2026-02-24T10:10:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-start-2", "2026-02-24T10:10:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Claude first turn.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase(
|
||||
"evt-claude-start-3",
|
||||
"2026-02-24T10:10:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-start-3", "2026-02-24T10:10:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -963,7 +939,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
||||
messageId: "msg-user-claude-initial",
|
||||
text: "Use Claude",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -979,7 +955,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
|
||||
);
|
||||
assert.equal(thread.session?.providerName, "claudeAgent");
|
||||
}),
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
@@ -993,32 +969,20 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-1",
|
||||
"2026-02-24T10:11:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-recover-1", "2026-02-24T10:11:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-2",
|
||||
"2026-02-24T10:11:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-recover-2", "2026-02-24T10:11:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn before restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-3",
|
||||
"2026-02-24T10:11:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-recover-3", "2026-02-24T10:11:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1032,7 +996,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
messageId: "msg-user-claude-recover-1",
|
||||
text: "Before restart",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1054,32 +1018,20 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-4",
|
||||
"2026-02-24T10:11:01.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-recover-4", "2026-02-24T10:11:01.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-5",
|
||||
"2026-02-24T10:11:01.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-recover-5", "2026-02-24T10:11:01.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Turn after restart.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase(
|
||||
"evt-claude-recover-6",
|
||||
"2026-02-24T10:11:01.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-recover-6", "2026-02-24T10:11:01.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1111,7 +1063,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
|
||||
assert.equal(recoveredThread.session?.providerName, "claudeAgent");
|
||||
assert.equal(recoveredThread.session?.threadId, "thread-1");
|
||||
}),
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1125,21 +1077,13 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase(
|
||||
"evt-claude-approval-1",
|
||||
"2026-02-24T10:12:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-approval-1", "2026-02-24T10:12:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "approval.requested",
|
||||
...runtimeBase(
|
||||
"evt-claude-approval-2",
|
||||
"2026-02-24T10:12:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-approval-2", "2026-02-24T10:12:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
requestId: APPROVAL_REQUEST_ID,
|
||||
@@ -1148,11 +1092,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase(
|
||||
"evt-claude-approval-3",
|
||||
"2026-02-24T10:12:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-approval-3", "2026-02-24T10:12:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1166,7 +1106,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1197,7 +1137,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
);
|
||||
assert.equal(approvalResponses[0]?.decision, "accept");
|
||||
}),
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1211,32 +1151,20 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase(
|
||||
"evt-claude-interrupt-1",
|
||||
"2026-02-24T10:13:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-interrupt-1", "2026-02-24T10:13:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase(
|
||||
"evt-claude-interrupt-2",
|
||||
"2026-02-24T10:13:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-interrupt-2", "2026-02-24T10:13:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "Long running output.\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase(
|
||||
"evt-claude-interrupt-3",
|
||||
"2026-02-24T10:13:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-interrupt-3", "2026-02-24T10:13:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1250,7 +1178,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
messageId: "msg-user-claude-interrupt",
|
||||
text: "Start long turn",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1278,7 +1206,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
|
||||
);
|
||||
assert.equal(interruptCalls.length, 1);
|
||||
}),
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1292,32 +1220,20 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-1",
|
||||
"2026-02-24T10:14:00.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-revert-1", "2026-02-24T10:14:00.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-2",
|
||||
"2026-02-24T10:14:00.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-revert-2", "2026-02-24T10:14:00.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v2\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-3",
|
||||
"2026-02-24T10:14:00.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-revert-3", "2026-02-24T10:14:00.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1335,7 +1251,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
messageId: "msg-user-claude-revert-1",
|
||||
text: "First Claude edit",
|
||||
modelSelection: {
|
||||
instanceId: ProviderInstanceId.make("claudeAgent"),
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
@@ -1350,32 +1266,20 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
events: [
|
||||
{
|
||||
type: "turn.started",
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-4",
|
||||
"2026-02-24T10:14:01.000Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-revert-4", "2026-02-24T10:14:01.000Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
},
|
||||
{
|
||||
type: "message.delta",
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-5",
|
||||
"2026-02-24T10:14:01.050Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-revert-5", "2026-02-24T10:14:01.050Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
delta: "README -> v3\n",
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...runtimeBase(
|
||||
"evt-claude-revert-6",
|
||||
"2026-02-24T10:14:01.100Z",
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
),
|
||||
...runtimeBase("evt-claude-revert-6", "2026-02-24T10:14:01.100Z", "claudeAgent"),
|
||||
threadId: THREAD_ID,
|
||||
turnId: FIXTURE_TURN_ID,
|
||||
status: "completed",
|
||||
@@ -1426,6 +1330,6 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
|
||||
);
|
||||
assert.deepEqual(harness.adapterHarness!.getRollbackCalls(THREAD_ID), [1]);
|
||||
}),
|
||||
CLAUDE_AGENT_PROVIDER,
|
||||
"claudeAgent",
|
||||
),
|
||||
);
|
||||
@@ -1,17 +1,13 @@
|
||||
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
|
||||
import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it, assert } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
|
||||
|
||||
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
|
||||
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
|
||||
import {
|
||||
NoOpProviderEventLoggers,
|
||||
ProviderEventLoggers,
|
||||
} from "../src/provider/Layers/ProviderEventLoggers.ts";
|
||||
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
|
||||
import {
|
||||
ProviderService,
|
||||
@@ -33,8 +29,6 @@ import {
|
||||
codexTurnTextFixture,
|
||||
} from "./fixtures/providerRuntime.ts";
|
||||
|
||||
const codexInstanceId = ProviderInstanceId.make("codex");
|
||||
|
||||
const makeWorkspaceDirectory = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const pathService = yield* Path.Path;
|
||||
@@ -53,9 +47,13 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
const registry: typeof ProviderAdapterRegistry.Service = {
|
||||
getByProvider: (provider) =>
|
||||
provider === "codex"
|
||||
? Effect.succeed(harness.adapter)
|
||||
: Effect.fail(new ProviderUnsupportedError({ provider })),
|
||||
listProviders: () => Effect.succeed(["codex"]),
|
||||
};
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntimeRepositoryLive),
|
||||
@@ -66,7 +64,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
@@ -127,8 +124,7 @@ it.live("replays typed runtime fixture events", () =>
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-typed"), {
|
||||
threadId: ThreadId.make("thread-integration-typed"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
@@ -146,10 +142,6 @@ it.live("replays typed runtime fixture events", () =>
|
||||
observedEvents.map((event) => event.type),
|
||||
codexTurnTextFixture.map((event) => event.type),
|
||||
);
|
||||
assert.deepEqual(
|
||||
observedEvents.map((event) => event.providerInstanceId),
|
||||
codexTurnTextFixture.map(() => codexInstanceId),
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -164,8 +156,7 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-tools"), {
|
||||
threadId: ThreadId.make("thread-integration-tools"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
@@ -201,8 +192,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-multi"), {
|
||||
threadId: ThreadId.make("thread-integration-multi"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
@@ -253,8 +243,7 @@ it.live("rolls back provider conversation state only", () =>
|
||||
const provider = yield* ProviderService;
|
||||
const session = yield* provider.startSession(ThreadId.make("thread-integration-rollback"), {
|
||||
threadId: ThreadId.make("thread-integration-rollback"),
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
provider: "codex",
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.22",
|
||||
"version": "0.0.17",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -15,21 +15,19 @@
|
||||
],
|
||||
"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:",
|
||||
"@opencode-ai/sdk": "^1.3.15",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/diffs": "^1.1.0-beta.16",
|
||||
"effect": "catalog:",
|
||||
"node-pty": "^1.1.0",
|
||||
"open": "^10.1.0"
|
||||
@@ -39,12 +37,9 @@
|
||||
"@effect/vitest": "catalog:",
|
||||
"@t3tools/contracts": "workspace:*",
|
||||
"@t3tools/shared": "workspace:*",
|
||||
"@t3tools/tailscale": "workspace:*",
|
||||
"@t3tools/web": "workspace:*",
|
||||
"@types/bun": "catalog:",
|
||||
"@types/node": "catalog:",
|
||||
"effect-acp": "workspace:*",
|
||||
"effect-codex-app-server": "workspace:*",
|
||||
"tsdown": "catalog:",
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
|
||||
@@ -1,590 +0,0 @@
|
||||
#!/usr/bin/env bun
|
||||
import { appendFileSync } from "node:fs";
|
||||
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
|
||||
import * as EffectAcpAgent from "effect-acp/agent";
|
||||
import * as AcpError from "effect-acp/errors";
|
||||
import type * as AcpSchema from "effect-acp/schema";
|
||||
|
||||
const requestLogPath = process.env.T3_ACP_REQUEST_LOG_PATH;
|
||||
const exitLogPath = process.env.T3_ACP_EXIT_LOG_PATH;
|
||||
const emitToolCalls = process.env.T3_ACP_EMIT_TOOL_CALLS === "1";
|
||||
const emitInterleavedAssistantToolCalls =
|
||||
process.env.T3_ACP_EMIT_INTERLEAVED_ASSISTANT_TOOL_CALLS === "1";
|
||||
const emitGenericToolPlaceholders = process.env.T3_ACP_EMIT_GENERIC_TOOL_PLACEHOLDERS === "1";
|
||||
const emitAskQuestion = process.env.T3_ACP_EMIT_ASK_QUESTION === "1";
|
||||
const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
|
||||
const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
|
||||
const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT;
|
||||
const sessionId = "mock-session-1";
|
||||
|
||||
let currentModeId = "ask";
|
||||
let currentModelId = "default";
|
||||
let parameterizedModelPicker = false;
|
||||
let currentReasoning = "medium";
|
||||
let currentContext = "272k";
|
||||
let currentFast = false;
|
||||
const cancelledSessions = new Set<string>();
|
||||
|
||||
function logExit(reason: string): void {
|
||||
if (!exitLogPath) {
|
||||
return;
|
||||
}
|
||||
appendFileSync(exitLogPath, `${reason}\n`, "utf8");
|
||||
}
|
||||
|
||||
process.once("SIGTERM", () => {
|
||||
logExit("SIGTERM");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("SIGINT", () => {
|
||||
logExit("SIGINT");
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.once("exit", (code) => {
|
||||
logExit(`exit:${code}`);
|
||||
});
|
||||
|
||||
function configOptions(): ReadonlyArray<AcpSchema.SessionConfigOption> {
|
||||
if (parameterizedModelPicker) {
|
||||
const baseOptions: Array<AcpSchema.SessionConfigOption> = [
|
||||
{
|
||||
id: "mode",
|
||||
name: "Mode",
|
||||
category: "mode",
|
||||
type: "select",
|
||||
currentValue: currentModeId,
|
||||
options: availableModes.map((mode) => ({
|
||||
value: mode.id,
|
||||
name: mode.name,
|
||||
...(mode.description ? { description: mode.description } : {}),
|
||||
})),
|
||||
},
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select",
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ value: "claude-opus-4-6", name: "Opus 4.6" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
switch (currentModelId) {
|
||||
case "gpt-5.4":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "none", name: "None" },
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
{ value: "extra-high", name: "Extra High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "context",
|
||||
name: "Context",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: currentContext,
|
||||
options: [
|
||||
{ value: "272k", name: "272K" },
|
||||
{ value: "1m", name: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "composer-2":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "fast",
|
||||
name: "Fast",
|
||||
category: "model_config",
|
||||
type: "select",
|
||||
currentValue: String(currentFast),
|
||||
options: [
|
||||
{ value: "false", name: "Off" },
|
||||
{ value: "true", name: "Fast" },
|
||||
],
|
||||
},
|
||||
];
|
||||
case "claude-opus-4-6":
|
||||
return [
|
||||
...baseOptions,
|
||||
{
|
||||
id: "reasoning",
|
||||
name: "Reasoning",
|
||||
category: "thought_level",
|
||||
type: "select",
|
||||
currentValue: currentReasoning,
|
||||
options: [
|
||||
{ value: "low", name: "Low" },
|
||||
{ value: "medium", name: "Medium" },
|
||||
{ value: "high", name: "High" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "thinking",
|
||||
name: "Thinking",
|
||||
category: "model_config",
|
||||
type: "boolean",
|
||||
currentValue: true,
|
||||
},
|
||||
];
|
||||
default:
|
||||
return baseOptions;
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: "model",
|
||||
name: "Model",
|
||||
category: "model",
|
||||
type: "select" as const,
|
||||
currentValue: currentModelId,
|
||||
options: [
|
||||
{ value: "default", name: "Auto" },
|
||||
{ value: "composer-2", name: "Composer 2" },
|
||||
{ value: "composer-2[fast=true]", name: "Composer 2 Fast" },
|
||||
{ value: "gpt-5.3-codex[reasoning=medium,fast=false]", name: "Codex 5.3" },
|
||||
],
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const availableModes: ReadonlyArray<AcpSchema.SessionMode> = [
|
||||
{
|
||||
id: "ask",
|
||||
name: "Ask",
|
||||
description: "Request permission before making any changes",
|
||||
},
|
||||
{
|
||||
id: "architect",
|
||||
name: "Architect",
|
||||
description: "Design and plan software systems without implementation",
|
||||
},
|
||||
{
|
||||
id: "code",
|
||||
name: "Code",
|
||||
description: "Write and modify code with full tool access",
|
||||
},
|
||||
];
|
||||
|
||||
function modeState(): AcpSchema.SessionModeState {
|
||||
return {
|
||||
currentModeId,
|
||||
availableModes,
|
||||
};
|
||||
}
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const agent = yield* EffectAcpAgent.AcpAgent;
|
||||
|
||||
yield* agent.handleInitialize((request) =>
|
||||
Effect.sync(() => {
|
||||
parameterizedModelPicker =
|
||||
request.clientCapabilities?._meta?.parameterizedModelPicker === true;
|
||||
return {
|
||||
protocolVersion: 1,
|
||||
agentCapabilities: { loadSession: true },
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleAuthenticate(() => Effect.succeed({}));
|
||||
|
||||
yield* agent.handleCreateSession(() =>
|
||||
Effect.succeed({
|
||||
sessionId,
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleLoadSession((request) =>
|
||||
agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: String(request.sessionId ?? sessionId),
|
||||
update: {
|
||||
sessionUpdate: "user_message_chunk",
|
||||
content: { type: "text", text: "replay" },
|
||||
},
|
||||
})
|
||||
.pipe(
|
||||
Effect.as({
|
||||
modes: modeState(),
|
||||
configOptions: configOptions(),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
yield* agent.handleSetSessionConfigOption((request) =>
|
||||
Effect.gen(function* () {
|
||||
if (exitOnSetConfigOption) {
|
||||
return yield* Effect.sync(() => {
|
||||
process.exit(7);
|
||||
});
|
||||
}
|
||||
if (failSetConfigOption) {
|
||||
return yield* AcpError.AcpRequestError.invalidParams(
|
||||
"Mock invalid params for session/set_config_option",
|
||||
{
|
||||
method: "session/set_config_option",
|
||||
params: request,
|
||||
},
|
||||
);
|
||||
}
|
||||
if (request.configId === "mode" && typeof request.value === "string") {
|
||||
currentModeId = request.value;
|
||||
}
|
||||
if (request.configId === "model" && typeof request.value === "string") {
|
||||
currentModelId = request.value;
|
||||
}
|
||||
if (request.configId === "reasoning" && typeof request.value === "string") {
|
||||
currentReasoning = request.value;
|
||||
}
|
||||
if (request.configId === "context" && typeof request.value === "string") {
|
||||
currentContext = request.value;
|
||||
}
|
||||
if (request.configId === "fast") {
|
||||
currentFast = request.value === true || request.value === "true";
|
||||
}
|
||||
return {
|
||||
configOptions: configOptions(),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleCancel(({ sessionId }) =>
|
||||
Effect.sync(() => {
|
||||
cancelledSessions.add(String(sessionId ?? "mock-session-1"));
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handlePrompt((request) =>
|
||||
Effect.gen(function* () {
|
||||
const requestedSessionId = String(request.sessionId ?? sessionId);
|
||||
|
||||
if (emitInterleavedAssistantToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "before tool" },
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["echo", "hello"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: "hello",
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "after tool" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitToolCalls) {
|
||||
const toolCallId = "tool-call-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
rawInput: {
|
||||
command: ["cat", "server/package.json"],
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
const permission = yield* agent.client.requestPermission({
|
||||
sessionId: requestedSessionId,
|
||||
toolCall: {
|
||||
toolCallId,
|
||||
title: "`cat server/package.json`",
|
||||
kind: "execute",
|
||||
status: "pending",
|
||||
content: [
|
||||
{
|
||||
type: "content",
|
||||
content: {
|
||||
type: "text",
|
||||
text: "Not in allowlist: cat server/package.json",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
options: [
|
||||
{ optionId: "allow-once", name: "Allow once", kind: "allow_once" },
|
||||
{ optionId: "allow-always", name: "Allow always", kind: "allow_always" },
|
||||
{ optionId: "reject-once", name: "Reject", kind: "reject_once" },
|
||||
],
|
||||
});
|
||||
|
||||
const cancelled =
|
||||
cancelledSessions.delete(requestedSessionId) ||
|
||||
permission.outcome.outcome === "cancelled";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
title: "Terminal",
|
||||
kind: "execute",
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
exitCode: 0,
|
||||
stdout: '{ "name": "t3" }',
|
||||
stderr: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: cancelled ? "cancelled" : "end_turn" };
|
||||
}
|
||||
|
||||
if (emitGenericToolPlaceholders) {
|
||||
const toolCallId = "tool-call-generic-1";
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call",
|
||||
toolCallId,
|
||||
title: "Read File",
|
||||
kind: "read",
|
||||
status: "pending",
|
||||
rawInput: {},
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "in_progress",
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "tool_call_update",
|
||||
toolCallId,
|
||||
status: "completed",
|
||||
rawOutput: {
|
||||
content: "package.json\n",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
if (emitAskQuestion) {
|
||||
yield* agent.client.extRequest("cursor/ask_question", {
|
||||
toolCallId: "ask-question-tool-call-1",
|
||||
title: "Question",
|
||||
questions: [
|
||||
{
|
||||
id: "scope",
|
||||
prompt: "Which scope?",
|
||||
options: [
|
||||
{ id: "workspace", label: "Workspace" },
|
||||
{ id: "session", label: "Session" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "plan",
|
||||
entries: [
|
||||
{
|
||||
content: "Inspect mock ACP state",
|
||||
priority: "high",
|
||||
status: "completed",
|
||||
},
|
||||
{
|
||||
content: "Implement the requested change",
|
||||
priority: "high",
|
||||
status: "in_progress",
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
yield* agent.client.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "agent_message_chunk",
|
||||
content: { type: "text", text: promptResponseText ?? "hello from mock" },
|
||||
},
|
||||
});
|
||||
|
||||
return { stopReason: "end_turn" };
|
||||
}),
|
||||
);
|
||||
|
||||
yield* agent.handleUnknownExtRequest((method, params) => {
|
||||
if (method !== "session/mode/set") {
|
||||
return Effect.fail(AcpError.AcpRequestError.methodNotFound(method));
|
||||
}
|
||||
|
||||
const nextModeId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"modeId" in params &&
|
||||
typeof params.modeId === "string"
|
||||
? params.modeId
|
||||
: typeof params === "object" &&
|
||||
params !== null &&
|
||||
"mode" in params &&
|
||||
typeof params.mode === "string"
|
||||
? params.mode
|
||||
: undefined;
|
||||
const requestedSessionId =
|
||||
typeof params === "object" &&
|
||||
params !== null &&
|
||||
"sessionId" in params &&
|
||||
typeof params.sessionId === "string"
|
||||
? params.sessionId
|
||||
: sessionId;
|
||||
|
||||
if (typeof nextModeId === "string" && nextModeId.trim()) {
|
||||
currentModeId = nextModeId.trim();
|
||||
return agent.client
|
||||
.sessionUpdate({
|
||||
sessionId: requestedSessionId,
|
||||
update: {
|
||||
sessionUpdate: "current_mode_update",
|
||||
currentModeId,
|
||||
},
|
||||
})
|
||||
.pipe(Effect.as({}));
|
||||
}
|
||||
|
||||
return Effect.succeed({});
|
||||
});
|
||||
|
||||
return yield* Effect.never;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
EffectAcpAgent.layerStdio(
|
||||
requestLogPath
|
||||
? {
|
||||
logIncoming: true,
|
||||
logger: (event) => {
|
||||
if (event.direction !== "incoming" || event.stage !== "raw") {
|
||||
return Effect.void;
|
||||
}
|
||||
if (typeof event.payload !== "string") {
|
||||
return Effect.void;
|
||||
}
|
||||
const payload = event.payload;
|
||||
return Effect.sync(() => {
|
||||
appendFileSync(
|
||||
requestLogPath,
|
||||
payload.endsWith("\n") ? payload : `${payload}\n`,
|
||||
"utf8",
|
||||
);
|
||||
});
|
||||
},
|
||||
}
|
||||
: {},
|
||||
),
|
||||
),
|
||||
Effect.scoped,
|
||||
Effect.provide(NodeServices.layer),
|
||||
);
|
||||
|
||||
NodeRuntime.runMain(program);
|
||||
+20
-15
@@ -147,13 +147,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");
|
||||
@@ -203,8 +203,10 @@ 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 = {
|
||||
name: serverPackageJson.name,
|
||||
@@ -214,22 +216,25 @@ 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,
|
||||
overrides: rootPackageJson.overrides,
|
||||
};
|
||||
|
||||
pkg.dependencies = resolveCatalogDependencies(
|
||||
pkg.dependencies,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"apps/server dependencies",
|
||||
);
|
||||
pkg.overrides = resolveCatalogDependencies(
|
||||
pkg.overrides,
|
||||
rootPackageJson.workspaces.catalog,
|
||||
"root overrides",
|
||||
);
|
||||
|
||||
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 };
|
||||
|
||||
@@ -1,435 +0,0 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import process from "node:process";
|
||||
import readline from "node:readline";
|
||||
|
||||
type JsonPrimitive = null | boolean | number | string;
|
||||
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
|
||||
|
||||
type JsonRpcId = number | string;
|
||||
|
||||
type JsonRpcMessage = {
|
||||
jsonrpc?: string;
|
||||
id?: JsonRpcId;
|
||||
method?: string;
|
||||
params?: JsonValue;
|
||||
result?: JsonValue;
|
||||
error?: JsonValue;
|
||||
headers?: JsonValue;
|
||||
};
|
||||
|
||||
type SelectLeafOption = {
|
||||
value: string;
|
||||
label?: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
type SelectGroupOption = {
|
||||
label?: string;
|
||||
name?: string;
|
||||
options: SelectLeafOption[];
|
||||
};
|
||||
|
||||
type SessionConfigOption = {
|
||||
id: string;
|
||||
name?: string;
|
||||
category?: string;
|
||||
type?: string;
|
||||
options?: Array<SelectLeafOption | SelectGroupOption>;
|
||||
};
|
||||
|
||||
type SessionNewResult = {
|
||||
sessionId: string;
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type SetConfigResult = {
|
||||
configOptions?: SessionConfigOption[];
|
||||
};
|
||||
|
||||
type PendingRequest = {
|
||||
method: string;
|
||||
resolve: (value: JsonValue | undefined) => void;
|
||||
reject: (error: Error) => void;
|
||||
};
|
||||
|
||||
const targetCwd = process.argv[2] ?? process.cwd();
|
||||
const targetModel = process.argv[3] ?? "gpt-5.4";
|
||||
const promptText = process.argv[4] ?? "helo";
|
||||
const targetReasoning = process.env.CURSOR_REASONING ?? "";
|
||||
const targetContext = process.env.CURSOR_CONTEXT ?? "";
|
||||
const targetFast = process.env.CURSOR_FAST ?? "";
|
||||
const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
|
||||
const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
|
||||
const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
|
||||
|
||||
function logSection(title: string, value: unknown) {
|
||||
process.stdout.write(`\n=== ${title} ===\n`);
|
||||
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
|
||||
}
|
||||
|
||||
function fail(message: string): never {
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
function asString(value: JsonValue | undefined): string | null {
|
||||
return typeof value === "string" ? value : null;
|
||||
}
|
||||
|
||||
function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
|
||||
if (!option || option.type !== "select" || !Array.isArray(option.options)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
for (const entry of option.options) {
|
||||
if (!entry || typeof entry !== "object") {
|
||||
continue;
|
||||
}
|
||||
if ("value" in entry && typeof entry.value === "string") {
|
||||
values.push(entry.value);
|
||||
continue;
|
||||
}
|
||||
if ("options" in entry && Array.isArray(entry.options)) {
|
||||
for (const nested of entry.options) {
|
||||
if (nested && typeof nested === "object" && typeof nested.value === "string") {
|
||||
values.push(nested.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
function findConfigOption(
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
): SessionConfigOption | undefined {
|
||||
return configOptions.find(predicate);
|
||||
}
|
||||
|
||||
function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
|
||||
const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
|
||||
return haystack.includes(keyword.toLowerCase());
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise<void>((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
class JsonRpcChild {
|
||||
readonly child: ChildProcessWithoutNullStreams;
|
||||
readonly pending = new Map<JsonRpcId, PendingRequest>();
|
||||
nextId = 1;
|
||||
closed = false;
|
||||
|
||||
constructor(bin: string, args: string[], cwd: string) {
|
||||
this.child = spawn(bin, args, {
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
env: process.env,
|
||||
});
|
||||
|
||||
this.child.on("exit", (code, signal) => {
|
||||
this.closed = true;
|
||||
const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
this.child.on("error", (error) => {
|
||||
this.closed = true;
|
||||
for (const pending of this.pending.values()) {
|
||||
pending.reject(error);
|
||||
}
|
||||
this.pending.clear();
|
||||
});
|
||||
|
||||
const stdout = readline.createInterface({ input: this.child.stdout });
|
||||
stdout.on("line", (line) => {
|
||||
void this.handleStdoutLine(line);
|
||||
});
|
||||
|
||||
const stderr = readline.createInterface({ input: this.child.stderr });
|
||||
stderr.on("line", (line) => {
|
||||
process.stdout.write(`[stderr] ${line}\n`);
|
||||
});
|
||||
}
|
||||
|
||||
write(message: JsonRpcMessage) {
|
||||
if (this.closed) {
|
||||
fail("ACP process is already closed.");
|
||||
}
|
||||
const payload = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
headers: [],
|
||||
...message,
|
||||
});
|
||||
process.stdout.write(`>>> ${payload}\n`);
|
||||
this.child.stdin.write(`${payload}\n`);
|
||||
}
|
||||
|
||||
async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
|
||||
const id = this.nextId++;
|
||||
|
||||
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
|
||||
const timeout = setTimeout(() => {
|
||||
this.pending.delete(id);
|
||||
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
|
||||
}, timeoutMs);
|
||||
|
||||
this.pending.set(id, {
|
||||
method,
|
||||
resolve: (value) => {
|
||||
clearTimeout(timeout);
|
||||
resolve(value);
|
||||
},
|
||||
reject: (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
this.write({
|
||||
id,
|
||||
method,
|
||||
params,
|
||||
});
|
||||
|
||||
return responsePromise;
|
||||
}
|
||||
|
||||
notify(method: string, params: JsonValue) {
|
||||
this.write({
|
||||
method,
|
||||
params,
|
||||
});
|
||||
}
|
||||
|
||||
respond(id: JsonRpcId, result: JsonValue) {
|
||||
this.write({
|
||||
id,
|
||||
result,
|
||||
});
|
||||
}
|
||||
|
||||
respondError(id: JsonRpcId, code: number, message: string) {
|
||||
this.write({
|
||||
id,
|
||||
error: {
|
||||
code,
|
||||
message,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async handleStdoutLine(line: string) {
|
||||
if (line.trim().length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
process.stdout.write(`<<< ${line}\n`);
|
||||
|
||||
let message: JsonRpcMessage;
|
||||
try {
|
||||
message = JSON.parse(line) as JsonRpcMessage;
|
||||
} catch (error) {
|
||||
process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && !message.method) {
|
||||
const pending = this.pending.get(message.id);
|
||||
if (!pending) {
|
||||
return;
|
||||
}
|
||||
this.pending.delete(message.id);
|
||||
if (typeof message.error !== "undefined") {
|
||||
pending.reject(
|
||||
new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
|
||||
);
|
||||
return;
|
||||
}
|
||||
pending.resolve(message.result);
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
|
||||
this.respond(message.id, {
|
||||
outcome: {
|
||||
outcome: "selected",
|
||||
optionId: "allow",
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof message.id !== "undefined" && message.id !== "") {
|
||||
this.respondError(
|
||||
message.id,
|
||||
-32601,
|
||||
`Unhandled server request: ${message.method ?? "unknown"}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async close() {
|
||||
if (this.closed) {
|
||||
return;
|
||||
}
|
||||
this.child.kill("SIGTERM");
|
||||
await sleep(250);
|
||||
if (!this.closed) {
|
||||
this.child.kill("SIGKILL");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function setSelectOptionIfAdvertised(
|
||||
rpc: JsonRpcChild,
|
||||
sessionId: string,
|
||||
configOptions: SessionConfigOption[],
|
||||
predicate: (option: SessionConfigOption) => boolean,
|
||||
value: string,
|
||||
label: string,
|
||||
) {
|
||||
if (value.length === 0) {
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const option = findConfigOption(configOptions, predicate);
|
||||
const values = flattenSelectValues(option);
|
||||
if (!option || !values.includes(value)) {
|
||||
logSection(`SKIP_${label}`, {
|
||||
requestedValue: value,
|
||||
availableValues: values,
|
||||
});
|
||||
return configOptions;
|
||||
}
|
||||
|
||||
const response = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: option.id,
|
||||
value,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
|
||||
logSection(`SET_${label}_RESPONSE`, response);
|
||||
return response?.configOptions ?? configOptions;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
|
||||
|
||||
try {
|
||||
const initializeResponse = await rpc.request("initialize", {
|
||||
protocolVersion: 1,
|
||||
clientCapabilities: {
|
||||
fs: { readTextFile: false, writeTextFile: false },
|
||||
terminal: false,
|
||||
_meta: {
|
||||
parameterizedModelPicker: true,
|
||||
},
|
||||
},
|
||||
clientInfo: {
|
||||
name: "cursor-acp-model-mismatch-probe",
|
||||
version: "0.0.0",
|
||||
},
|
||||
});
|
||||
logSection("INITIALIZE_RESPONSE", initializeResponse);
|
||||
|
||||
const authenticateResponse = await rpc.request("authenticate", {
|
||||
methodId: "cursor_login",
|
||||
});
|
||||
logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
|
||||
|
||||
const sessionResponse = (await rpc.request("session/new", {
|
||||
cwd: targetCwd,
|
||||
mcpServers: [],
|
||||
})) as SessionNewResult;
|
||||
logSection("SESSION_NEW_RESPONSE", sessionResponse);
|
||||
|
||||
const sessionId = asString(sessionResponse.sessionId);
|
||||
if (!sessionId) {
|
||||
fail("session/new did not return a sessionId.");
|
||||
}
|
||||
|
||||
let configOptions = sessionResponse.configOptions ?? [];
|
||||
const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
|
||||
const advertisedModels = flattenSelectValues(modelConfig);
|
||||
logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
|
||||
|
||||
if (!modelConfig || modelConfig.type !== "select") {
|
||||
fail("Cursor ACP did not expose a select-type model config option.");
|
||||
}
|
||||
|
||||
if (!advertisedModels.includes(targetModel)) {
|
||||
fail(
|
||||
`Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
|
||||
);
|
||||
}
|
||||
|
||||
const setModelResponse = (await rpc.request("session/set_config_option", {
|
||||
sessionId,
|
||||
configId: modelConfig.id,
|
||||
value: targetModel,
|
||||
})) as SetConfigResult | null | undefined;
|
||||
logSection("SET_MODEL_RESPONSE", setModelResponse);
|
||||
|
||||
configOptions = setModelResponse?.configOptions ?? configOptions;
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "thought_level",
|
||||
targetReasoning,
|
||||
"REASONING",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "context"),
|
||||
targetContext,
|
||||
"CONTEXT",
|
||||
);
|
||||
|
||||
configOptions = await setSelectOptionIfAdvertised(
|
||||
rpc,
|
||||
sessionId,
|
||||
configOptions,
|
||||
(option) => option.category === "model_config" && matchesKeyword(option, "fast"),
|
||||
targetFast,
|
||||
"FAST",
|
||||
);
|
||||
|
||||
const promptResponse = await rpc.request("session/prompt", {
|
||||
sessionId,
|
||||
prompt: [
|
||||
{
|
||||
type: "text",
|
||||
text: promptText,
|
||||
},
|
||||
],
|
||||
});
|
||||
logSection("PROMPT_RESPONSE", promptResponse);
|
||||
|
||||
await sleep(promptWaitMs);
|
||||
rpc.notify("session/cancel", { sessionId });
|
||||
} finally {
|
||||
await rpc.close();
|
||||
}
|
||||
}
|
||||
|
||||
void main().catch((error: unknown) => {
|
||||
process.stderr.write(
|
||||
`${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
import { Effect, FileSystem, Path } from "effect";
|
||||
import * as Random from "effect/Random";
|
||||
|
||||
export const writeFileStringAtomically = (input: {
|
||||
readonly filePath: string;
|
||||
readonly contents: string;
|
||||
}) =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const tempFileId = yield* Random.nextUUIDv4;
|
||||
const targetDirectory = path.dirname(input.filePath);
|
||||
|
||||
yield* fs.makeDirectory(targetDirectory, { recursive: true });
|
||||
const tempDirectory = yield* fs.makeTempDirectoryScoped({
|
||||
directory: targetDirectory,
|
||||
prefix: `${path.basename(input.filePath)}.`,
|
||||
});
|
||||
const tempPath = path.join(tempDirectory, `${tempFileId}.tmp`);
|
||||
|
||||
yield* fs.writeFileString(tempPath, input.contents);
|
||||
yield* fs.rename(tempPath, input.filePath);
|
||||
}),
|
||||
);
|
||||
@@ -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";
|
||||
|
||||
@@ -5,7 +5,7 @@ import type {
|
||||
AuthSessionId,
|
||||
} from "@t3tools/contracts";
|
||||
import { Data, DateTime, Duration, Effect, Context } from "effect";
|
||||
import type { SessionRole } from "./SessionCredentialService.ts";
|
||||
import { SessionRole } from "./SessionCredentialService";
|
||||
|
||||
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
|
||||
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
+6
-17
@@ -5,24 +5,13 @@ import * as Layer from "effect/Layer";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { authCommand } from "./cli/auth.ts";
|
||||
import { sharedServerCommandFlags } from "./cli/config.ts";
|
||||
import { projectCommand } from "./cli/project.ts";
|
||||
import { runServerCommand, serveCommand, startCommand } from "./cli/server.ts";
|
||||
import { cli } from "./cli";
|
||||
import { version } from "../package.json" with { type: "json" };
|
||||
|
||||
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
|
||||
|
||||
export const cli = Command.make("t3", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) => runServerCommand(flags)),
|
||||
Command.withSubcommands([startCommand, serveCommand, authCommand, projectCommand]),
|
||||
Command.run(cli, { version }).pipe(
|
||||
Effect.scoped,
|
||||
Effect.provide(CliRuntimeLayer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(cli, { version: packageJson.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 }));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Schema } from "effect";
|
||||
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
|
||||
/**
|
||||
* CheckpointUnavailableError - Expected checkpoint does not exist.
|
||||
@@ -35,6 +35,9 @@ export class CheckpointInvariantError extends Schema.TaggedErrorClass<Checkpoint
|
||||
}
|
||||
}
|
||||
|
||||
export type CheckpointStoreError = VcsError | CheckpointInvariantError | CheckpointUnavailableError;
|
||||
export type CheckpointStoreError =
|
||||
| GitCommandError
|
||||
| CheckpointInvariantError
|
||||
| CheckpointUnavailableError;
|
||||
|
||||
export type CheckpointServiceError = CheckpointStoreError | ProjectionRepositoryError;
|
||||
@@ -48,7 +48,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly cwd: string;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
@@ -69,14 +68,9 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
return true;
|
||||
}),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
|
||||
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
cwd,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
diffCheckpointsCalls.push({ fromCheckpointRef, toCheckpointRef, cwd });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
@@ -86,20 +80,12 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
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()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -111,7 +97,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
@@ -123,7 +108,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
cwd: "/tmp/workspace",
|
||||
fromCheckpointRef: expectedFromRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
},
|
||||
]);
|
||||
expect(result).toEqual({
|
||||
@@ -134,70 +118,6 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("defaults to hide whitespace changes", async () => {
|
||||
const projectId = ProjectId.make("project-default-whitespace");
|
||||
const threadId = ThreadId.make("thread-default-whitespace");
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
const diffCheckpointsCalls: Array<{ readonly ignoreWhitespace: boolean }> = [];
|
||||
|
||||
const threadCheckpointContext = makeThreadCheckpointContext({
|
||||
projectId,
|
||||
threadId,
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
worktreePath: null,
|
||||
checkpointTurnCount: 1,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const checkpointStore: CheckpointStoreShape = {
|
||||
isGitRepository: () => Effect.succeed(true),
|
||||
captureCheckpoint: () => Effect.void,
|
||||
hasCheckpointRef: () => Effect.succeed(true),
|
||||
restoreCheckpoint: () => Effect.succeed(true),
|
||||
diffCheckpoints: ({ ignoreWhitespace }) =>
|
||||
Effect.sync(() => {
|
||||
diffCheckpointsCalls.push({ ignoreWhitespace });
|
||||
return "diff patch";
|
||||
}),
|
||||
deleteCheckpointRefs: () => Effect.void,
|
||||
};
|
||||
|
||||
const layer = CheckpointDiffQueryLive.pipe(
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
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()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const query = yield* CheckpointDiffQuery;
|
||||
return yield* query.getTurnDiff({
|
||||
threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: 1,
|
||||
});
|
||||
}).pipe(Effect.provide(layer)),
|
||||
);
|
||||
|
||||
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
|
||||
});
|
||||
|
||||
it("fails when the thread is missing from the snapshot", async () => {
|
||||
const threadId = ThreadId.make("thread-missing");
|
||||
|
||||
@@ -214,20 +134,12 @@ describe("CheckpointDiffQueryLive", () => {
|
||||
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
|
||||
Layer.provideMerge(
|
||||
Layer.succeed(ProjectionSnapshotQuery, {
|
||||
getCommandReadModel: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the command read model"),
|
||||
getSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
|
||||
getShellSnapshot: () =>
|
||||
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
|
||||
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
|
||||
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()),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -24,7 +24,6 @@ const make = Effect.gen(function* () {
|
||||
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
|
||||
function* (input) {
|
||||
const operation = "CheckpointDiffQuery.getTurnDiff";
|
||||
const ignoreWhitespace = input.ignoreWhitespace ?? true;
|
||||
|
||||
if (input.fromTurnCount === input.toTurnCount) {
|
||||
const emptyDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -132,7 +131,6 @@ const make = Effect.gen(function* () {
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
fallbackFromToHead: false,
|
||||
ignoreWhitespace,
|
||||
});
|
||||
|
||||
const turnDiff: OrchestrationGetTurnDiffResultType = {
|
||||
@@ -159,7 +157,6 @@ const make = Effect.gen(function* () {
|
||||
threadId: input.threadId,
|
||||
fromTurnCount: 0,
|
||||
toTurnCount: input.toTurnCount,
|
||||
ignoreWhitespace: input.ignoreWhitespace ?? true,
|
||||
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
|
||||
|
||||
return {
|
||||
|
||||
@@ -8,27 +8,24 @@ import { describe, expect } from "vitest";
|
||||
import { checkpointRefForThreadTurn } from "../Utils.ts";
|
||||
import { CheckpointStoreLive } from "./CheckpointStore.ts";
|
||||
import { CheckpointStore } from "../Services/CheckpointStore.ts";
|
||||
import * as VcsDriverRegistry from "../../vcs/VcsDriverRegistry.ts";
|
||||
import * as VcsProcess from "../../vcs/VcsProcess.ts";
|
||||
import type { VcsError } from "@t3tools/contracts";
|
||||
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
|
||||
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-checkpoint-store-test-",
|
||||
});
|
||||
const VcsProcessTestLayer = VcsProcess.layer.pipe(Layer.provide(NodeServices.layer));
|
||||
const VcsDriverTestLayer = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProcessTestLayer));
|
||||
const GitCoreTestLayer = GitCoreLive.pipe(
|
||||
Layer.provide(ServerConfigLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const CheckpointStoreTestLayer = CheckpointStoreLive.pipe(
|
||||
Layer.provideMerge(VcsDriverTestLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const TestLayer = CheckpointStoreTestLayer.pipe(
|
||||
Layer.provideMerge(VcsProcessTestLayer),
|
||||
Layer.provideMerge(VcsDriverTestLayer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provide(GitCoreTestLayer),
|
||||
Layer.provide(NodeServices.layer),
|
||||
);
|
||||
const TestLayer = Layer.mergeAll(NodeServices.layer, GitCoreTestLayer, CheckpointStoreTestLayer);
|
||||
|
||||
function makeTmpDir(
|
||||
prefix = "checkpoint-store-test-",
|
||||
@@ -52,12 +49,11 @@ function writeTextFile(
|
||||
function git(
|
||||
cwd: string,
|
||||
args: ReadonlyArray<string>,
|
||||
): Effect.Effect<string, VcsError, VcsProcess.VcsProcess> {
|
||||
): Effect.Effect<string, GitCommandError, GitCore> {
|
||||
return Effect.gen(function* () {
|
||||
const process = yield* VcsProcess.VcsProcess;
|
||||
const result = yield* process.run({
|
||||
const gitCore = yield* GitCore;
|
||||
const result = yield* gitCore.execute({
|
||||
operation: "CheckpointStore.test.git",
|
||||
command: "git",
|
||||
cwd,
|
||||
args,
|
||||
timeoutMs: 10_000,
|
||||
@@ -70,11 +66,12 @@ function initRepoWithCommit(
|
||||
cwd: string,
|
||||
): Effect.Effect<
|
||||
void,
|
||||
VcsError | PlatformError.PlatformError,
|
||||
VcsProcess.VcsProcess | FileSystem.FileSystem
|
||||
GitCommandError | PlatformError.PlatformError,
|
||||
GitCore | FileSystem.FileSystem
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
yield* git(cwd, ["init"]);
|
||||
const core = yield* GitCore;
|
||||
yield* core.initRepo({ cwd });
|
||||
yield* git(cwd, ["config", "user.email", "[email protected]"]);
|
||||
yield* git(cwd, ["config", "user.name", "Test"]);
|
||||
yield* writeTextFile(path.join(cwd, "README.md"), "# test\n");
|
||||
@@ -114,7 +111,6 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
|
||||
expect(diff).toContain("diff --git");
|
||||
@@ -122,80 +118,5 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
|
||||
expect(diff).toContain("+line 04999");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("can hide indentation churn when changes wrap existing lines", () =>
|
||||
Effect.gen(function* () {
|
||||
const tmp = yield* makeTmpDir();
|
||||
yield* initRepoWithCommit(tmp);
|
||||
const checkpointStore = yield* CheckpointStore;
|
||||
const threadId = ThreadId.make("thread-checkpoint-store-whitespace");
|
||||
const fromCheckpointRef = checkpointRefForThreadTurn(threadId, 0);
|
||||
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
|
||||
|
||||
const componentPath = path.join(tmp, "Component.tsx");
|
||||
yield* writeTextFile(
|
||||
componentPath,
|
||||
[
|
||||
"export function View() {",
|
||||
" return (",
|
||||
" <section>",
|
||||
" <h1>Title</h1>",
|
||||
" <p>Body</p>",
|
||||
" </section>",
|
||||
" );",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: fromCheckpointRef,
|
||||
});
|
||||
yield* writeTextFile(
|
||||
componentPath,
|
||||
[
|
||||
"export function View() {",
|
||||
" return (",
|
||||
" <section>",
|
||||
" {isReady ? (",
|
||||
" <div>",
|
||||
" <h1>Title</h1>",
|
||||
" <p>Body</p>",
|
||||
" </div>",
|
||||
" ) : null}",
|
||||
" </section>",
|
||||
" );",
|
||||
"}",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* checkpointStore.captureCheckpoint({
|
||||
cwd: tmp,
|
||||
checkpointRef: toCheckpointRef,
|
||||
});
|
||||
|
||||
const normalDiff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: false,
|
||||
});
|
||||
const whitespaceIgnoredDiff = yield* checkpointStore.diffCheckpoints({
|
||||
cwd: tmp,
|
||||
fromCheckpointRef,
|
||||
toCheckpointRef,
|
||||
ignoreWhitespace: true,
|
||||
});
|
||||
|
||||
expect(normalDiff).toContain("diff --git");
|
||||
expect(normalDiff).toContain("- <h1>Title</h1>");
|
||||
expect(normalDiff).toContain("+ <h1>Title</h1>");
|
||||
expect(whitespaceIgnoredDiff).toContain("diff --git");
|
||||
expect(whitespaceIgnoredDiff).toContain("+ {isReady ? (");
|
||||
expect(whitespaceIgnoredDiff).toContain("+ <div>");
|
||||
expect(whitespaceIgnoredDiff).not.toContain("- <h1>Title</h1>");
|
||||
expect(whitespaceIgnoredDiff).not.toContain("+ <h1>Title</h1>");
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -14,36 +14,18 @@ import { randomUUID } from "node:crypto";
|
||||
import { Effect, Layer, FileSystem, Path } from "effect";
|
||||
|
||||
import { CheckpointInvariantError } from "../Errors.ts";
|
||||
import { VcsProcessExitError } from "@t3tools/contracts";
|
||||
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
|
||||
import { GitCommandError } from "@t3tools/contracts";
|
||||
import { GitCore } from "../../git/Services/GitCore.ts";
|
||||
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
|
||||
import { CheckpointRef } from "@t3tools/contracts";
|
||||
|
||||
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
|
||||
|
||||
const makeCheckpointStore = Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const vcsRegistry = yield* VcsDriverRegistry;
|
||||
const vcs = {
|
||||
execute: (input: {
|
||||
readonly operation: string;
|
||||
readonly cwd: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly stdin?: string;
|
||||
readonly env?: NodeJS.ProcessEnv;
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly truncateOutputAtMaxBytes?: boolean;
|
||||
}) =>
|
||||
vcsRegistry
|
||||
.resolve({ cwd: input.cwd, requestedKind: "git" })
|
||||
.pipe(Effect.flatMap((handle) => handle.driver.execute(input))),
|
||||
};
|
||||
const git = yield* GitCore;
|
||||
|
||||
const resolveHeadCommit = (cwd: string) =>
|
||||
vcs
|
||||
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveHeadCommit",
|
||||
cwd,
|
||||
@@ -52,7 +34,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
@@ -60,18 +42,21 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
}),
|
||||
);
|
||||
|
||||
const hasHeadCommit = (cwd: string) =>
|
||||
vcs
|
||||
const hasHeadCommit = (cwd: string): Effect.Effect<boolean, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.hasHeadCommit",
|
||||
cwd,
|
||||
args: ["rev-parse", "--verify", "HEAD"],
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(Effect.map((result) => result.exitCode === 0));
|
||||
.pipe(Effect.map((result) => result.code === 0));
|
||||
|
||||
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
|
||||
vcs
|
||||
const resolveCheckpointCommit = (
|
||||
cwd: string,
|
||||
checkpointRef: CheckpointRef,
|
||||
): Effect.Effect<string | null, GitCommandError> =>
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.resolveCheckpointCommit",
|
||||
cwd,
|
||||
@@ -80,7 +65,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => {
|
||||
if (result.exitCode !== 0) {
|
||||
if (result.code !== 0) {
|
||||
return null;
|
||||
}
|
||||
const commit = result.stdout.trim();
|
||||
@@ -89,7 +74,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
);
|
||||
|
||||
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
|
||||
vcs
|
||||
git
|
||||
.execute({
|
||||
operation: "CheckpointStore.isGitRepository",
|
||||
cwd,
|
||||
@@ -97,7 +82,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
allowNonZeroExit: true,
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
|
||||
Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"),
|
||||
Effect.catch(() => Effect.succeed(false)),
|
||||
);
|
||||
|
||||
@@ -121,7 +106,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["read-tree", "HEAD"],
|
||||
@@ -129,14 +114,14 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["add", "-A", "--", "."],
|
||||
env: commitEnv,
|
||||
});
|
||||
|
||||
const writeTreeResult = yield* vcs.execute({
|
||||
const writeTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["write-tree"],
|
||||
@@ -144,17 +129,16 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
const treeOid = writeTreeResult.stdout.trim();
|
||||
if (treeOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git write-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git write-tree returned an empty tree oid.",
|
||||
});
|
||||
}
|
||||
|
||||
const message = `t3 checkpoint ref=${input.checkpointRef}`;
|
||||
const commitTreeResult = yield* vcs.execute({
|
||||
const commitTreeResult = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["commit-tree", treeOid, "-m", message],
|
||||
@@ -162,16 +146,15 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
});
|
||||
const commitOid = commitTreeResult.stdout.trim();
|
||||
if (commitOid.length === 0) {
|
||||
return yield* new VcsProcessExitError({
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git commit-tree",
|
||||
cwd: input.cwd,
|
||||
exitCode: 0,
|
||||
detail: "git commit-tree returned an empty commit oid.",
|
||||
});
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", input.checkpointRef, commitOid],
|
||||
@@ -212,12 +195,12 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
return false;
|
||||
}
|
||||
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
|
||||
});
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["clean", "-fd", "--", "."],
|
||||
@@ -225,7 +208,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
|
||||
const headExists = yield* hasHeadCommit(input.cwd);
|
||||
if (headExists) {
|
||||
yield* vcs.execute({
|
||||
yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["reset", "--quiet", "--", "."],
|
||||
@@ -250,30 +233,18 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
}
|
||||
|
||||
if (!fromCommitOid || !toCommitOid) {
|
||||
return yield* new VcsProcessExitError({
|
||||
return yield* new GitCommandError({
|
||||
operation,
|
||||
command: "git diff",
|
||||
cwd: input.cwd,
|
||||
exitCode: 1,
|
||||
detail: "Checkpoint ref is unavailable for diff operation.",
|
||||
});
|
||||
}
|
||||
|
||||
const diffArgs = [
|
||||
"diff",
|
||||
"--patch",
|
||||
"--minimal",
|
||||
"--no-color",
|
||||
...(input.ignoreWhitespace ? ["--ignore-all-space"] : []),
|
||||
fromCommitOid,
|
||||
toCommitOid,
|
||||
];
|
||||
|
||||
const result = yield* vcs.execute({
|
||||
const result = yield* git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: diffArgs,
|
||||
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
|
||||
args: ["diff", "--patch", "--minimal", "--no-color", fromCommitOid, toCommitOid],
|
||||
});
|
||||
|
||||
return result.stdout;
|
||||
@@ -288,7 +259,7 @@ const makeCheckpointStore = Effect.gen(function* () {
|
||||
yield* Effect.forEach(
|
||||
input.checkpointRefs,
|
||||
(checkpointRef) =>
|
||||
vcs.execute({
|
||||
git.execute({
|
||||
operation,
|
||||
cwd: input.cwd,
|
||||
args: ["update-ref", "-d", checkpointRef],
|
||||
|
||||
@@ -32,7 +32,6 @@ export interface DiffCheckpointsInput {
|
||||
readonly fromCheckpointRef: CheckpointRef;
|
||||
readonly toCheckpointRef: CheckpointRef;
|
||||
readonly fallbackFromToHead?: boolean;
|
||||
readonly ignoreWhitespace: boolean;
|
||||
}
|
||||
|
||||
export interface DeleteCheckpointRefsInput {
|
||||
|
||||
@@ -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 "./config.ts";
|
||||
import { deriveServerPaths } from "./config";
|
||||
import { resolveServerConfig } from "./cli";
|
||||
|
||||
it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
const defaultObservabilityConfig = {
|
||||
@@ -46,8 +46,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -89,8 +87,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -112,8 +108,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(true),
|
||||
logWebSocketEvents: Option.some(true),
|
||||
tailscaleServeEnabled: Option.some(true),
|
||||
tailscaleServePort: Option.some(8443),
|
||||
},
|
||||
Option.some("Debug"),
|
||||
).pipe(
|
||||
@@ -155,8 +149,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: true,
|
||||
tailscaleServePort: 8443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -169,8 +161,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
@@ -186,8 +176,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.some(false),
|
||||
logWebSocketEvents: Option.some(false),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -224,8 +212,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -243,8 +229,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
otlpTracesUrl: "http://localhost:4318/v1/traces",
|
||||
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
|
||||
});
|
||||
@@ -262,8 +246,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -299,8 +281,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
assert.equal(join(baseDir, "dev"), resolved.stateDir);
|
||||
}),
|
||||
@@ -325,8 +305,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -368,8 +346,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
noBrowser: false,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
|
||||
|
||||
@@ -385,8 +361,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.some("Debug"),
|
||||
).pipe(
|
||||
@@ -425,8 +399,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: true,
|
||||
logWebSocketEvents: true,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -460,8 +432,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
).pipe(
|
||||
@@ -493,8 +463,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -517,8 +485,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
Option.none(),
|
||||
{
|
||||
@@ -556,8 +522,6 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -15,8 +15,9 @@ import * as CliError from "effect/unstable/cli/CliError";
|
||||
import * as TestConsole from "effect/testing/TestConsole";
|
||||
import { Command } from "effect/unstable/cli";
|
||||
|
||||
import { cli } from "./bin.ts";
|
||||
import { cli } from "./cli.ts";
|
||||
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config.ts";
|
||||
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
|
||||
import {
|
||||
@@ -75,8 +76,6 @@ const makeCliTestServerConfig = (baseDir: string) =>
|
||||
desktopBootstrapToken: undefined,
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
} satisfies ServerConfigShape;
|
||||
});
|
||||
|
||||
@@ -148,7 +147,7 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Ef
|
||||
);
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
|
||||
it.effect("accepts the built-in lowercase log-level flag values", () =>
|
||||
runCliWithRuntime(["--log-level", "debug", "--version"]),
|
||||
);
|
||||
@@ -315,8 +314,8 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
|
||||
"--base-dir",
|
||||
baseDir,
|
||||
]);
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
const readModel = yield* projectionSnapshotQuery.getSnapshot();
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
const addedProject = readModel.projects.find(
|
||||
(project) => project.workspaceRoot === workspaceRoot && project.deletedAt === null,
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,243 +0,0 @@
|
||||
import { AuthSessionId } from "@t3tools/contracts";
|
||||
import { Console, Effect, Layer, Option, References } from "effect";
|
||||
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
|
||||
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
|
||||
import {
|
||||
formatIssuedPairingCredential,
|
||||
formatIssuedSession,
|
||||
formatPairingCredentialList,
|
||||
formatSessionList,
|
||||
} from "../cliAuthFormat.ts";
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import {
|
||||
authLocationFlags,
|
||||
type CliAuthLocationFlags,
|
||||
DurationFromString,
|
||||
resolveCliAuthConfig,
|
||||
} from "./config.ts";
|
||||
|
||||
const runWithAuthControlPlane = <A, E>(
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (authControlPlane: AuthControlPlaneShape) => Effect.Effect<A, E>,
|
||||
options?: {
|
||||
readonly quietLogs?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = options?.quietLogs ? "Error" : config.logLevel;
|
||||
return yield* Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
return yield* run(authControlPlane);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(AuthControlPlaneRuntimeLive).pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const ttlFlag = Flag.string("ttl").pipe(
|
||||
Flag.withSchema(DurationFromString),
|
||||
Flag.withDescription("TTL, for example `5m`, `1h`, `30d`, or `15 minutes`."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const jsonFlag = Flag.boolean("json").pipe(
|
||||
Flag.withDescription("Emit JSON instead of human-readable output."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const sessionRoleFlag = Flag.choice("role", ["owner", "client"]).pipe(
|
||||
Flag.withDescription("Role for the issued bearer session."),
|
||||
Flag.withDefault("owner"),
|
||||
);
|
||||
|
||||
const labelFlag = Flag.string("label").pipe(
|
||||
Flag.withDescription("Optional human-readable label."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const subjectFlag = Flag.string("subject").pipe(
|
||||
Flag.withDescription("Optional session subject."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const baseUrlFlag = Flag.string("base-url").pipe(
|
||||
Flag.withDescription("Optional public base URL used to print a ready `/pair#token=...` link."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const tokenOnlyFlag = Flag.boolean("token-only").pipe(
|
||||
Flag.withDescription("Print only the issued bearer token."),
|
||||
Flag.withDefault(false),
|
||||
);
|
||||
|
||||
const pairingCreateCommand = Command.make("create", {
|
||||
...authLocationFlags,
|
||||
ttl: ttlFlag,
|
||||
label: labelFlag,
|
||||
baseUrl: baseUrlFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Issue a new client pairing token."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* authControlPlane.createPairingLink({
|
||||
role: "client",
|
||||
subject: "one-time-token",
|
||||
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
|
||||
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
|
||||
});
|
||||
const output = formatIssuedPairingCredential(issued, {
|
||||
json: flags.json,
|
||||
...(Option.isSome(flags.baseUrl) ? { baseUrl: flags.baseUrl.value } : {}),
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingListCommand = Command.make("list", {
|
||||
...authLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List active client pairing tokens without revealing their secrets."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const pairingLinks = yield* authControlPlane.listPairingLinks({ role: "client" });
|
||||
yield* Console.log(formatPairingCredentialList(pairingLinks, { json: flags.json }));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingRevokeCommand = Command.make("revoke", {
|
||||
...authLocationFlags,
|
||||
id: Argument.string("id").pipe(Argument.withDescription("Pairing credential id to revoke.")),
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke an active client pairing token."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(flags, (authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const revoked = yield* authControlPlane.revokePairingLink(flags.id);
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked pairing credential ${flags.id}.\n`
|
||||
: `No active pairing credential found for ${flags.id}.\n`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const pairingCommand = Command.make("pairing").pipe(
|
||||
Command.withDescription("Manage one-time client pairing tokens."),
|
||||
Command.withSubcommands([pairingCreateCommand, pairingListCommand, pairingRevokeCommand]),
|
||||
);
|
||||
|
||||
const sessionIssueCommand = Command.make("issue", {
|
||||
...authLocationFlags,
|
||||
ttl: ttlFlag,
|
||||
role: sessionRoleFlag,
|
||||
label: labelFlag,
|
||||
subject: subjectFlag,
|
||||
tokenOnly: tokenOnlyFlag,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("Issue a bearer session token for headless or remote clients."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const issued = yield* authControlPlane.issueSession({
|
||||
role: flags.role,
|
||||
...(Option.isSome(flags.ttl) ? { ttl: flags.ttl.value } : {}),
|
||||
...(Option.isSome(flags.label) ? { label: flags.label.value } : {}),
|
||||
...(Option.isSome(flags.subject) ? { subject: flags.subject.value } : {}),
|
||||
});
|
||||
yield* Console.log(
|
||||
formatIssuedSession(issued, {
|
||||
json: flags.json,
|
||||
tokenOnly: flags.tokenOnly,
|
||||
}),
|
||||
);
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json || flags.tokenOnly,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionListCommand = Command.make("list", {
|
||||
...authLocationFlags,
|
||||
json: jsonFlag,
|
||||
}).pipe(
|
||||
Command.withDescription("List active sessions without revealing bearer tokens."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(
|
||||
flags,
|
||||
(authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const sessions = yield* authControlPlane.listSessions();
|
||||
yield* Console.log(formatSessionList(sessions, { json: flags.json }));
|
||||
}),
|
||||
{
|
||||
quietLogs: flags.json,
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionRevokeCommand = Command.make("revoke", {
|
||||
...authLocationFlags,
|
||||
sessionId: Argument.string("session-id").pipe(
|
||||
Argument.withDescription("Session id to revoke."),
|
||||
Argument.withSchema(AuthSessionId),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Revoke an active session."),
|
||||
Command.withHandler((flags) =>
|
||||
runWithAuthControlPlane(flags, (authControlPlane) =>
|
||||
Effect.gen(function* () {
|
||||
const revoked = yield* authControlPlane.revokeSession(flags.sessionId);
|
||||
yield* Console.log(
|
||||
revoked
|
||||
? `Revoked session ${flags.sessionId}.\n`
|
||||
: `No active session found for ${flags.sessionId}.\n`,
|
||||
);
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const sessionCommand = Command.make("session").pipe(
|
||||
Command.withDescription("Manage bearer sessions."),
|
||||
Command.withSubcommands([sessionIssueCommand, sessionListCommand, sessionRevokeCommand]),
|
||||
);
|
||||
|
||||
export const authCommand = Command.make("auth").pipe(
|
||||
Command.withDescription("Manage the local auth control plane for headless deployments."),
|
||||
Command.withSubcommands([pairingCommand, sessionCommand]),
|
||||
);
|
||||
@@ -1,490 +0,0 @@
|
||||
import { NetService } from "@t3tools/shared/Net";
|
||||
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
|
||||
import {
|
||||
Config,
|
||||
Duration,
|
||||
Effect,
|
||||
FileSystem,
|
||||
LogLevel,
|
||||
Option,
|
||||
Path,
|
||||
Schema,
|
||||
SchemaIssue,
|
||||
SchemaTransformation,
|
||||
} from "effect";
|
||||
import { Argument, Flag } from "effect/unstable/cli";
|
||||
|
||||
import { readBootstrapEnvelope } from "../bootstrap.ts";
|
||||
import {
|
||||
DEFAULT_PORT,
|
||||
deriveServerPaths,
|
||||
ensureServerDirectories,
|
||||
resolveStaticDir,
|
||||
RuntimeMode,
|
||||
type ServerConfigShape,
|
||||
type StartupPresentation,
|
||||
} from "../config.ts";
|
||||
import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
|
||||
|
||||
export const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
|
||||
|
||||
const BootstrapEnvelopeSchema = Schema.Struct({
|
||||
mode: Schema.optional(RuntimeMode),
|
||||
port: Schema.optional(PortSchema),
|
||||
host: Schema.optional(Schema.String),
|
||||
t3Home: Schema.optional(Schema.String),
|
||||
devUrl: Schema.optional(Schema.URLFromString),
|
||||
noBrowser: Schema.optional(Schema.Boolean),
|
||||
desktopBootstrapToken: Schema.optional(Schema.String),
|
||||
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
|
||||
logWebSocketEvents: Schema.optional(Schema.Boolean),
|
||||
tailscaleServeEnabled: Schema.optional(Schema.Boolean),
|
||||
tailscaleServePort: Schema.optional(PortSchema),
|
||||
otlpTracesUrl: Schema.optional(Schema.String),
|
||||
otlpMetricsUrl: Schema.optional(Schema.String),
|
||||
});
|
||||
|
||||
export const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
|
||||
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const hostFlag = Flag.string("host").pipe(
|
||||
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const baseDirFlag = Flag.string("base-dir").pipe(
|
||||
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const devUrlFlag = Flag.string("dev-url").pipe(
|
||||
Flag.withSchema(Schema.URLFromString),
|
||||
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.withDescription("Disable automatic browser opening."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
|
||||
Flag.withSchema(Schema.Int),
|
||||
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
|
||||
Flag.optional,
|
||||
);
|
||||
export const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
|
||||
Flag.withDescription(
|
||||
"Create a project for the current working directory on startup when missing.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
export const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
|
||||
Flag.withDescription(
|
||||
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
|
||||
),
|
||||
Flag.withAlias("log-ws-events"),
|
||||
Flag.optional,
|
||||
);
|
||||
export const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
|
||||
Flag.withDescription(
|
||||
"Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
|
||||
),
|
||||
Flag.optional,
|
||||
);
|
||||
export const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
const EnvServerConfig = Config.all({
|
||||
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
|
||||
traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
|
||||
traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
|
||||
traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
|
||||
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
|
||||
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
|
||||
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
|
||||
Config.withDefault(10_000),
|
||||
),
|
||||
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
|
||||
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
|
||||
Config.option,
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
});
|
||||
|
||||
export interface CliServerFlags {
|
||||
readonly mode: Option.Option<RuntimeMode>;
|
||||
readonly port: Option.Option<number>;
|
||||
readonly host: Option.Option<string>;
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly cwd: Option.Option<string>;
|
||||
readonly devUrl: Option.Option<URL>;
|
||||
readonly noBrowser: Option.Option<boolean>;
|
||||
readonly bootstrapFd: Option.Option<number>;
|
||||
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
|
||||
readonly logWebSocketEvents: Option.Option<boolean>;
|
||||
readonly tailscaleServeEnabled: Option.Option<boolean>;
|
||||
readonly tailscaleServePort: Option.Option<number>;
|
||||
}
|
||||
|
||||
export interface CliAuthLocationFlags {
|
||||
readonly baseDir: Option.Option<string>;
|
||||
readonly devUrl?: Option.Option<URL>;
|
||||
}
|
||||
|
||||
export const sharedServerLocationFlags = {
|
||||
baseDir: baseDirFlag,
|
||||
devUrl: devUrlFlag,
|
||||
} as const;
|
||||
|
||||
export const projectLocationFlags = {
|
||||
baseDir: baseDirFlag,
|
||||
} as const;
|
||||
|
||||
export const sharedServerCommandFlags = {
|
||||
mode: modeFlag,
|
||||
port: portFlag,
|
||||
host: hostFlag,
|
||||
baseDir: baseDirFlag,
|
||||
cwd: Argument.string("cwd").pipe(
|
||||
Argument.withDescription(
|
||||
"Working directory for provider sessions (defaults to the current directory).",
|
||||
),
|
||||
Argument.optional,
|
||||
),
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
tailscaleServeEnabled: tailscaleServeFlag,
|
||||
tailscaleServePort: tailscaleServePortFlag,
|
||||
} as const;
|
||||
|
||||
export const authLocationFlags = sharedServerLocationFlags;
|
||||
|
||||
const resolveOptionPrecedence = <Value>(
|
||||
...values: ReadonlyArray<Option.Option<Value>>
|
||||
): Option.Option<Value> => Option.firstSomeOf(values);
|
||||
|
||||
const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
|
||||
if (!exists) {
|
||||
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
|
||||
}
|
||||
|
||||
const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
|
||||
return parsePersistedServerObservabilitySettings(raw);
|
||||
});
|
||||
|
||||
export const resolveServerConfig = (
|
||||
flags: CliServerFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
options?: {
|
||||
readonly startupPresentation?: StartupPresentation;
|
||||
readonly forceAutoBootstrapProjectFromCwd?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const { findAvailablePort } = yield* NetService;
|
||||
const path = yield* Path.Path;
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const env = yield* EnvServerConfig;
|
||||
const normalizedFlags = {
|
||||
mode: flags.mode ?? Option.none(),
|
||||
port: flags.port ?? Option.none(),
|
||||
host: flags.host ?? Option.none(),
|
||||
baseDir: flags.baseDir ?? Option.none(),
|
||||
cwd: flags.cwd ?? Option.none(),
|
||||
devUrl: flags.devUrl ?? Option.none(),
|
||||
noBrowser: flags.noBrowser ?? Option.none(),
|
||||
bootstrapFd: flags.bootstrapFd ?? Option.none(),
|
||||
autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
|
||||
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
|
||||
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
|
||||
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
|
||||
} satisfies CliServerFlags;
|
||||
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
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),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.fromUndefinedOr(bootstrap?.port),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
);
|
||||
const devUrl = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.devUrl,
|
||||
Option.fromUndefinedOr(env.devUrl),
|
||||
Option.fromUndefinedOr(bootstrap?.devUrl),
|
||||
),
|
||||
() => undefined,
|
||||
);
|
||||
const baseDir = yield* resolveBaseDir(
|
||||
Option.getOrUndefined(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.baseDir,
|
||||
Option.fromUndefinedOr(env.t3Home),
|
||||
Option.fromUndefinedOr(bootstrap?.t3Home),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
|
||||
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
|
||||
yield* fs.makeDirectory(cwd, { recursive: true });
|
||||
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
|
||||
yield* ensureServerDirectories(derivedPaths);
|
||||
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
|
||||
derivedPaths.settingsPath,
|
||||
);
|
||||
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),
|
||||
),
|
||||
() => 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),
|
||||
),
|
||||
() => mode === "web",
|
||||
);
|
||||
const logWebSocketEvents = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.logWebSocketEvents,
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.fromUndefinedOr(bootstrap?.logWebSocketEvents),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
);
|
||||
const tailscaleServeEnabled = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.tailscaleServeEnabled,
|
||||
Option.fromUndefinedOr(env.tailscaleServeEnabled),
|
||||
Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
|
||||
),
|
||||
() => false,
|
||||
);
|
||||
const tailscaleServePort = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.tailscaleServePort,
|
||||
Option.fromUndefinedOr(env.tailscaleServePort),
|
||||
Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
|
||||
),
|
||||
() => 443,
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
normalizedFlags.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.fromUndefinedOr(bootstrap?.host),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
logLevel,
|
||||
traceMinLevel: env.traceMinLevel,
|
||||
traceTimingEnabled: env.traceTimingEnabled,
|
||||
traceBatchWindowMs: env.traceBatchWindowMs,
|
||||
traceMaxBytes: env.traceMaxBytes,
|
||||
traceMaxFiles: env.traceMaxFiles,
|
||||
otlpTracesUrl:
|
||||
env.otlpTracesUrl ??
|
||||
bootstrap?.otlpTracesUrl ??
|
||||
persistedObservabilitySettings.otlpTracesUrl,
|
||||
otlpMetricsUrl:
|
||||
env.otlpMetricsUrl ??
|
||||
bootstrap?.otlpMetricsUrl ??
|
||||
persistedObservabilitySettings.otlpMetricsUrl,
|
||||
otlpExportIntervalMs: env.otlpExportIntervalMs,
|
||||
otlpServiceName: env.otlpServiceName,
|
||||
mode,
|
||||
port,
|
||||
cwd,
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
serverTracePath,
|
||||
host,
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
startupPresentation,
|
||||
desktopBootstrapToken,
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
tailscaleServeEnabled,
|
||||
tailscaleServePort,
|
||||
};
|
||||
|
||||
return config;
|
||||
});
|
||||
|
||||
export const resolveCliAuthConfig = (
|
||||
flags: CliAuthLocationFlags,
|
||||
cliLogLevel: Option.Option<LogLevel.LogLevel>,
|
||||
) =>
|
||||
resolveServerConfig(
|
||||
{
|
||||
mode: Option.none(),
|
||||
port: Option.none(),
|
||||
host: Option.none(),
|
||||
baseDir: flags.baseDir,
|
||||
cwd: Option.none(),
|
||||
devUrl: flags.devUrl ?? Option.none(),
|
||||
noBrowser: Option.none(),
|
||||
bootstrapFd: Option.none(),
|
||||
autoBootstrapProjectFromCwd: Option.none(),
|
||||
logWebSocketEvents: Option.none(),
|
||||
tailscaleServeEnabled: Option.none(),
|
||||
tailscaleServePort: Option.none(),
|
||||
},
|
||||
cliLogLevel,
|
||||
);
|
||||
|
||||
const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
|
||||
|
||||
const parseDurationInput = (value: string): Duration.Duration | null => {
|
||||
const trimmed = value.trim();
|
||||
if (trimmed.length === 0) return null;
|
||||
|
||||
const shorthand = DurationShorthandPattern.exec(trimmed);
|
||||
const normalizedInput = shorthand?.groups
|
||||
? (() => {
|
||||
const amountText = shorthand.groups.value;
|
||||
const unitText = shorthand.groups.unit;
|
||||
if (typeof amountText !== "string" || typeof unitText !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const amount = Number.parseInt(amountText, 10);
|
||||
if (!Number.isFinite(amount)) return null;
|
||||
|
||||
switch (unitText.toLowerCase()) {
|
||||
case "ms":
|
||||
return `${amount} millis`;
|
||||
case "s":
|
||||
return `${amount} seconds`;
|
||||
case "m":
|
||||
return `${amount} minutes`;
|
||||
case "h":
|
||||
return `${amount} hours`;
|
||||
case "d":
|
||||
return `${amount} days`;
|
||||
case "w":
|
||||
return `${amount} weeks`;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
})()
|
||||
: (trimmed as Duration.Input);
|
||||
|
||||
if (normalizedInput === null) return null;
|
||||
|
||||
const decoded = Duration.fromInput(normalizedInput as Duration.Input);
|
||||
return Option.isSome(decoded) ? decoded.value : null;
|
||||
};
|
||||
|
||||
export const DurationFromString = Schema.String.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.Duration,
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (value) => {
|
||||
const duration = parseDurationInput(value);
|
||||
if (duration !== null) {
|
||||
return Effect.succeed(duration);
|
||||
}
|
||||
return Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
|
||||
}),
|
||||
);
|
||||
},
|
||||
encode: (duration) => Effect.succeed(Duration.format(duration)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -1,434 +0,0 @@
|
||||
import {
|
||||
CommandId,
|
||||
OrchestrationReadModel,
|
||||
ProjectId,
|
||||
type ClientOrchestrationCommand,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Console,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
References,
|
||||
Schema,
|
||||
} from "effect";
|
||||
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
|
||||
import {
|
||||
FetchHttpClient,
|
||||
HttpClient,
|
||||
HttpClientRequest,
|
||||
HttpClientResponse,
|
||||
} from "effect/unstable/http";
|
||||
|
||||
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
|
||||
import { AuthControlPlane } from "../auth/Services/AuthControlPlane.ts";
|
||||
import type { AuthControlPlaneShape } from "../auth/Services/AuthControlPlane.ts";
|
||||
import { ServerConfig, type ServerConfigShape } from "../config.ts";
|
||||
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
|
||||
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
|
||||
import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
|
||||
import { layerConfig as SqlitePersistenceLayerLive } from "../persistence/Layers/Sqlite.ts";
|
||||
import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts";
|
||||
import { getAutoBootstrapDefaultModelSelection } from "../serverRuntimeStartup.ts";
|
||||
import {
|
||||
clearPersistedServerRuntimeState,
|
||||
readPersistedServerRuntimeState,
|
||||
} from "../serverRuntimeState.ts";
|
||||
import { WorkspacePathsLive } from "../workspace/Layers/WorkspacePaths.ts";
|
||||
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths.ts";
|
||||
import { type CliAuthLocationFlags, projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
|
||||
|
||||
type ProjectMutationTarget = {
|
||||
readonly id: ProjectId;
|
||||
readonly title: string;
|
||||
readonly workspaceRoot: string;
|
||||
};
|
||||
|
||||
type ProjectCommandExecutionMode = "live" | "offline";
|
||||
type ProjectCliDispatchCommand = Extract<
|
||||
ClientOrchestrationCommand,
|
||||
{ type: "project.create" | "project.meta.update" | "project.delete" }
|
||||
>;
|
||||
|
||||
const ProjectCliRuntimeLive = Layer.mergeAll(
|
||||
WorkspacePathsLive,
|
||||
OrchestrationLayerLive.pipe(
|
||||
Layer.provideMerge(RepositoryIdentityResolverLive),
|
||||
Layer.provideMerge(SqlitePersistenceLayerLive),
|
||||
),
|
||||
);
|
||||
|
||||
const PROJECT_CLI_LIVE_SERVER_TIMEOUT = Duration.seconds(1);
|
||||
const OrchestrationHttpErrorResponse = Schema.Struct({
|
||||
error: Schema.String,
|
||||
});
|
||||
|
||||
const withProjectCliSessionToken = <A, E, R>(
|
||||
authControlPlane: AuthControlPlaneShape,
|
||||
run: (token: string) => Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.acquireUseRelease(
|
||||
authControlPlane.issueSession({
|
||||
role: "owner",
|
||||
label: "t3 project cli",
|
||||
}),
|
||||
(issued) => run(issued.token),
|
||||
(issued) => authControlPlane.revokeSession(issued.sessionId).pipe(Effect.ignore({ log: true })),
|
||||
);
|
||||
|
||||
const withProjectCliLiveServerTimeout = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(Effect.timeout(PROJECT_CLI_LIVE_SERVER_TIMEOUT));
|
||||
|
||||
const runLiveServerRequest = <A, E extends Error, R>(
|
||||
request: HttpClientRequest.HttpClientRequest,
|
||||
handle: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<A, E, R>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const httpClient = yield* HttpClient.HttpClient;
|
||||
const response = yield* httpClient.execute(request);
|
||||
return yield* handle(response);
|
||||
}).pipe(withProjectCliLiveServerTimeout);
|
||||
|
||||
const decodeOrchestrationReadModelResponse = (response: HttpClientResponse.HttpClientResponse) =>
|
||||
HttpClientResponse.schemaBodyJson(OrchestrationReadModel)(response);
|
||||
|
||||
const readErrorMessageFromResponse = (response: HttpClientResponse.HttpClientResponse) =>
|
||||
HttpClientResponse.schemaBodyJson(OrchestrationHttpErrorResponse)(response).pipe(
|
||||
Effect.map((body) => body.error),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
Effect.map((body) => {
|
||||
if (typeof body === "string" && body.trim().length > 0) {
|
||||
return body;
|
||||
}
|
||||
return `Server request failed with status ${response.status}.`;
|
||||
}),
|
||||
);
|
||||
|
||||
const normalizeWorkspaceRootForProjectCommand = Effect.fn(
|
||||
"normalizeWorkspaceRootForProjectCommand",
|
||||
)(function* (workspaceRoot: string) {
|
||||
const workspacePaths = yield* WorkspacePaths;
|
||||
return yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot);
|
||||
});
|
||||
|
||||
const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
|
||||
workspaceRoot: string,
|
||||
explicitTitle?: string,
|
||||
) {
|
||||
if (explicitTitle !== undefined) {
|
||||
const trimmed = explicitTitle.trim();
|
||||
if (trimmed.length > 0) {
|
||||
return trimmed;
|
||||
}
|
||||
return yield* Effect.fail(new Error("Project title cannot be empty."));
|
||||
}
|
||||
|
||||
const path = yield* Path.Path;
|
||||
const basename = path.basename(workspaceRoot).trim();
|
||||
return basename.length > 0 ? basename : "project";
|
||||
});
|
||||
|
||||
const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly identifier: string;
|
||||
}) {
|
||||
const trimmedIdentifier = input.identifier.trim();
|
||||
if (trimmedIdentifier.length === 0) {
|
||||
return yield* Effect.fail(new Error("Project identifier cannot be empty."));
|
||||
}
|
||||
|
||||
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
|
||||
const exactIdMatch = activeProjects.find((project) => project.id === trimmedIdentifier);
|
||||
if (exactIdMatch) {
|
||||
return {
|
||||
id: exactIdMatch.id,
|
||||
title: exactIdMatch.title,
|
||||
workspaceRoot: exactIdMatch.workspaceRoot,
|
||||
} satisfies ProjectMutationTarget;
|
||||
}
|
||||
|
||||
const normalizedWorkspaceRootResult = yield* Effect.exit(
|
||||
normalizeWorkspaceRootForProjectCommand(trimmedIdentifier),
|
||||
);
|
||||
const normalizedWorkspaceRoot = Exit.isSuccess(normalizedWorkspaceRootResult)
|
||||
? normalizedWorkspaceRootResult.value
|
||||
: null;
|
||||
|
||||
const exactWorkspaceMatch =
|
||||
normalizedWorkspaceRoot === null
|
||||
? undefined
|
||||
: activeProjects.find((project) => project.workspaceRoot === normalizedWorkspaceRoot);
|
||||
|
||||
const resolved = exactWorkspaceMatch;
|
||||
if (!resolved) {
|
||||
return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
|
||||
}
|
||||
|
||||
return {
|
||||
id: resolved.id,
|
||||
title: resolved.title,
|
||||
workspaceRoot: resolved.workspaceRoot,
|
||||
} satisfies ProjectMutationTarget;
|
||||
});
|
||||
|
||||
const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
|
||||
runLiveServerRequest(
|
||||
HttpClientRequest.get(`${origin}/api/orchestration/snapshot`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(bearerToken),
|
||||
),
|
||||
HttpClientResponse.matchStatus({
|
||||
"2xx": decodeOrchestrationReadModelResponse,
|
||||
orElse: (response) =>
|
||||
readErrorMessageFromResponse(response).pipe(
|
||||
Effect.flatMap((message) => Effect.fail(new Error(message))),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
const dispatchLiveOrchestrationCommand = (
|
||||
origin: string,
|
||||
bearerToken: string,
|
||||
command: ProjectCliDispatchCommand,
|
||||
) =>
|
||||
HttpClientRequest.post(`${origin}/api/orchestration/dispatch`).pipe(
|
||||
HttpClientRequest.acceptJson,
|
||||
HttpClientRequest.bearerToken(bearerToken),
|
||||
HttpClientRequest.bodyJson(command),
|
||||
Effect.flatMap((request) =>
|
||||
runLiveServerRequest(
|
||||
request,
|
||||
HttpClientResponse.matchStatus({
|
||||
"2xx": () => Effect.void,
|
||||
orElse: (response) =>
|
||||
readErrorMessageFromResponse(response).pipe(
|
||||
Effect.flatMap((message) => Effect.fail(new Error(message))),
|
||||
),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const getOfflineSnapshot = Effect.fn("getOfflineSnapshot")(function* () {
|
||||
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
|
||||
return yield* projectionSnapshotQuery.getSnapshot();
|
||||
});
|
||||
|
||||
const tryResolveLiveProjectExecutionMode = Effect.fn("tryResolveLiveProjectExecutionMode")(
|
||||
function* (authControlPlane: AuthControlPlaneShape, config: ServerConfigShape) {
|
||||
const runtimeState = yield* readPersistedServerRuntimeState(config.serverRuntimeStatePath);
|
||||
if (Option.isNone(runtimeState)) {
|
||||
return Option.none<{ readonly origin: string }>();
|
||||
}
|
||||
|
||||
const attempt = withProjectCliSessionToken(authControlPlane, (token) =>
|
||||
fetchLiveOrchestrationSnapshot(runtimeState.value.origin, token).pipe(
|
||||
Effect.as({
|
||||
origin: runtimeState.value.origin,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const attempted = yield* Effect.exit(attempt);
|
||||
if (Exit.isSuccess(attempted)) {
|
||||
return Option.some(attempted.value);
|
||||
}
|
||||
|
||||
yield* clearPersistedServerRuntimeState(config.serverRuntimeStatePath);
|
||||
return Option.none<{ readonly origin: string }>();
|
||||
},
|
||||
);
|
||||
|
||||
const runProjectMutation = Effect.fn("runProjectMutation")(function* (
|
||||
flags: CliAuthLocationFlags,
|
||||
run: (input: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
readonly mode: ProjectCommandExecutionMode;
|
||||
}) => Effect.Effect<
|
||||
string,
|
||||
Error,
|
||||
FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | WorkspacePaths
|
||||
>,
|
||||
) {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveCliAuthConfig(flags, logLevel);
|
||||
const minimumLogLevel = config.logLevel;
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const authControlPlane = yield* AuthControlPlane;
|
||||
const liveMode = yield* tryResolveLiveProjectExecutionMode(authControlPlane, config);
|
||||
|
||||
if (Option.isSome(liveMode)) {
|
||||
return yield* withProjectCliSessionToken(authControlPlane, (token) =>
|
||||
Effect.gen(function* () {
|
||||
const snapshot = yield* fetchLiveOrchestrationSnapshot(liveMode.value.origin, token);
|
||||
const output = yield* run({
|
||||
snapshot,
|
||||
dispatch: (command) =>
|
||||
dispatchLiveOrchestrationCommand(liveMode.value.origin, token, command),
|
||||
mode: "live",
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const offlineRuntimeLayer = ProjectCliRuntimeLive.pipe(
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
);
|
||||
|
||||
return yield* Effect.gen(function* () {
|
||||
const snapshot = yield* getOfflineSnapshot();
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const output = yield* run({
|
||||
snapshot,
|
||||
dispatch: (command) => orchestrationEngine.dispatch(command),
|
||||
mode: "offline",
|
||||
});
|
||||
yield* Console.log(output);
|
||||
}).pipe(Effect.provide(offlineRuntimeLayer));
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
Layer.mergeAll(AuthControlPlaneRuntimeLive, WorkspacePathsLive).pipe(
|
||||
Layer.provideMerge(FetchHttpClient.layer),
|
||||
Layer.provide(Layer.succeed(ServerConfig, config)),
|
||||
Layer.provide(Layer.succeed(References.MinimumLogLevel, minimumLogLevel)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const projectAddCommand = Command.make("add", {
|
||||
...projectLocationFlags,
|
||||
workspaceRoot: Argument.string("path").pipe(
|
||||
Argument.withDescription("Workspace root to add as a project."),
|
||||
),
|
||||
title: Flag.string("title").pipe(Flag.withDescription("Optional project title."), Flag.optional),
|
||||
}).pipe(
|
||||
Command.withDescription("Add a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectAddMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const workspaceRoot = yield* normalizeWorkspaceRootForProjectCommand(flags.workspaceRoot);
|
||||
const existingProject = snapshot.projects.find(
|
||||
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
|
||||
);
|
||||
if (existingProject) {
|
||||
return yield* Effect.fail(
|
||||
new Error(`An active project already exists for '${workspaceRoot}'.`),
|
||||
);
|
||||
}
|
||||
|
||||
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
|
||||
const projectId = ProjectId.make(crypto.randomUUID());
|
||||
yield* dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId,
|
||||
title,
|
||||
workspaceRoot,
|
||||
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const projectRemoveCommand = Command.make("remove", {
|
||||
...projectLocationFlags,
|
||||
project: Argument.string("project").pipe(
|
||||
Argument.withDescription("Project id or workspace root to remove."),
|
||||
),
|
||||
}).pipe(
|
||||
Command.withDescription("Remove a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectRemoveMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const project = yield* findActiveProjectTarget({
|
||||
snapshot,
|
||||
identifier: flags.project,
|
||||
});
|
||||
yield* dispatch({
|
||||
type: "project.delete",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
});
|
||||
return `Removed project ${project.id} (${project.title}).`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const projectRenameCommand = Command.make("rename", {
|
||||
...projectLocationFlags,
|
||||
project: Argument.string("project").pipe(
|
||||
Argument.withDescription("Project id or workspace root to rename."),
|
||||
),
|
||||
title: Argument.string("title").pipe(Argument.withDescription("New project title.")),
|
||||
}).pipe(
|
||||
Command.withDescription("Rename a project."),
|
||||
Command.withHandler((flags) =>
|
||||
runProjectMutation(
|
||||
flags,
|
||||
Effect.fn("projectRenameMutation")(function* ({
|
||||
snapshot,
|
||||
dispatch,
|
||||
}: {
|
||||
readonly snapshot: OrchestrationReadModel;
|
||||
readonly dispatch: (
|
||||
command: ProjectCliDispatchCommand,
|
||||
) => Effect.Effect<void, Error, FileSystem.FileSystem | HttpClient.HttpClient | Path.Path>;
|
||||
}) {
|
||||
const project = yield* findActiveProjectTarget({
|
||||
snapshot,
|
||||
identifier: flags.project,
|
||||
});
|
||||
const nextTitle = yield* resolveProjectTitle(project.workspaceRoot, flags.title);
|
||||
if (nextTitle === project.title) {
|
||||
return `Project ${project.id} is already named ${nextTitle}.`;
|
||||
}
|
||||
|
||||
yield* dispatch({
|
||||
type: "project.meta.update",
|
||||
commandId: CommandId.make(crypto.randomUUID()),
|
||||
projectId: project.id,
|
||||
title: nextTitle,
|
||||
});
|
||||
return `Renamed project ${project.id} to ${nextTitle}.`;
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
export const projectCommand = Command.make("project").pipe(
|
||||
Command.withDescription("Manage projects."),
|
||||
Command.withSubcommands([projectAddCommand, projectRemoveCommand, projectRenameCommand]),
|
||||
);
|
||||
@@ -1,36 +0,0 @@
|
||||
import { Effect } from "effect";
|
||||
import { Command, GlobalFlag } from "effect/unstable/cli";
|
||||
|
||||
import { ServerConfig, type StartupPresentation } from "../config.ts";
|
||||
import { runServer } from "../server.ts";
|
||||
import { type CliServerFlags, resolveServerConfig, sharedServerCommandFlags } from "./config.ts";
|
||||
|
||||
export const runServerCommand = (
|
||||
flags: CliServerFlags,
|
||||
options?: {
|
||||
readonly startupPresentation?: StartupPresentation;
|
||||
readonly forceAutoBootstrapProjectFromCwd?: boolean;
|
||||
},
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const logLevel = yield* GlobalFlag.LogLevel;
|
||||
const config = yield* resolveServerConfig(flags, logLevel, options);
|
||||
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
|
||||
});
|
||||
|
||||
export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription("Run the T3 Code server."),
|
||||
Command.withHandler((flags) => runServerCommand(flags)),
|
||||
);
|
||||
|
||||
export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
|
||||
Command.withDescription(
|
||||
"Run the T3 Code server without opening a browser and print headless pairing details.",
|
||||
),
|
||||
Command.withHandler((flags) =>
|
||||
runServerCommand(flags, {
|
||||
startupPresentation: "headless",
|
||||
forceAutoBootstrapProjectFromCwd: false,
|
||||
}),
|
||||
),
|
||||
);
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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;
|
||||
@@ -65,8 +64,6 @@ export interface ServerConfigShape extends ServerDerivedPaths {
|
||||
readonly desktopBootstrapToken: string | undefined;
|
||||
readonly autoBootstrapProjectFromCwd: boolean;
|
||||
readonly logWebSocketEvents: boolean;
|
||||
readonly tailscaleServeEnabled: boolean;
|
||||
readonly tailscaleServePort: number;
|
||||
}
|
||||
|
||||
export const deriveServerPaths = Effect.fn(function* (
|
||||
@@ -79,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,
|
||||
@@ -115,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 }),
|
||||
],
|
||||
@@ -160,8 +154,6 @@ export class ServerConfig extends Context.Service<ServerConfig, ServerConfigShap
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Sink from "effect/Sink";
|
||||
import * as Stream from "effect/Stream";
|
||||
import { ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
function mockHandle(result: {
|
||||
readonly stdout?: string;
|
||||
readonly stderr?: string;
|
||||
readonly code?: number;
|
||||
}) {
|
||||
return ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(1),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
stdin: Sink.drain,
|
||||
stdout: Stream.make(encoder.encode(result.stdout ?? "")),
|
||||
stderr: Stream.make(encoder.encode(result.stderr ?? "")),
|
||||
all: Stream.empty,
|
||||
getInputFd: () => Sink.drain,
|
||||
getOutputFd: () => Stream.empty,
|
||||
});
|
||||
}
|
||||
|
||||
describe("ProcessDiagnostics", () => {
|
||||
it.effect("parses POSIX ps rows with full commands", () =>
|
||||
Effect.sync(() => {
|
||||
const rows = ProcessDiagnostics.parsePosixProcessRows(
|
||||
[
|
||||
" 10 1 10 Ss 0.0 1024 01:02.03 /usr/bin/node server.js",
|
||||
" 11 10 10 S+ 12.5 20480 00:04 codex app-server --config /tmp/one two",
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
expect(rows).toEqual([
|
||||
{
|
||||
pid: 10,
|
||||
ppid: 1,
|
||||
pgid: 10,
|
||||
status: "Ss",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1024 * 1024,
|
||||
elapsed: "01:02.03",
|
||||
command: "/usr/bin/node server.js",
|
||||
},
|
||||
{
|
||||
pid: 11,
|
||||
ppid: 10,
|
||||
pgid: 10,
|
||||
status: "S+",
|
||||
cpuPercent: 12.5,
|
||||
rssBytes: 20480 * 1024,
|
||||
elapsed: "00:04",
|
||||
command: "codex app-server --config /tmp/one two",
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("aggregates only descendants of the server process", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 100,
|
||||
ppid: 1,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 1_000,
|
||||
elapsed: "01:00",
|
||||
command: "t3 server",
|
||||
},
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 1.5,
|
||||
rssBytes: 2_000,
|
||||
elapsed: "00:20",
|
||||
command: "codex app-server",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 3.25,
|
||||
rssBytes: 4_000,
|
||||
elapsed: "00:05",
|
||||
command: "git status",
|
||||
},
|
||||
{
|
||||
pid: 200,
|
||||
ppid: 1,
|
||||
pgid: 200,
|
||||
status: "S",
|
||||
cpuPercent: 99,
|
||||
rssBytes: 8_000,
|
||||
elapsed: "00:01",
|
||||
command: "unrelated",
|
||||
},
|
||||
{
|
||||
pid: 201,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "R",
|
||||
cpuPercent: 9,
|
||||
rssBytes: 9_000,
|
||||
elapsed: "00:00",
|
||||
command: "ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.serverPid).toBe(100);
|
||||
expect(DateTime.formatIso(diagnostics.readAt)).toBe("2026-05-05T10:00:00.000Z");
|
||||
expect(diagnostics.processCount).toBe(2);
|
||||
expect(diagnostics.totalRssBytes).toBe(6_000);
|
||||
expect(diagnostics.totalCpuPercent).toBe(4.75);
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102]);
|
||||
expect(diagnostics.processes.map((process) => process.depth)).toEqual([0, 1]);
|
||||
expect(Option.getOrNull(diagnostics.processes[0]!.pgid)).toBe(100);
|
||||
expect(diagnostics.processes[0]?.childPids).toEqual([102]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves ascending sibling order for nested descendants", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
|
||||
serverPid: 100,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
rows: [
|
||||
{
|
||||
pid: 101,
|
||||
ppid: 100,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "agent",
|
||||
},
|
||||
{
|
||||
pid: 103,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-b",
|
||||
},
|
||||
{
|
||||
pid: 102,
|
||||
ppid: 101,
|
||||
pgid: 100,
|
||||
status: "S",
|
||||
cpuPercent: 0,
|
||||
rssBytes: 100,
|
||||
elapsed: "00:10",
|
||||
command: "child-a",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([101, 102, 103]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("queries processes through the ChildProcessSpawner service", () =>
|
||||
Effect.gen(function* () {
|
||||
const commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }> =
|
||||
[];
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make((command) => {
|
||||
const childProcess = command as unknown as {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
};
|
||||
commands.push({ command: childProcess.command, args: childProcess.args });
|
||||
return Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} S 1.5 2048 00:04 agent`,
|
||||
].join("\n"),
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const diagnostics = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.read),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(diagnostics.processes.map((process) => process.pid)).toEqual([4242]);
|
||||
expect(commands).toEqual([
|
||||
{
|
||||
command: "ps",
|
||||
args: ["-axo", "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command="],
|
||||
},
|
||||
]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not allow signaling the diagnostics query process", () =>
|
||||
Effect.gen(function* () {
|
||||
const spawnerLayer = Layer.succeed(
|
||||
ChildProcessSpawner.ChildProcessSpawner,
|
||||
ChildProcessSpawner.make(() =>
|
||||
Effect.succeed(
|
||||
mockHandle({
|
||||
stdout: [
|
||||
` ${process.pid} 1 ${process.pid} Ss 0.0 1024 01:02.03 t3 server`,
|
||||
` 4242 ${process.pid} ${process.pid} R 1.5 2048 00:00 ps -axo pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=`,
|
||||
].join("\n"),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
const layer = ProcessDiagnostics.layer.pipe(Layer.provide(spawnerLayer));
|
||||
|
||||
const result = yield* Effect.service(ProcessDiagnostics.ProcessDiagnostics).pipe(
|
||||
Effect.flatMap((pd) => pd.signal({ pid: 4242, signal: "SIGINT" })),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
|
||||
expect(result).toEqual({
|
||||
pid: 4242,
|
||||
signal: "SIGINT",
|
||||
signaled: false,
|
||||
message: Option.some("Process 4242 is not a live descendant of the T3 server."),
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,461 +0,0 @@
|
||||
import type {
|
||||
ServerProcessDiagnosticsEntry,
|
||||
ServerProcessDiagnosticsResult,
|
||||
ServerProcessSignal,
|
||||
ServerSignalProcessResult,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Duration from "effect/Duration";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
|
||||
|
||||
interface ProcessRow {
|
||||
readonly pid: number;
|
||||
readonly ppid: number;
|
||||
readonly pgid: number | null;
|
||||
readonly status: string;
|
||||
readonly cpuPercent: number;
|
||||
readonly rssBytes: number;
|
||||
readonly elapsed: string;
|
||||
readonly command: string;
|
||||
}
|
||||
|
||||
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
|
||||
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
|
||||
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export interface ProcessDiagnosticsShape {
|
||||
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
|
||||
readonly signal: (input: {
|
||||
readonly pid: number;
|
||||
readonly signal: ServerProcessSignal;
|
||||
}) => Effect.Effect<ServerSignalProcessResult>;
|
||||
}
|
||||
|
||||
export class ProcessDiagnostics extends Context.Service<
|
||||
ProcessDiagnostics,
|
||||
ProcessDiagnosticsShape
|
||||
>()("t3/diagnostics/ProcessDiagnostics") {}
|
||||
|
||||
class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnosticsError>()(
|
||||
"ProcessDiagnosticsError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
|
||||
return new ProcessDiagnosticsError({
|
||||
message,
|
||||
...(cause === undefined ? {} : { cause }),
|
||||
});
|
||||
}
|
||||
|
||||
function parsePositiveInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNonNegativeInt(value: string): number | null {
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isInteger(parsed) && parsed >= 0 ? parsed : null;
|
||||
}
|
||||
|
||||
function parseNumber(value: string): number | null {
|
||||
const parsed = Number.parseFloat(value);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
const rows: ProcessRow[] = [];
|
||||
const rowPattern =
|
||||
/^\s*(\d+)\s+(\d+)\s+(-?\d+)\s+(\S+)\s+([+-]?(?:\d+\.?\d*|\.\d+))\s+(\d+)\s+(\S+)\s+(.+)$/;
|
||||
|
||||
for (const line of output.split(/\r?\n/)) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
const match = rowPattern.exec(line);
|
||||
if (!match) continue;
|
||||
|
||||
const pidText = match[1];
|
||||
const ppidText = match[2];
|
||||
const pgidText = match[3];
|
||||
const status = match[4];
|
||||
const cpuText = match[5];
|
||||
const rssText = match[6];
|
||||
const elapsed = match[7];
|
||||
const command = match[8];
|
||||
if (
|
||||
pidText === undefined ||
|
||||
ppidText === undefined ||
|
||||
pgidText === undefined ||
|
||||
status === undefined ||
|
||||
cpuText === undefined ||
|
||||
rssText === undefined ||
|
||||
elapsed === undefined ||
|
||||
command === undefined
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const pid = parsePositiveInt(pidText);
|
||||
const ppid = parseNonNegativeInt(ppidText);
|
||||
const pgid = Number.parseInt(pgidText, 10);
|
||||
const cpuPercent = parseNumber(cpuText);
|
||||
const rssKiB = parseNonNegativeInt(rssText);
|
||||
if (
|
||||
pid === null ||
|
||||
ppid === null ||
|
||||
!Number.isInteger(pgid) ||
|
||||
cpuPercent === null ||
|
||||
rssKiB === null ||
|
||||
!status ||
|
||||
!elapsed ||
|
||||
!command
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
rows.push({
|
||||
pid,
|
||||
ppid,
|
||||
pgid,
|
||||
status,
|
||||
cpuPercent,
|
||||
rssBytes: rssKiB * 1024,
|
||||
elapsed,
|
||||
command,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
|
||||
if (typeof value !== "object" || value === null) return null;
|
||||
const record = value as Record<string, unknown>;
|
||||
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
|
||||
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
|
||||
const commandLine =
|
||||
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
|
||||
? record.CommandLine
|
||||
: typeof record.Name === "string"
|
||||
? record.Name
|
||||
: null;
|
||||
const workingSet =
|
||||
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
|
||||
? Math.max(0, Math.round(record.WorkingSetSize))
|
||||
: 0;
|
||||
const cpuPercent =
|
||||
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
|
||||
? Math.max(0, record.PercentProcessorTime)
|
||||
: 0;
|
||||
|
||||
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
|
||||
return {
|
||||
pid,
|
||||
ppid,
|
||||
pgid: null,
|
||||
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
|
||||
cpuPercent,
|
||||
rssBytes: workingSet,
|
||||
elapsed: "",
|
||||
command: commandLine,
|
||||
};
|
||||
}
|
||||
|
||||
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
|
||||
if (output.trim().length === 0) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(output) as unknown;
|
||||
const records = Array.isArray(parsed) ? parsed : [parsed];
|
||||
return records.flatMap((record) => {
|
||||
const row = normalizeWindowsProcessRow(record);
|
||||
return row ? [row] : [];
|
||||
});
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function buildDescendantEntries(
|
||||
rows: ReadonlyArray<ProcessRow>,
|
||||
serverPid: number,
|
||||
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
|
||||
const childrenByParent = new Map<number, ProcessRow[]>();
|
||||
for (const row of rows) {
|
||||
const children = childrenByParent.get(row.ppid) ?? [];
|
||||
children.push(row);
|
||||
childrenByParent.set(row.ppid, children);
|
||||
}
|
||||
|
||||
const entries: ServerProcessDiagnosticsEntry[] = [];
|
||||
const visited = new Set<number>();
|
||||
const stack = [...(childrenByParent.get(serverPid) ?? [])]
|
||||
.toSorted((left, right) => left.pid - right.pid)
|
||||
.map((row) => ({ row, depth: 0 }));
|
||||
|
||||
while (stack.length > 0) {
|
||||
const item = stack.shift();
|
||||
if (!item || visited.has(item.row.pid)) continue;
|
||||
visited.add(item.row.pid);
|
||||
|
||||
const children = [...(childrenByParent.get(item.row.pid) ?? [])].toSorted(
|
||||
(left, right) => left.pid - right.pid,
|
||||
);
|
||||
entries.push({
|
||||
pid: item.row.pid,
|
||||
ppid: item.row.ppid,
|
||||
pgid: Option.fromNullishOr(item.row.pgid),
|
||||
status: item.row.status,
|
||||
cpuPercent: item.row.cpuPercent,
|
||||
rssBytes: item.row.rssBytes,
|
||||
elapsed: item.row.elapsed || "n/a",
|
||||
command: item.row.command,
|
||||
depth: item.depth,
|
||||
childPids: children.map((child) => child.pid),
|
||||
});
|
||||
|
||||
stack.unshift(...children.map((row) => ({ row, depth: item.depth + 1 })));
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
|
||||
if (row.ppid !== serverPid) return false;
|
||||
|
||||
const command = row.command.trim();
|
||||
return (
|
||||
/(?:^|[/\\])ps\s+-axo\s+pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=/.test(command) ||
|
||||
(/\bpowershell(?:\.exe)?\b/i.test(command) &&
|
||||
/\bGet-CimInstance\s+Win32_Process\b/i.test(command))
|
||||
);
|
||||
}
|
||||
|
||||
function makeResult(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: string;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
|
||||
const processes = buildDescendantEntries(rows, input.serverPid);
|
||||
const totalRssBytes = processes.reduce((total, process) => total + process.rssBytes, 0);
|
||||
const totalCpuPercent = processes.reduce((total, process) => total + process.cpuPercent, 0);
|
||||
|
||||
return {
|
||||
serverPid: input.serverPid,
|
||||
readAt,
|
||||
processCount: processes.length,
|
||||
totalRssBytes,
|
||||
totalCpuPercent,
|
||||
processes,
|
||||
error: input.error ? Option.some({ message: input.error }) : Option.none(),
|
||||
};
|
||||
}
|
||||
|
||||
interface ProcessOutput {
|
||||
readonly exitCode: number;
|
||||
readonly stdout: string;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
const runProcess = Effect.fn("runProcess")(
|
||||
function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
readonly errorMessage: string;
|
||||
}) {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const child = yield* spawner.spawn(
|
||||
ChildProcess.make(input.command, input.args, {
|
||||
cwd: process.cwd(),
|
||||
shell: process.platform === "win32",
|
||||
}),
|
||||
);
|
||||
const [stdout, stderr, exitCode] = yield* Effect.all(
|
||||
[
|
||||
collectUint8StreamText({
|
||||
stream: child.stdout,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
collectUint8StreamText({
|
||||
stream: child.stderr,
|
||||
maxBytes: PROCESS_QUERY_MAX_OUTPUT_BYTES,
|
||||
truncatedMarker: "\n\n[truncated]",
|
||||
}),
|
||||
child.exitCode,
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
|
||||
return {
|
||||
exitCode,
|
||||
stdout: stdout.text,
|
||||
stderr: stderr.text,
|
||||
} satisfies ProcessOutput;
|
||||
},
|
||||
(effect, input) =>
|
||||
effect.pipe(
|
||||
Effect.scoped,
|
||||
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
|
||||
Effect.flatMap((result) =>
|
||||
Option.match(result, {
|
||||
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
|
||||
onSome: Effect.succeed,
|
||||
}),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
Schema.is(ProcessDiagnosticsError)(cause)
|
||||
? cause
|
||||
: toProcessDiagnosticsError(input.errorMessage, cause),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
function readPosixProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
return runProcess({
|
||||
command: "ps",
|
||||
args: ["-axo", POSIX_PROCESS_QUERY_COMMAND],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(toProcessDiagnosticsError(result.stderr.trim() || "ps failed."))
|
||||
: Effect.succeed(parsePosixProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function readWindowsProcessRows(): Effect.Effect<
|
||||
ReadonlyArray<ProcessRow>,
|
||||
ProcessDiagnosticsError,
|
||||
ChildProcessSpawner.ChildProcessSpawner
|
||||
> {
|
||||
const command = [
|
||||
"$processes = Get-CimInstance Win32_Process | ForEach-Object {",
|
||||
'$perf = Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess = $($_.ProcessId)" -ErrorAction SilentlyContinue;',
|
||||
"[pscustomobject]@{ ProcessId = $_.ProcessId; ParentProcessId = $_.ParentProcessId; Name = $_.Name; CommandLine = $_.CommandLine; Status = $_.Status; WorkingSetSize = $_.WorkingSetSize; PercentProcessorTime = if ($perf) { $perf.PercentProcessorTime } else { 0 } }",
|
||||
"};",
|
||||
"$processes | ConvertTo-Json -Compress -Depth 3",
|
||||
].join(" ");
|
||||
|
||||
return runProcess({
|
||||
command: "powershell.exe",
|
||||
args: ["-NoProfile", "-NonInteractive", "-Command", command],
|
||||
errorMessage: "Failed to query process diagnostics.",
|
||||
}).pipe(
|
||||
Effect.flatMap((result) =>
|
||||
result.exitCode !== 0
|
||||
? Effect.fail(
|
||||
toProcessDiagnosticsError(result.stderr.trim() || "PowerShell process query failed."),
|
||||
)
|
||||
: Effect.succeed(parseWindowsProcessRows(result.stdout)),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const readProcessRows = (platform = process.platform) =>
|
||||
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
|
||||
|
||||
export function aggregateProcessDiagnostics(input: {
|
||||
readonly serverPid: number;
|
||||
readonly rows: ReadonlyArray<ProcessRow>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
}): ServerProcessDiagnosticsResult {
|
||||
return makeResult(input);
|
||||
}
|
||||
|
||||
function assertDescendantPid(
|
||||
pid: number,
|
||||
): Effect.Effect<void, ProcessDiagnosticsError, ChildProcessSpawner.ChildProcessSpawner> {
|
||||
if (pid === process.pid) {
|
||||
return Effect.fail(toProcessDiagnosticsError("Refusing to signal the T3 server process."));
|
||||
}
|
||||
|
||||
return readProcessRows().pipe(
|
||||
Effect.flatMap((rows) => {
|
||||
const filteredRows = rows.filter((row) => !isDiagnosticsQueryProcess(row, process.pid));
|
||||
const descendant = buildDescendantEntries(filteredRows, process.pid).some(
|
||||
(entry) => entry.pid === pid,
|
||||
);
|
||||
return descendant
|
||||
? Effect.void
|
||||
: Effect.fail(
|
||||
toProcessDiagnosticsError(`Process ${pid} is not a live descendant of the T3 server.`),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeProcessDiagnostics")(function* () {
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const read: ProcessDiagnosticsShape["read"] = Effect.gen(function* () {
|
||||
const readAt = yield* DateTime.now;
|
||||
const rows = yield* readProcessRows().pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
return makeResult({ serverPid: process.pid, rows, readAt });
|
||||
}).pipe(
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
DateTime.now.pipe(
|
||||
Effect.map((readAt) =>
|
||||
makeResult({ serverPid: process.pid, rows: [], readAt, error: error.message }),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const signal: ProcessDiagnosticsShape["signal"] = Effect.fn("ProcessDiagnostics.signal")(
|
||||
function* (input) {
|
||||
return yield* assertDescendantPid(input.pid).pipe(
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
Effect.flatMap(() =>
|
||||
Effect.try({
|
||||
try: () => {
|
||||
process.kill(input.pid, input.signal);
|
||||
return {
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: true,
|
||||
message: Option.none(),
|
||||
};
|
||||
},
|
||||
catch: (cause) =>
|
||||
toProcessDiagnosticsError(
|
||||
`Failed to signal process ${input.pid} with ${input.signal}.`,
|
||||
cause,
|
||||
),
|
||||
}),
|
||||
),
|
||||
Effect.catch((error: ProcessDiagnosticsError) =>
|
||||
Effect.succeed({
|
||||
pid: input.pid,
|
||||
signal: input.signal,
|
||||
signaled: false,
|
||||
message: Option.some(error.message),
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return ProcessDiagnostics.of({ read, signal });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(ProcessDiagnostics, make());
|
||||
@@ -1,258 +0,0 @@
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
import * as TraceDiagnostics from "./TraceDiagnostics.ts";
|
||||
|
||||
function ns(ms: number): string {
|
||||
return String(BigInt(ms) * 1_000_000n);
|
||||
}
|
||||
|
||||
function record(input: {
|
||||
readonly name: string;
|
||||
readonly traceId: string;
|
||||
readonly spanId: string;
|
||||
readonly startMs: number;
|
||||
readonly durationMs: number;
|
||||
readonly exit?: { readonly _tag: "Success" | "Failure" | "Interrupted"; readonly cause?: string };
|
||||
readonly events?: ReadonlyArray<unknown>;
|
||||
}) {
|
||||
return JSON.stringify({
|
||||
type: "effect-span",
|
||||
name: input.name,
|
||||
traceId: input.traceId,
|
||||
spanId: input.spanId,
|
||||
sampled: true,
|
||||
kind: "internal",
|
||||
startTimeUnixNano: ns(input.startMs),
|
||||
endTimeUnixNano: ns(input.startMs + input.durationMs),
|
||||
durationMs: input.durationMs,
|
||||
attributes: {},
|
||||
events: input.events ?? [],
|
||||
links: [],
|
||||
exit: input.exit ?? { _tag: "Success" },
|
||||
});
|
||||
}
|
||||
|
||||
describe("TraceDiagnostics", () => {
|
||||
it.effect("aggregates failures, slow spans, log levels, and parse errors", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
slowSpanThresholdMs: 1_000,
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson.1",
|
||||
text: [
|
||||
record({
|
||||
name: "server.getConfig",
|
||||
traceId: "trace-a",
|
||||
spanId: "span-a",
|
||||
startMs: 1_000,
|
||||
durationMs: 50,
|
||||
}),
|
||||
"not-json",
|
||||
].join("\n"),
|
||||
},
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: [
|
||||
record({
|
||||
name: "orchestration.dispatch",
|
||||
traceId: "trace-b",
|
||||
spanId: "span-b",
|
||||
startMs: 2_000,
|
||||
durationMs: 1_500,
|
||||
exit: { _tag: "Failure", cause: "Provider crashed" },
|
||||
events: [
|
||||
{
|
||||
name: "provider failed",
|
||||
timeUnixNano: ns(3_400),
|
||||
attributes: { "effect.logLevel": "Error" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
record({
|
||||
name: "orchestration.dispatch",
|
||||
traceId: "trace-c",
|
||||
spanId: "span-c",
|
||||
startMs: 4_000,
|
||||
durationMs: 250,
|
||||
exit: { _tag: "Failure", cause: "Provider crashed" },
|
||||
}),
|
||||
record({
|
||||
name: "git.status",
|
||||
traceId: "trace-d",
|
||||
spanId: "span-d",
|
||||
startMs: 5_000,
|
||||
durationMs: 25,
|
||||
exit: { _tag: "Interrupted", cause: "Interrupted" },
|
||||
events: [
|
||||
{
|
||||
name: "status delayed",
|
||||
timeUnixNano: ns(5_010),
|
||||
attributes: { "effect.logLevel": "Warning" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
].join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 4);
|
||||
assert.equal(DateTime.formatIso(diagnostics.readAt), "2026-05-05T10:00:00.000Z");
|
||||
assert.equal(
|
||||
Option.match(diagnostics.firstSpanAt, {
|
||||
onNone: () => null,
|
||||
onSome: DateTime.formatIso,
|
||||
}),
|
||||
"1970-01-01T00:00:01.000Z",
|
||||
);
|
||||
assert.equal(
|
||||
Option.match(diagnostics.lastSpanAt, {
|
||||
onNone: () => null,
|
||||
onSome: DateTime.formatIso,
|
||||
}),
|
||||
"1970-01-01T00:00:05.025Z",
|
||||
);
|
||||
assert.equal(diagnostics.parseErrorCount, 1);
|
||||
assert.equal(diagnostics.failureCount, 2);
|
||||
assert.equal(diagnostics.interruptionCount, 1);
|
||||
assert.equal(diagnostics.slowSpanCount, 1);
|
||||
assert.equal(diagnostics.logLevelCounts.Error, 1);
|
||||
assert.equal(diagnostics.logLevelCounts.Warning, 1);
|
||||
assert.equal(diagnostics.commonFailures[0]?.name, "orchestration.dispatch");
|
||||
assert.equal(diagnostics.commonFailures[0]?.count, 2);
|
||||
assert.equal(diagnostics.latestFailures[0]?.traceId, "trace-c");
|
||||
assert.equal(diagnostics.slowestSpans[0]?.traceId, "trace-b");
|
||||
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, "status delayed");
|
||||
assert.equal(diagnostics.topSpansByCount[0]?.name, "orchestration.dispatch");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns a not-found diagnostic when no files are available", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/missing.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 0);
|
||||
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-not-found");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("preserves full failure causes and log messages", () =>
|
||||
Effect.sync(() => {
|
||||
const longCause = `VcsProcessSpawnError: ${"missing executable ".repeat(80)}`.trim();
|
||||
const longMessage = `provider warning: ${"retrying command ".repeat(80)}`.trim();
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: record({
|
||||
name: "VcsProcess.run",
|
||||
traceId: "trace-long",
|
||||
spanId: "span-long",
|
||||
startMs: 1_000,
|
||||
durationMs: 25,
|
||||
exit: { _tag: "Failure", cause: longCause },
|
||||
events: [
|
||||
{
|
||||
name: longMessage,
|
||||
timeUnixNano: ns(1_010),
|
||||
attributes: { "effect.logLevel": "Warning" },
|
||||
},
|
||||
],
|
||||
}),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.latestFailures[0]?.cause, longCause);
|
||||
assert.equal(diagnostics.commonFailures[0]?.cause, longCause);
|
||||
assert.equal(diagnostics.latestWarningAndErrorLogs[0]?.message, longMessage);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps loaded trace data when one rotated trace file fails to read", () =>
|
||||
Effect.gen(function* () {
|
||||
const traceFilePath = "/tmp/server.trace.ndjson";
|
||||
const fileSystemLayer = FileSystem.layerNoop({
|
||||
readFileString: (path) =>
|
||||
path === `${traceFilePath}.1`
|
||||
? Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "PermissionDenied",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
description: "permission denied",
|
||||
pathOrDescriptor: path,
|
||||
}),
|
||||
)
|
||||
: Effect.succeed(
|
||||
record({
|
||||
name: "server.getConfig",
|
||||
traceId: "trace-a",
|
||||
spanId: "span-a",
|
||||
startMs: 1_000,
|
||||
durationMs: 50,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
const diagnostics = yield* TraceDiagnostics.readTraceDiagnostics({
|
||||
traceFilePath,
|
||||
maxFiles: 1,
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
}).pipe(Effect.provide(TraceDiagnostics.layer.pipe(Layer.provide(fileSystemLayer))));
|
||||
|
||||
assert.equal(diagnostics.recordCount, 1);
|
||||
assert.equal(
|
||||
Option.getOrElse(diagnostics.partialFailure, () => false),
|
||||
true,
|
||||
);
|
||||
assert.equal(Option.getOrUndefined(diagnostics.error)?.kind, "trace-file-read-failed");
|
||||
assert.deepStrictEqual(diagnostics.scannedFilePaths, [`${traceFilePath}.1`, traceFilePath]);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps only the slowest span occurrences while aggregating large inputs", () =>
|
||||
Effect.sync(() => {
|
||||
const diagnostics = TraceDiagnostics.aggregateTraceDiagnostics({
|
||||
traceFilePath: "/tmp/server.trace.ndjson",
|
||||
readAt: DateTime.makeUnsafe("2026-05-05T10:00:00.000Z"),
|
||||
files: [
|
||||
{
|
||||
path: "/tmp/server.trace.ndjson",
|
||||
text: Array.from({ length: 25 }, (_, index) =>
|
||||
record({
|
||||
name: `span-${index}`,
|
||||
traceId: `trace-${index}`,
|
||||
spanId: `span-${index}`,
|
||||
startMs: index * 1_000,
|
||||
durationMs: index,
|
||||
}),
|
||||
).join("\n"),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
assert.equal(diagnostics.recordCount, 25);
|
||||
assert.equal(diagnostics.slowestSpans.length, 10);
|
||||
assert.deepStrictEqual(
|
||||
diagnostics.slowestSpans.map((span) => span.durationMs),
|
||||
[24, 23, 22, 21, 20, 19, 18, 17, 16, 15],
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,470 +0,0 @@
|
||||
import type {
|
||||
ServerTraceDiagnosticsErrorKind,
|
||||
ServerTraceDiagnosticsFailureSummary,
|
||||
ServerTraceDiagnosticsLogEvent,
|
||||
ServerTraceDiagnosticsRecentFailure,
|
||||
ServerTraceDiagnosticsResult,
|
||||
ServerTraceDiagnosticsSpanOccurrence,
|
||||
ServerTraceDiagnosticsSpanSummary,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Context from "effect/Context";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Option from "effect/Option";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
|
||||
interface TraceRecordLike {
|
||||
readonly name?: unknown;
|
||||
readonly traceId?: unknown;
|
||||
readonly spanId?: unknown;
|
||||
readonly startTimeUnixNano?: unknown;
|
||||
readonly endTimeUnixNano?: unknown;
|
||||
readonly durationMs?: unknown;
|
||||
readonly exit?: unknown;
|
||||
readonly events?: unknown;
|
||||
}
|
||||
|
||||
interface TraceEventLike {
|
||||
readonly name?: unknown;
|
||||
readonly timeUnixNano?: unknown;
|
||||
readonly attributes?: unknown;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsOptions {
|
||||
readonly traceFilePath: string;
|
||||
readonly maxFiles: number;
|
||||
readonly slowSpanThresholdMs?: number;
|
||||
readonly readAt?: DateTime.Utc;
|
||||
}
|
||||
|
||||
export interface TraceDiagnosticsShape {
|
||||
readonly read: (options: TraceDiagnosticsOptions) => Effect.Effect<ServerTraceDiagnosticsResult>;
|
||||
}
|
||||
|
||||
export class TraceDiagnostics extends Context.Service<TraceDiagnostics, TraceDiagnosticsShape>()(
|
||||
"t3/diagnostics/TraceDiagnostics",
|
||||
) {}
|
||||
|
||||
interface TraceDiagnosticsInput {
|
||||
readonly traceFilePath: string;
|
||||
readonly files: ReadonlyArray<{ readonly path: string; readonly text: string }>;
|
||||
readonly scannedFilePaths?: ReadonlyArray<string>;
|
||||
readonly slowSpanThresholdMs?: number;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly error?: TraceDiagnosticsErrorSummary;
|
||||
readonly partialFailure?: boolean;
|
||||
}
|
||||
|
||||
interface TraceDiagnosticsErrorSummary {
|
||||
readonly kind: ServerTraceDiagnosticsErrorKind;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
const DEFAULT_SLOW_SPAN_THRESHOLD_MS = 1_000;
|
||||
const TOP_LIMIT = 10;
|
||||
const RECENT_LIMIT = 20;
|
||||
function toRotatedTracePaths(traceFilePath: string, maxFiles: number): ReadonlyArray<string> {
|
||||
const backupCount = Math.max(0, Math.floor(maxFiles));
|
||||
const backups = Array.from(
|
||||
{ length: backupCount },
|
||||
(_, index) => `${traceFilePath}.${backupCount - index}`,
|
||||
);
|
||||
return [...backups, traceFilePath];
|
||||
}
|
||||
|
||||
function isRecordObject(value: unknown): value is TraceRecordLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function toStringValue(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
||||
}
|
||||
|
||||
function toNumberValue(value: unknown): number | null {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
||||
}
|
||||
|
||||
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
|
||||
const text = toStringValue(value);
|
||||
if (!text) return null;
|
||||
|
||||
try {
|
||||
const millis = Number(BigInt(text) / 1_000_000n);
|
||||
if (!Number.isFinite(millis)) return null;
|
||||
return DateTime.makeUnsafe(millis);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function isAfter(left: DateTime.Utc, right: DateTime.Utc): boolean {
|
||||
return DateTime.toEpochMillis(left) > DateTime.toEpochMillis(right);
|
||||
}
|
||||
|
||||
function isBefore(left: DateTime.Utc, right: DateTime.Utc): boolean {
|
||||
return DateTime.toEpochMillis(left) < DateTime.toEpochMillis(right);
|
||||
}
|
||||
|
||||
function readExitTag(exit: unknown): string | null {
|
||||
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
|
||||
return toStringValue(exit._tag);
|
||||
}
|
||||
|
||||
function readExitCause(exit: unknown): string {
|
||||
if (!isRecordObject(exit) || !("cause" in exit)) return "Failure";
|
||||
return toStringValue(exit.cause)?.trim() ?? "Failure";
|
||||
}
|
||||
|
||||
function isTraceEvent(value: unknown): value is TraceEventLike {
|
||||
return typeof value === "object" && value !== null;
|
||||
}
|
||||
|
||||
function readEventAttributes(event: TraceEventLike): Readonly<Record<string, unknown>> {
|
||||
return typeof event.attributes === "object" && event.attributes !== null
|
||||
? (event.attributes as Readonly<Record<string, unknown>>)
|
||||
: {};
|
||||
}
|
||||
|
||||
function makeEmptyDiagnostics(input: {
|
||||
readonly traceFilePath: string;
|
||||
readonly scannedFilePaths: ReadonlyArray<string>;
|
||||
readonly readAt: DateTime.Utc;
|
||||
readonly slowSpanThresholdMs: number;
|
||||
readonly error?: TraceDiagnosticsErrorSummary;
|
||||
readonly partialFailure?: boolean;
|
||||
}): ServerTraceDiagnosticsResult {
|
||||
return {
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths: [...input.scannedFilePaths],
|
||||
readAt: input.readAt,
|
||||
recordCount: 0,
|
||||
parseErrorCount: 0,
|
||||
firstSpanAt: Option.none(),
|
||||
lastSpanAt: Option.none(),
|
||||
failureCount: 0,
|
||||
interruptionCount: 0,
|
||||
slowSpanThresholdMs: input.slowSpanThresholdMs,
|
||||
slowSpanCount: 0,
|
||||
logLevelCounts: {},
|
||||
topSpansByCount: [],
|
||||
slowestSpans: [],
|
||||
commonFailures: [],
|
||||
latestFailures: [],
|
||||
latestWarningAndErrorLogs: [],
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
}
|
||||
|
||||
function isNotFoundError(error: PlatformError.PlatformError): boolean {
|
||||
return error.reason._tag === "NotFound";
|
||||
}
|
||||
|
||||
function platformErrorMessage(error: PlatformError.PlatformError): string {
|
||||
return error.message || String(error);
|
||||
}
|
||||
|
||||
function insertBoundedSlowestSpan(
|
||||
slowestSpans: ServerTraceDiagnosticsSpanOccurrence[],
|
||||
span: ServerTraceDiagnosticsSpanOccurrence,
|
||||
): void {
|
||||
if (
|
||||
slowestSpans.length >= TOP_LIMIT &&
|
||||
span.durationMs <= slowestSpans[slowestSpans.length - 1]!.durationMs
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
slowestSpans.push(span);
|
||||
slowestSpans.sort((left, right) => right.durationMs - left.durationMs);
|
||||
if (slowestSpans.length > TOP_LIMIT) {
|
||||
slowestSpans.length = TOP_LIMIT;
|
||||
}
|
||||
}
|
||||
|
||||
export function aggregateTraceDiagnostics(
|
||||
input: TraceDiagnosticsInput,
|
||||
): ServerTraceDiagnosticsResult {
|
||||
const readAt = input.readAt;
|
||||
const slowSpanThresholdMs = input.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const scannedFilePaths = input.scannedFilePaths ?? input.files.map((file) => file.path);
|
||||
if (input.files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error: input.error ?? {
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
},
|
||||
...(input.partialFailure ? { partialFailure: true } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
let parseErrorCount = 0;
|
||||
let recordCount = 0;
|
||||
let failureCount = 0;
|
||||
let interruptionCount = 0;
|
||||
let slowSpanCount = 0;
|
||||
let firstSpanAt: DateTime.Utc | null = null;
|
||||
let lastSpanAt: DateTime.Utc | null = null;
|
||||
|
||||
const spansByName = new Map<
|
||||
string,
|
||||
{ count: number; failureCount: number; totalDurationMs: number; maxDurationMs: number }
|
||||
>();
|
||||
const failuresByKey = new Map<string, ServerTraceDiagnosticsFailureSummary>();
|
||||
const latestFailures: ServerTraceDiagnosticsRecentFailure[] = [];
|
||||
const slowestSpans: ServerTraceDiagnosticsSpanOccurrence[] = [];
|
||||
const latestWarningAndErrorLogs: ServerTraceDiagnosticsLogEvent[] = [];
|
||||
const logLevelCounts: Record<string, number> = {};
|
||||
|
||||
for (const file of input.files) {
|
||||
const lines = file.text.split(/\r?\n/);
|
||||
for (const line of lines) {
|
||||
if (line.trim().length === 0) continue;
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!isRecordObject(parsed)) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const name = toStringValue(parsed.name);
|
||||
const traceId = toStringValue(parsed.traceId);
|
||||
const spanId = toStringValue(parsed.spanId);
|
||||
const durationMs = toNumberValue(parsed.durationMs);
|
||||
const endedAt = unixNanoToDateTime(parsed.endTimeUnixNano);
|
||||
const startedAt = unixNanoToDateTime(parsed.startTimeUnixNano);
|
||||
|
||||
if (!name || !traceId || !spanId || durationMs === null || !endedAt) {
|
||||
parseErrorCount += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
recordCount += 1;
|
||||
firstSpanAt =
|
||||
startedAt && (firstSpanAt === null || isBefore(startedAt, firstSpanAt))
|
||||
? startedAt
|
||||
: firstSpanAt;
|
||||
lastSpanAt = lastSpanAt === null || isAfter(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
|
||||
|
||||
const exitTag = readExitTag(parsed.exit);
|
||||
const isFailure = exitTag === "Failure";
|
||||
const isInterrupted = exitTag === "Interrupted";
|
||||
if (isFailure) failureCount += 1;
|
||||
if (isInterrupted) interruptionCount += 1;
|
||||
|
||||
const spanSummary = spansByName.get(name) ?? {
|
||||
count: 0,
|
||||
failureCount: 0,
|
||||
totalDurationMs: 0,
|
||||
maxDurationMs: 0,
|
||||
};
|
||||
spanSummary.count += 1;
|
||||
spanSummary.totalDurationMs += durationMs;
|
||||
spanSummary.maxDurationMs = Math.max(spanSummary.maxDurationMs, durationMs);
|
||||
if (isFailure) spanSummary.failureCount += 1;
|
||||
spansByName.set(name, spanSummary);
|
||||
|
||||
const spanItem = { name, durationMs, endedAt, traceId, spanId };
|
||||
if (durationMs >= slowSpanThresholdMs) {
|
||||
slowSpanCount += 1;
|
||||
}
|
||||
insertBoundedSlowestSpan(slowestSpans, spanItem);
|
||||
|
||||
if (isFailure) {
|
||||
const cause = readExitCause(parsed.exit);
|
||||
latestFailures.push({ ...spanItem, cause });
|
||||
|
||||
const failureKey = `${name}\0${cause}`;
|
||||
const existing = failuresByKey.get(failureKey);
|
||||
const isLatestFailure = !existing || isAfter(endedAt, existing.lastSeenAt);
|
||||
failuresByKey.set(failureKey, {
|
||||
name,
|
||||
cause,
|
||||
count: (existing?.count ?? 0) + 1,
|
||||
lastSeenAt: isLatestFailure ? endedAt : existing!.lastSeenAt,
|
||||
traceId: isLatestFailure ? traceId : existing!.traceId,
|
||||
spanId: isLatestFailure ? spanId : existing!.spanId,
|
||||
});
|
||||
}
|
||||
|
||||
if (Array.isArray(parsed.events)) {
|
||||
for (const rawEvent of parsed.events) {
|
||||
if (!isTraceEvent(rawEvent)) continue;
|
||||
const attributes = readEventAttributes(rawEvent);
|
||||
const level = toStringValue(attributes["effect.logLevel"]);
|
||||
if (!level) continue;
|
||||
|
||||
logLevelCounts[level] = (logLevelCounts[level] ?? 0) + 1;
|
||||
const normalizedLevel = level.toLowerCase();
|
||||
if (
|
||||
normalizedLevel !== "warning" &&
|
||||
normalizedLevel !== "warn" &&
|
||||
normalizedLevel !== "error" &&
|
||||
normalizedLevel !== "fatal"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const seenAt = unixNanoToDateTime(rawEvent.timeUnixNano) ?? endedAt;
|
||||
const message = toStringValue(rawEvent.name)?.trim() ?? "Log event";
|
||||
latestWarningAndErrorLogs.push({
|
||||
spanName: name,
|
||||
level,
|
||||
message,
|
||||
seenAt,
|
||||
traceId,
|
||||
spanId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const topSpansByCount: ServerTraceDiagnosticsSpanSummary[] = [...spansByName.entries()]
|
||||
.map(([name, span]) => ({
|
||||
name,
|
||||
count: span.count,
|
||||
failureCount: span.failureCount,
|
||||
totalDurationMs: span.totalDurationMs,
|
||||
averageDurationMs: span.count > 0 ? span.totalDurationMs / span.count : 0,
|
||||
maxDurationMs: span.maxDurationMs,
|
||||
}))
|
||||
.toSorted((left, right) => right.count - left.count || right.maxDurationMs - left.maxDurationMs)
|
||||
.slice(0, TOP_LIMIT);
|
||||
|
||||
return {
|
||||
traceFilePath: input.traceFilePath,
|
||||
scannedFilePaths,
|
||||
readAt,
|
||||
recordCount,
|
||||
parseErrorCount,
|
||||
firstSpanAt: Option.fromNullishOr(firstSpanAt),
|
||||
lastSpanAt: Option.fromNullishOr(lastSpanAt),
|
||||
failureCount,
|
||||
interruptionCount,
|
||||
slowSpanThresholdMs,
|
||||
slowSpanCount,
|
||||
logLevelCounts,
|
||||
topSpansByCount,
|
||||
slowestSpans,
|
||||
commonFailures: [...failuresByKey.values()]
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
right.count - left.count ||
|
||||
DateTime.toEpochMillis(right.lastSeenAt) - DateTime.toEpochMillis(left.lastSeenAt),
|
||||
)
|
||||
.slice(0, TOP_LIMIT),
|
||||
latestFailures: latestFailures
|
||||
.toSorted(
|
||||
(left, right) =>
|
||||
DateTime.toEpochMillis(right.endedAt) - DateTime.toEpochMillis(left.endedAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
latestWarningAndErrorLogs: latestWarningAndErrorLogs
|
||||
.toSorted(
|
||||
(left, right) => DateTime.toEpochMillis(right.seenAt) - DateTime.toEpochMillis(left.seenAt),
|
||||
)
|
||||
.slice(0, RECENT_LIMIT),
|
||||
partialFailure: input.partialFailure ? Option.some(true) : Option.none(),
|
||||
error: Option.fromNullishOr(input.error),
|
||||
};
|
||||
}
|
||||
|
||||
type TraceFileReadResult =
|
||||
| { readonly _tag: "Loaded"; readonly path: string; readonly text: string }
|
||||
| { readonly _tag: "Missing"; readonly path: string }
|
||||
| { readonly _tag: "Failed"; readonly path: string; readonly message: string };
|
||||
|
||||
function readTraceFile(
|
||||
fileSystem: FileSystem.FileSystem,
|
||||
path: string,
|
||||
): Effect.Effect<TraceFileReadResult> {
|
||||
return fileSystem.readFileString(path).pipe(
|
||||
Effect.map((text) => ({ _tag: "Loaded" as const, path, text })),
|
||||
Effect.catch((error: PlatformError.PlatformError) =>
|
||||
Effect.succeed(
|
||||
isNotFoundError(error)
|
||||
? { _tag: "Missing" as const, path }
|
||||
: { _tag: "Failed" as const, path, message: platformErrorMessage(error) },
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeTraceDiagnostics")(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
|
||||
const read: TraceDiagnosticsShape["read"] = Effect.fn("TraceDiagnostics.read")(
|
||||
function* (options) {
|
||||
const readAt = options.readAt ?? (yield* DateTime.now);
|
||||
const slowSpanThresholdMs = options.slowSpanThresholdMs ?? DEFAULT_SLOW_SPAN_THRESHOLD_MS;
|
||||
const paths = toRotatedTracePaths(options.traceFilePath, options.maxFiles);
|
||||
const results = yield* Effect.all(
|
||||
paths.map((path) => readTraceFile(fileSystem, path)),
|
||||
{
|
||||
concurrency: 1,
|
||||
},
|
||||
);
|
||||
const files = results.flatMap((result) =>
|
||||
result._tag === "Loaded" ? [{ path: result.path, text: result.text }] : [],
|
||||
);
|
||||
const readFailure = results.find((result) => result._tag === "Failed");
|
||||
const readFailureError = readFailure
|
||||
? ({
|
||||
kind: "trace-file-read-failed",
|
||||
message: readFailure.message.trim() || `Failed to read ${readFailure.path}.`,
|
||||
} satisfies TraceDiagnosticsErrorSummary)
|
||||
: undefined;
|
||||
|
||||
if (files.length === 0) {
|
||||
return makeEmptyDiagnostics({
|
||||
traceFilePath: options.traceFilePath,
|
||||
scannedFilePaths: paths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
error:
|
||||
readFailureError ??
|
||||
({
|
||||
kind: "trace-file-not-found",
|
||||
message: "No local trace files were found.",
|
||||
} satisfies TraceDiagnosticsErrorSummary),
|
||||
});
|
||||
}
|
||||
|
||||
return aggregateTraceDiagnostics({
|
||||
traceFilePath: options.traceFilePath,
|
||||
files,
|
||||
scannedFilePaths: paths,
|
||||
readAt,
|
||||
slowSpanThresholdMs,
|
||||
...(readFailureError ? { partialFailure: true, error: readFailureError } : {}),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
return TraceDiagnostics.of({ read });
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(TraceDiagnostics, make());
|
||||
|
||||
export function readTraceDiagnostics(
|
||||
options: TraceDiagnosticsOptions,
|
||||
): Effect.Effect<ServerTraceDiagnosticsResult, never, TraceDiagnostics> {
|
||||
return Effect.gen(function* () {
|
||||
const diagnostics = yield* TraceDiagnostics;
|
||||
return yield* diagnostics.read(options);
|
||||
});
|
||||
}
|
||||
@@ -30,8 +30,6 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
|
||||
mode: "web",
|
||||
autoBootstrapProjectFromCwd: false,
|
||||
logWebSocketEvents: false,
|
||||
tailscaleServeEnabled: false,
|
||||
tailscaleServePort: 443,
|
||||
port: 0,
|
||||
host: undefined,
|
||||
desktopBootstrapToken: undefined,
|
||||
|
||||
@@ -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"] {
|
||||
@@ -77,7 +77,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
|
||||
os: platformOs(),
|
||||
arch: platformArch(),
|
||||
},
|
||||
serverVersion: packageJson.version,
|
||||
serverVersion: version,
|
||||
capabilities: {
|
||||
repositoryIdentity: true,
|
||||
},
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
import { assert, describe, it, vi } from "@effect/vitest";
|
||||
import { Effect, Layer } from "effect";
|
||||
|
||||
import * as GitManager from "./GitManager.ts";
|
||||
import * as GitWorkflowService from "./GitWorkflowService.ts";
|
||||
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
|
||||
import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
function makeLayer(input: { readonly detect: VcsDriverRegistry.VcsDriverRegistryShape["detect"] }) {
|
||||
return GitWorkflowService.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
||||
detect: input.detect,
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
|
||||
Layer.provide(Layer.mock(GitManager.GitManager)({})),
|
||||
);
|
||||
}
|
||||
|
||||
describe("GitWorkflowService", () => {
|
||||
it.effect("returns an empty local status when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const status = yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(status, {
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns an empty full status when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const status = yield* workflow.status({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(status, {
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("does not call GitManager status methods when no VCS repository is detected", () => {
|
||||
const localStatus = vi.fn();
|
||||
const remoteStatus = vi.fn();
|
||||
const status = vi.fn();
|
||||
|
||||
const testLayer = GitWorkflowService.layer.pipe(
|
||||
Layer.provide(
|
||||
Layer.mock(VcsDriverRegistry.VcsDriverRegistry)({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
|
||||
Layer.provide(
|
||||
Layer.mock(GitManager.GitManager)({
|
||||
localStatus,
|
||||
remoteStatus,
|
||||
status,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
yield* workflow.localStatus({ cwd: "/not-a-repo" });
|
||||
yield* workflow.remoteStatus({ cwd: "/not-a-repo" });
|
||||
yield* workflow.status({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.equal(localStatus.mock.calls.length, 0);
|
||||
assert.equal(remoteStatus.mock.calls.length, 0);
|
||||
assert.equal(status.mock.calls.length, 0);
|
||||
}).pipe(Effect.provide(testLayer));
|
||||
});
|
||||
|
||||
it.effect("returns an empty ref list when no VCS repository is detected", () =>
|
||||
Effect.gen(function* () {
|
||||
const workflow = yield* GitWorkflowService.GitWorkflowService;
|
||||
const refs = yield* workflow.listRefs({ cwd: "/not-a-repo" });
|
||||
|
||||
assert.deepStrictEqual(refs, {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
makeLayer({
|
||||
detect: () => Effect.succeed(null),
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -1,314 +0,0 @@
|
||||
import { Context, Effect, Layer } from "effect";
|
||||
|
||||
import {
|
||||
GitManagerError,
|
||||
GitCommandError,
|
||||
type VcsSwitchRefInput,
|
||||
type VcsSwitchRefResult,
|
||||
type VcsCreateRefInput,
|
||||
type VcsCreateRefResult,
|
||||
type VcsCreateWorktreeInput,
|
||||
type VcsCreateWorktreeResult,
|
||||
type VcsListRefsInput,
|
||||
type VcsListRefsResult,
|
||||
type GitManagerServiceError,
|
||||
type GitPreparePullRequestThreadInput,
|
||||
type GitPreparePullRequestThreadResult,
|
||||
type GitPullRequestRefInput,
|
||||
type VcsPullResult,
|
||||
type VcsRemoveWorktreeInput,
|
||||
type GitResolvePullRequestResult,
|
||||
type GitRunStackedActionInput,
|
||||
type GitRunStackedActionResult,
|
||||
type VcsStatusInput,
|
||||
type VcsStatusLocalResult,
|
||||
type VcsStatusRemoteResult,
|
||||
type VcsStatusResult,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { GitManager, type GitRunStackedActionOptions } from "./GitManager.ts";
|
||||
import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
|
||||
import { VcsDriverRegistry } from "../vcs/VcsDriverRegistry.ts";
|
||||
|
||||
export interface GitWorkflowServiceShape {
|
||||
readonly status: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
|
||||
readonly localStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
|
||||
readonly remoteStatus: (
|
||||
input: VcsStatusInput,
|
||||
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
|
||||
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
|
||||
readonly pullCurrentBranch: (cwd: string) => Effect.Effect<VcsPullResult, GitCommandError>;
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
readonly resolvePullRequest: (
|
||||
input: GitPullRequestRefInput,
|
||||
) => Effect.Effect<GitResolvePullRequestResult, GitManagerServiceError>;
|
||||
readonly preparePullRequestThread: (
|
||||
input: GitPreparePullRequestThreadInput,
|
||||
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
|
||||
readonly listRefs: (input: VcsListRefsInput) => Effect.Effect<VcsListRefsResult, GitCommandError>;
|
||||
readonly createWorktree: (
|
||||
input: VcsCreateWorktreeInput,
|
||||
) => Effect.Effect<VcsCreateWorktreeResult, GitCommandError>;
|
||||
readonly removeWorktree: (input: VcsRemoveWorktreeInput) => Effect.Effect<void, GitCommandError>;
|
||||
readonly createRef: (
|
||||
input: VcsCreateRefInput,
|
||||
) => Effect.Effect<VcsCreateRefResult, GitCommandError>;
|
||||
readonly switchRef: (
|
||||
input: VcsSwitchRefInput,
|
||||
) => Effect.Effect<VcsSwitchRefResult, GitCommandError>;
|
||||
readonly renameBranch: (input: {
|
||||
readonly cwd: string;
|
||||
readonly oldBranch: string;
|
||||
readonly newBranch: string;
|
||||
}) => Effect.Effect<{ readonly branch: string }, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
export class GitWorkflowService extends Context.Service<
|
||||
GitWorkflowService,
|
||||
GitWorkflowServiceShape
|
||||
>()("t3/git/GitWorkflowService") {}
|
||||
|
||||
const unsupportedGitWorkflow = (operation: string, cwd: string, detail: string) =>
|
||||
new GitManagerError({
|
||||
operation,
|
||||
detail: `${detail} (${cwd})`,
|
||||
});
|
||||
|
||||
const unsupportedGitCommand = (operation: string, cwd: string, detail: string) =>
|
||||
new GitCommandError({
|
||||
operation,
|
||||
command: "vcs-route",
|
||||
cwd,
|
||||
detail,
|
||||
});
|
||||
|
||||
function nonRepositoryLocalStatus(): VcsStatusLocalResult {
|
||||
return {
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
isDefaultRef: false,
|
||||
refName: null,
|
||||
hasWorkingTreeChanges: false,
|
||||
workingTree: {
|
||||
files: [],
|
||||
insertions: 0,
|
||||
deletions: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function nonRepositoryStatus(): VcsStatusResult {
|
||||
return {
|
||||
...nonRepositoryLocalStatus(),
|
||||
hasUpstream: false,
|
||||
aheadCount: 0,
|
||||
behindCount: 0,
|
||||
aheadOfDefaultCount: 0,
|
||||
pr: null,
|
||||
};
|
||||
}
|
||||
|
||||
function nonRepositoryListRefs(): VcsListRefsResult {
|
||||
return {
|
||||
refs: [],
|
||||
isRepo: false,
|
||||
hasPrimaryRemote: false,
|
||||
nextCursor: null,
|
||||
totalCount: 0,
|
||||
};
|
||||
}
|
||||
|
||||
export const make = Effect.fn("makeGitWorkflowService")(function* () {
|
||||
const registry = yield* VcsDriverRegistry;
|
||||
const git = yield* GitVcsDriver;
|
||||
const gitManager = yield* GitManager;
|
||||
|
||||
const ensureGit = Effect.fn("GitWorkflowService.ensureGit")(function* (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
) {
|
||||
const handle = yield* registry
|
||||
.resolve({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const ensureGitCommand = Effect.fn("GitWorkflowService.ensureGitCommand")(function* (
|
||||
operation: string,
|
||||
cwd: string,
|
||||
) {
|
||||
const handle = yield* registry
|
||||
.resolve({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const detectGitRepositoryForStatus = Effect.fn("GitWorkflowService.detectGitRepositoryForStatus")(
|
||||
function* (operation: string, cwd: string) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return false;
|
||||
}
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitWorkflow(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} workflow currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
);
|
||||
|
||||
const detectGitRepositoryForCommand = Effect.fn(
|
||||
"GitWorkflowService.detectGitRepositoryForCommand",
|
||||
)(function* (operation: string, cwd: string) {
|
||||
const handle = yield* registry
|
||||
.detect({ cwd })
|
||||
.pipe(
|
||||
Effect.mapError((error) =>
|
||||
unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
error instanceof Error ? error.message : String(error),
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!handle) {
|
||||
return false;
|
||||
}
|
||||
if (handle.kind !== "git") {
|
||||
return yield* unsupportedGitCommand(
|
||||
operation,
|
||||
cwd,
|
||||
`The ${operation} command currently supports Git repositories only; detected ${handle.kind}.`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const routeGitManager =
|
||||
<Input extends { readonly cwd: string }, Output>(
|
||||
operation: string,
|
||||
run: (input: Input) => Effect.Effect<Output, GitManagerServiceError>,
|
||||
) =>
|
||||
(input: Input) =>
|
||||
ensureGit(operation, input.cwd).pipe(Effect.andThen(run(input)));
|
||||
|
||||
return GitWorkflowService.of({
|
||||
status: (input) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.status", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? gitManager.status(input) : Effect.succeed(nonRepositoryStatus()),
|
||||
),
|
||||
),
|
||||
localStatus: (input) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.localStatus", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository
|
||||
? gitManager.localStatus(input)
|
||||
: Effect.succeed(nonRepositoryLocalStatus()),
|
||||
),
|
||||
),
|
||||
remoteStatus: (input) =>
|
||||
detectGitRepositoryForStatus("GitWorkflowService.remoteStatus", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? gitManager.remoteStatus(input) : Effect.succeed(null),
|
||||
),
|
||||
),
|
||||
invalidateLocalStatus: gitManager.invalidateLocalStatus,
|
||||
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
|
||||
invalidateStatus: gitManager.invalidateStatus,
|
||||
pullCurrentBranch: (cwd) =>
|
||||
ensureGitCommand("GitWorkflowService.pullCurrentBranch", cwd).pipe(
|
||||
Effect.andThen(git.pullCurrentBranch(cwd)),
|
||||
),
|
||||
runStackedAction: (input, options) =>
|
||||
ensureGit("GitWorkflowService.runStackedAction", input.cwd).pipe(
|
||||
Effect.andThen(gitManager.runStackedAction(input, options)),
|
||||
),
|
||||
resolvePullRequest: routeGitManager(
|
||||
"GitWorkflowService.resolvePullRequest",
|
||||
gitManager.resolvePullRequest,
|
||||
),
|
||||
preparePullRequestThread: routeGitManager(
|
||||
"GitWorkflowService.preparePullRequestThread",
|
||||
gitManager.preparePullRequestThread,
|
||||
),
|
||||
listRefs: (input) =>
|
||||
detectGitRepositoryForCommand("GitWorkflowService.listRefs", input.cwd).pipe(
|
||||
Effect.flatMap((isGitRepository) =>
|
||||
isGitRepository ? git.listRefs(input) : Effect.succeed(nonRepositoryListRefs()),
|
||||
),
|
||||
),
|
||||
createWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.createWorktree(input)),
|
||||
),
|
||||
removeWorktree: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.removeWorktree", input.cwd).pipe(
|
||||
Effect.andThen(git.removeWorktree(input)),
|
||||
),
|
||||
createRef: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.createRef", input.cwd).pipe(
|
||||
Effect.andThen(git.createRef(input)),
|
||||
),
|
||||
switchRef: (input) =>
|
||||
ensureGitCommand("GitWorkflowService.switchRef", input.cwd).pipe(
|
||||
Effect.andThen(Effect.scoped(git.switchRef(input))),
|
||||
),
|
||||
renameBranch: (input) =>
|
||||
ensureGit("GitWorkflowService.renameBranch", input.cwd).pipe(
|
||||
Effect.andThen(git.renameBranch(input)),
|
||||
),
|
||||
});
|
||||
});
|
||||
|
||||
export const layer = Layer.effect(GitWorkflowService, make());
|
||||
@@ -0,0 +1,309 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { sanitizeThreadTitle } from "../Utils.ts";
|
||||
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-claude-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeClaudeBinary(dir: string) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const binDir = path.join(dir, "bin");
|
||||
const claudePath = path.join(binDir, "claude");
|
||||
yield* fs.makeDirectory(binDir, { recursive: true });
|
||||
|
||||
yield* fs.writeFileString(
|
||||
claudePath,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
'args="$*"',
|
||||
'stdin_content="$(cat)"',
|
||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "args missing expected content" >&2',
|
||||
" exit 2",
|
||||
" }",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
|
||||
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
|
||||
' printf "%s\\n" "args contained forbidden content" >&2',
|
||||
" exit 3",
|
||||
" fi",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
" exit 4",
|
||||
" }",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
|
||||
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
|
||||
"fi",
|
||||
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
|
||||
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(claudePath, 0o755);
|
||||
return binDir;
|
||||
});
|
||||
}
|
||||
|
||||
function withFakeClaudeEnv<A, E, R>(
|
||||
input: {
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
argsMustContain?: string;
|
||||
argsMustNotContain?: string;
|
||||
stdinMustContain?: string;
|
||||
},
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.acquireUseRelease(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
|
||||
const binDir = yield* makeFakeClaudeBinary(tempDir);
|
||||
const previousPath = process.env.PATH;
|
||||
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
|
||||
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
|
||||
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||
|
||||
yield* Effect.sync(() => {
|
||||
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
|
||||
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
|
||||
|
||||
if (input.exitCode !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||
}
|
||||
|
||||
if (input.stderr !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
||||
}
|
||||
|
||||
if (input.argsMustContain !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||
}
|
||||
|
||||
if (input.argsMustNotContain !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||
}
|
||||
|
||||
if (input.stdinMustContain !== undefined) {
|
||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
|
||||
} else {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousArgsMustContain,
|
||||
previousArgsMustNotContain,
|
||||
previousStdinMustContain,
|
||||
};
|
||||
}),
|
||||
() => effect,
|
||||
(previous) =>
|
||||
Effect.sync(() => {
|
||||
process.env.PATH = previous.previousPath;
|
||||
|
||||
if (previous.previousOutput === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
|
||||
}
|
||||
|
||||
if (previous.previousExitCode === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
|
||||
}
|
||||
|
||||
if (previous.previousStderr === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDERR;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
|
||||
}
|
||||
|
||||
if (previous.previousArgsMustContain === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
|
||||
}
|
||||
|
||||
if (previous.previousArgsMustNotContain === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
|
||||
}
|
||||
|
||||
if (previous.previousStdinMustContain === undefined) {
|
||||
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
|
||||
} else {
|
||||
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
|
||||
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
subject: "Add important change",
|
||||
body: "",
|
||||
},
|
||||
}),
|
||||
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
|
||||
argsMustNotContain: "--effort",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/claude-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
thinking: false,
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("forwards Claude fast mode and supported effort", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title: "Improve orchestration flow",
|
||||
body: "Body",
|
||||
},
|
||||
}),
|
||||
argsMustContain: '--effort max --settings {"fastMode":true}',
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd: process.cwd(),
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/claude-effect",
|
||||
commitSummary: "Improve orchestration",
|
||||
diffSummary: "1 file changed",
|
||||
diffPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Improve orchestration flow");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("generates thread titles through the Claude provider", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title:
|
||||
' "Reconnect failures after restart because the session state does not recover" ',
|
||||
},
|
||||
}),
|
||||
stdinMustContain: "You write concise thread titles for coding conversations.",
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate reconnect failures after restarting the session.",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe(
|
||||
sanitizeThreadTitle(
|
||||
'"Reconnect failures after restart because the session state does not recover"',
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("falls back when Claude thread title normalization becomes whitespace-only", () =>
|
||||
withFakeClaudeEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
structured_output: {
|
||||
title: ' """ """ ',
|
||||
},
|
||||
}),
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
+58
-43
@@ -7,38 +7,31 @@
|
||||
*
|
||||
* @module ClaudeTextGeneration
|
||||
*/
|
||||
import { Effect, Option, Schema, Stream } from "effect";
|
||||
import { Effect, Layer, Option, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { type ClaudeSettings, type ModelSelection } from "@t3tools/contracts";
|
||||
import { ClaudeModelSelection } from "@t3tools/contracts";
|
||||
import { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import {
|
||||
buildBranchNamePrompt,
|
||||
buildCommitMessagePrompt,
|
||||
buildPrContentPrompt,
|
||||
buildThreadTitlePrompt,
|
||||
} from "./TextGenerationPrompts.ts";
|
||||
} from "../Prompts.ts";
|
||||
import {
|
||||
normalizeCliError,
|
||||
sanitizeCommitSubject,
|
||||
sanitizePrTitle,
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "./TextGenerationUtils.ts";
|
||||
import {
|
||||
getModelSelectionStringOptionValue,
|
||||
getProviderOptionDescriptors,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
getClaudeModelCapabilities,
|
||||
normalizeClaudeCliEffort,
|
||||
resolveClaudeApiModelId,
|
||||
resolveClaudeEffort,
|
||||
} from "../provider/Layers/ClaudeProvider.ts";
|
||||
import { makeClaudeEnvironment } from "../provider/Drivers/ClaudeHome.ts";
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -50,12 +43,9 @@ const ClaudeOutputEnvelope = Schema.Struct({
|
||||
structured_output: Schema.Unknown,
|
||||
});
|
||||
|
||||
export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(function* (
|
||||
claudeSettings: ClaudeSettings,
|
||||
environment: NodeJS.ProcessEnv = process.env,
|
||||
) {
|
||||
const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const claudeEnvironment = yield* makeClaudeEnvironment(claudeSettings, environment);
|
||||
const serverSettingsService = yield* Effect.service(ServerSettingsService);
|
||||
|
||||
const readStreamAsString = <E>(
|
||||
operation: string,
|
||||
@@ -91,32 +81,28 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
cwd: string;
|
||||
prompt: string;
|
||||
outputSchemaJson: S;
|
||||
modelSelection: ModelSelection;
|
||||
modelSelection: ClaudeModelSelection;
|
||||
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const caps = getClaudeModelCapabilities(modelSelection.model);
|
||||
const descriptors = getProviderOptionDescriptors({
|
||||
caps,
|
||||
selections: modelSelection.options,
|
||||
});
|
||||
const findDescriptor = (id: string) => descriptors.find((descriptor) => descriptor.id === id);
|
||||
const rawEffortSelection = getModelSelectionStringOptionValue(modelSelection, "effort");
|
||||
const resolvedEffort = resolveClaudeEffort(caps, rawEffortSelection);
|
||||
const cliEffort = normalizeClaudeCliEffort(resolvedEffort);
|
||||
const thinkingDescriptor = findDescriptor("thinking");
|
||||
const fastModeDescriptor = findDescriptor("fastMode");
|
||||
const thinking =
|
||||
thinkingDescriptor?.type === "boolean" ? thinkingDescriptor.currentValue : undefined;
|
||||
const fastMode =
|
||||
fastModeDescriptor?.type === "boolean" ? fastModeDescriptor.currentValue : undefined;
|
||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||
getClaudeModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(typeof normalizedOptions?.thinking === "boolean"
|
||||
? { alwaysThinkingEnabled: normalizedOptions.thinking }
|
||||
: {}),
|
||||
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
|
||||
};
|
||||
|
||||
const claudeSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.providers.claudeAgent,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
|
||||
const command = ChildProcess.make(
|
||||
claudeSettings.binaryPath || "claude",
|
||||
claudeSettings?.binaryPath || "claude",
|
||||
[
|
||||
"-p",
|
||||
"--output-format",
|
||||
@@ -124,13 +110,12 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
resolveClaudeApiModelId(modelSelection),
|
||||
...(cliEffort ? ["--effort", cliEffort] : []),
|
||||
resolveApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
],
|
||||
{
|
||||
env: claudeEnvironment,
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
@@ -231,6 +216,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
includeBranch: input.includeBranch === true,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
@@ -259,6 +251,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
diffPatch: input.diffPatch,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generatePrContent",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
@@ -281,6 +280,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
@@ -302,6 +308,13 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "claudeAgent") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateThreadTitle",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runClaudeJson({
|
||||
operation: "generateThreadTitle",
|
||||
cwd: input.cwd,
|
||||
@@ -322,3 +335,5 @@ export const makeClaudeTextGeneration = Effect.fn("makeClaudeTextGeneration")(fu
|
||||
generateThreadTitle,
|
||||
} satisfies TextGenerationShape;
|
||||
});
|
||||
|
||||
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
|
||||
+290
-245
@@ -1,24 +1,29 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path, Result, Schema } from "effect";
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { Effect, FileSystem, Layer, Path, Result } from "effect";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { CodexSettings, ProviderInstanceId, TextGenerationError } from "@t3tools/contracts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
|
||||
import { TextGenerationError } from "@t3tools/contracts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
import { ServerConfig } from "../config.ts";
|
||||
import { type TextGenerationShape } from "./TextGeneration.ts";
|
||||
import { makeCodexTextGeneration } from "./CodexTextGeneration.ts";
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5.4-mini",
|
||||
};
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = createModelSelection(
|
||||
ProviderInstanceId.make("codex"),
|
||||
"gpt-5.4-mini",
|
||||
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-codex-text-generation-test-",
|
||||
}),
|
||||
),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
const CodexTextGenerationTestLayer = ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-codex-text-generation-test-",
|
||||
}).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
function makeFakeCodexBinary(
|
||||
dir: string,
|
||||
input: {
|
||||
@@ -156,19 +161,39 @@ function withFakeCodexEnv<A, E, R>(
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: string;
|
||||
},
|
||||
effectFn: (textGeneration: TextGenerationShape) => Effect.Effect<A, E, R>,
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||
const config = Schema.decodeSync(CodexSettings)({ binaryPath: codexPath });
|
||||
const textGeneration = yield* makeCodexTextGeneration(config);
|
||||
return yield* effectFn(textGeneration);
|
||||
}).pipe(Effect.scoped);
|
||||
return Effect.acquireUseRelease(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const previousSettings = yield* serverSettings.getSettings;
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: codexPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
||||
}),
|
||||
() => effect,
|
||||
({ serverSettings, previousBinaryPath }) =>
|
||||
serverSettings
|
||||
.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: previousBinaryPath,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
it.effect("generates and sanitizes commit messages without branch by default", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
@@ -179,21 +204,22 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
}),
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||
expect(generated.subject.endsWith(".")).toBe(false);
|
||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||
expect(generated.branch).toBeUndefined();
|
||||
}),
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.subject.length).toBeLessThanOrEqual(72);
|
||||
expect(generated.subject.endsWith(".")).toBe(false);
|
||||
expect(generated.body).toBe("- added migration\n- updated tests");
|
||||
expect(generated.branch).toBeUndefined();
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -210,17 +236,24 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
requireReasoningEffort: "xhigh",
|
||||
stdinMustNotContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
(textGeneration) =>
|
||||
textGeneration.generateCommitMessage({
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: createModelSelection(ProviderInstanceId.make("codex"), "gpt-5.4", [
|
||||
{ id: "reasoningEffort", value: "xhigh" },
|
||||
{ id: "fastMode", value: true },
|
||||
]),
|
||||
}),
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -233,14 +266,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
}),
|
||||
requireReasoningEffort: "low",
|
||||
},
|
||||
(textGeneration) =>
|
||||
textGeneration.generateCommitMessage({
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
}),
|
||||
});
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -254,20 +290,21 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
}),
|
||||
stdinMustContain: "branch must be a short semantic git branch fragment",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
includeBranch: true,
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||
}),
|
||||
const generated = yield* textGeneration.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-effect",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
includeBranch: true,
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.subject).toBe("Add important change");
|
||||
expect(generated.branch).toBe("feature/fix/important-system-change");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -279,22 +316,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
body: "\n## Summary\n- improve flow\n\n## Testing\n- bun test\n\n",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd: process.cwd(),
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/codex-effect",
|
||||
commitSummary: "feat: improve orchestration flow",
|
||||
diffSummary: "2 files changed",
|
||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.title).toBe("Improve orchestration flow");
|
||||
expect(generated.body.startsWith("## Summary")).toBe(true);
|
||||
expect(generated.body.endsWith("\n\n")).toBe(false);
|
||||
}),
|
||||
const generated = yield* textGeneration.generatePrContent({
|
||||
cwd: process.cwd(),
|
||||
baseBranch: "main",
|
||||
headBranch: "feature/codex-effect",
|
||||
commitSummary: "feat: improve orchestration flow",
|
||||
diffSummary: "2 files changed",
|
||||
diffPatch: "diff --git a/a.ts b/a.ts",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Improve orchestration flow");
|
||||
expect(generated.body.startsWith("## Summary")).toBe(true);
|
||||
expect(generated.body.endsWith("\n\n")).toBe(false);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -306,16 +344,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
}),
|
||||
stdinMustNotContain: "Image attachments supplied to the model",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Please update session handling.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.branch).toBe("feat/session");
|
||||
}),
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Please update session handling.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("feat/session");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -327,16 +366,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
' "Investigate websocket reconnect regressions after worktree restore" \nignored line',
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
||||
}),
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Please investigate websocket reconnect regressions after a worktree restore.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("Investigate websocket reconnect regressions aft...");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -347,16 +387,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
title: ' """ """ ',
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("New thread");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -367,16 +408,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
title: ` "' hello world '" `,
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.title).toBe("hello world");
|
||||
}),
|
||||
const generated = yield* textGeneration.generateThreadTitle({
|
||||
cwd: process.cwd(),
|
||||
message: "Name this thread.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.title).toBe("hello world");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -388,16 +430,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
}),
|
||||
stdinMustNotContain: "Attachment metadata:",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix timeout behavior.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(generated.branch).toBe("fix/session-timeout");
|
||||
}),
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix timeout behavior.",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/session-timeout");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -410,17 +453,56 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
requireImage: true,
|
||||
stdinMustContain: "Attachment metadata:",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
},
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
@@ -433,59 +515,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("resolves persisted attachment ids to files for codex image inputs", () =>
|
||||
withFakeCodexEnv(
|
||||
{
|
||||
output: JSON.stringify({
|
||||
branch: "fix/ui-regression",
|
||||
}),
|
||||
requireImage: true,
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
|
||||
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
|
||||
yield* fs.writeFile(imagePath, Buffer.from("hello"));
|
||||
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: attachmentId,
|
||||
name: "bug.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() =>
|
||||
fs.stat(imagePath).pipe(
|
||||
Effect.map((fileInfo) => {
|
||||
expect(fileInfo.type).toBe("File");
|
||||
}),
|
||||
),
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() =>
|
||||
fs.stat(imagePath).pipe(
|
||||
Effect.map((fileInfo) => {
|
||||
expect(fileInfo.type).toBe("File");
|
||||
}),
|
||||
),
|
||||
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
|
||||
);
|
||||
),
|
||||
Effect.ensuring(fs.remove(imagePath).pipe(Effect.catch(() => Effect.void))),
|
||||
);
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -497,38 +540,38 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
}),
|
||||
requireImage: true,
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
|
||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const { attachmentsDir } = yield* ServerConfig;
|
||||
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
|
||||
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
|
||||
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
|
||||
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: missingAttachmentId,
|
||||
name: "outside.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
{
|
||||
type: "image",
|
||||
id: missingAttachmentId,
|
||||
name: "outside.png",
|
||||
mimeType: "image/png",
|
||||
sizeBytes: 5,
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain("missing --image input");
|
||||
}
|
||||
}),
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain("missing --image input");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -541,22 +584,23 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
title: "This is not a branch payload",
|
||||
}),
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix websocket reconnect flake",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
||||
}
|
||||
}),
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix websocket reconnect flake",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain("Codex returned invalid structured output");
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -567,26 +611,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGeneration", (it) => {
|
||||
exitCode: 1,
|
||||
stderr: "codex execution failed",
|
||||
},
|
||||
(textGeneration) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-error",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
Effect.gen(function* () {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain(
|
||||
"Codex CLI command failed: codex execution failed",
|
||||
);
|
||||
}
|
||||
}),
|
||||
const result = yield* textGeneration
|
||||
.generateCommitMessage({
|
||||
cwd: process.cwd(),
|
||||
branch: "feature/codex-error",
|
||||
stagedSummary: "M README.md",
|
||||
stagedPatch: "diff --git a/README.md b/README.md",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain(
|
||||
"Codex CLI command failed: codex execution failed",
|
||||
);
|
||||
}
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
Loaded 100 of 788 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user