Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge cb6fa9c8ea Use schema decoding for Effect parsing paths
Co-authored-by: Julius Marminge <[email protected]>
2026-05-21 16:07:18 +00:00
t3-code[bot] d1e85c4e8f chore(release): prepare v0.0.24 2026-05-15 06:40:13 +00:00
Julius Marminge ea20e80021 Exclude workspace packages from desktop runtime deps (#2688) 2026-05-14 07:32:48 +00:00
Julius MarmingeandJulius Marminge 9e632f5cec [codex] add diagnostics resource history (#2685)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-14 09:14:32 +02:00
Julius Marminge 4120e94598 Back off VCS remote refresh failures (#2686) 2026-05-14 08:41:02 +02:00
Theo Browne 34bb18c8cf feat(marketing): Made marketing site less cringe (#2681) 2026-05-13 18:31:06 -07:00
Julius Marminge 90eea047a9 Skip healthy env reconnects after browser resume (#2677) 2026-05-13 22:29:36 +02:00
Julius Marminge f92e1e1b06 Simplify workspace package builds and deps (#2676) 2026-05-13 21:35:01 +02:00
Julius Marminge 556c42452c Harden GitHub workflow permissions
- Restrict release workflow defaults to read-only access
- Grant `id-token` only to the publish job
- Document safe handling for `pull_request_target` in PR size checks
2026-05-13 14:19:18 +02:00
Julius Marminge 7e20b23e7e Constrain provider update popover overflow (#2669) 2026-05-13 10:23:31 +02:00
Julius Marminge b83e9c95e4 Refactor composer refs and context providers (#2664) 2026-05-12 21:54:28 +02:00
a41f4895ce Reduce chat timeline activity rerenders (#2660)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-12 20:56:03 +02:00
d15909af15 Use Effect child process for editor launches (#2659)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-12 20:15:11 +02:00
447236d51f Stabilize project grouping settings selector (#2629)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-05-11 10:07:50 +00:00
legsandJulius Marminge 5165b8c333 Optimize VCS diff loading to be up to 98% faster (#2586)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-11 12:07:26 +02:00
Julius Marmingeandcodex 8fc317939f Preserve Codex probe results across scoped teardown (#2638)
Co-authored-by: codex <[email protected]>
2026-05-11 10:48:19 +02:00
Julius Marminge 16c69ba7ff Remove outline styling from git success toast action (#2639) 2026-05-11 08:45:40 +00:00
Julius Marminge e64c19f1af Alias stable releases to the router domain (#2636) 2026-05-11 10:41:32 +02:00
Utkarsh Patil 6ab8f93a23 fix(codex): use longer and shared auth probe timeout for provider status check (#2616) 2026-05-11 00:29:56 -07:00
t3-code[bot] b793401aee chore(release): prepare v0.0.23 2026-05-09 22:22:22 +00:00
Julius MarmingeandJulius Marminge 3c32bc8fd1 [codex] Fix hosted channel bootstrap (#2613)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:57:16 -07:00
Julius MarmingeandJulius Marminge 6efdf67e15 [codex] Fix Vercel Turbo env forwarding (#2612)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:09:40 -07:00
Julius MarmingeandJulius Marminge 39371c6012 [codex] Fix Vercel release web deploy scope (#2611)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 22:01:57 -07:00
Kainoa NewtonandJulius Marminge 99efaa0faa Collapse long user messages by default (#2180)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-09 02:00:03 +00:00
Julius Marminge 6b9feb1bd3 Update deployment command in release workflow (#2610) 2026-05-08 18:30:44 -07:00
Ben Vargas e0f3abd1a4 Fix remote pairing CORS responses (#2594) 2026-05-08 23:52:47 +00:00
34ec8a86fb [codex] add configurable automatic git fetch interval (#2605)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-08 16:41:55 -07:00
932df4ed17 fix(ssh): fix reconnect issues and node binary path resolution (#2504)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-05-08 16:17:29 -07:00
Julius MarmingeandCursor Agent 63859aa072 perf: Add archived shell snapshot support (#2593)
Co-authored-by: Cursor Agent <[email protected]>
2026-05-08 15:49:41 -07:00
Julius MarmingeandJulius Marminge 7bfacd55d8 [codex] Handle NuGet provider bootstrap failures (#2608)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 15:20:02 -07:00
Kiri110K 271d65e047 Fix OpenCode raw text delta assembly (#2526) 2026-05-08 13:00:24 -07:00
196 changed files with 10521 additions and 4567 deletions

No files matched your search

+3
View File
@@ -124,6 +124,9 @@ jobs:
group: pr-size-${{ github.event.pull_request.number }}
cancel-in-progress: true
steps:
# This pull_request_target job may fetch untrusted PR commits only as passive
# git data. Do not add dependency installs, build/test scripts, or cache
# actions here; use pull_request plus workflow_run for that pattern instead.
- name: Checkout base repository
uses: actions/checkout@v4
with:
+30 -13
View File
@@ -23,8 +23,8 @@ on:
type: string
permissions:
contents: write
id-token: write
contents: read
id-token: none
jobs:
check_changes:
@@ -272,11 +272,16 @@ jobs:
exit 0
}
Install-PackageProvider `
-Name NuGet `
-MinimumVersion 2.8.5.201 `
-Force `
-Scope CurrentUser
try {
Install-PackageProvider `
-Name NuGet `
-MinimumVersion 2.8.5.201 `
-Force `
-Scope CurrentUser `
-ErrorAction Stop
} catch {
Write-Warning "Could not bootstrap NuGet package provider. Continuing because the runner may already have a usable provider. $($_.Exception.Message)"
}
Install-Module `
-Name TrustedSigning `
@@ -284,7 +289,8 @@ jobs:
-Force `
-AllowClobber `
-Repository PSGallery `
-Scope CurrentUser
-Scope CurrentUser `
-ErrorAction Stop
Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force
Get-Command Invoke-TrustedSigning -ErrorAction Stop
@@ -414,6 +420,9 @@ jobs:
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' }}
runs-on: ubuntu-24.04 # blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
permissions:
contents: read
id-token: write
steps:
- name: Checkout
uses: actions/checkout@v6
@@ -619,6 +628,9 @@ jobs:
router_url="${T3CODE_WEB_ROUTER_URL:-https://app.t3.codes}"
latest_domain="${T3CODE_WEB_LATEST_DOMAIN:-latest.app.t3.codes}"
nightly_domain="${T3CODE_WEB_NIGHTLY_DOMAIN:-nightly.app.t3.codes}"
router_domain="${router_url#http://}"
router_domain="${router_domain#https://}"
router_domain="${router_domain%%/*}"
if [[ "${{ needs.preflight.outputs.release_channel }}" == "stable" ]]; then
channel_domain="$latest_domain"
@@ -628,14 +640,12 @@ jobs:
channel_name="nightly"
fi
vercel_scope_args=()
if [[ -n "${VERCEL_TEAM_SLUG:-}" ]]; then
vercel_scope_args=(--scope "$VERCEL_TEAM_SLUG")
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
vercel_scope_args=(--scope "$vercel_scope")
echo "Deploying hosted web app for $channel_name channel."
deployment_url="$(
bunx [email protected] deploy apps/web \
bunx [email protected] deploy \
--prod \
--skip-domain \
--yes \
@@ -651,6 +661,13 @@ jobs:
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
bunx [email protected] alias set "$deployment_url" "$router_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
fi
finalize:
name: Finalize release
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' && needs.preflight.outputs.release_channel == 'stable' }}
+1
View File
@@ -23,5 +23,6 @@ __screenshots__/
.tanstack
squashfs-root/
.vercel
.gstack/
dist-electron/
.electron-runtime/
+37
View File
@@ -115,6 +115,43 @@ After setup, the renderer connects to a local forwarded HTTP/WebSocket endpoint.
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.
#### SSH Launch Troubleshooting
The desktop SSH launcher connects with a non-interactive `sh` session, writes a small launcher script under `~/.t3/ssh-launch/<host-key>/`, starts or reuses a remote T3 server, and forwards the remote loopback port back to your desktop.
The remote host must have a compatible Node.js runtime. T3 Code uses the server package's `engines.node` requirement:
```text
^22.16 || ^23.11 || >=24.10
```
During SSH launch, T3 Code first checks whether `node` is already available on `PATH`. If it is missing, the launcher tries common non-interactive shell locations and version-manager shims/activation hooks:
- `~/.local/bin`, `~/bin`, `/opt/homebrew/bin`, `/usr/local/bin`, `/usr/bin`, `/bin`
- Volta via `~/.volta/bin`
- asdf via `~/.asdf/shims`, `~/.asdf/bin`, or `~/.asdf/asdf.sh`
- mise via `~/.local/share/mise/shims`, `~/.mise/shims`, or `mise activate sh`
- fnm via `fnm env --use-on-cd --shell sh` or `fnm env --shell sh`
- nodenv via `~/.nodenv/bin`, `~/.nodenv/shims`, or `nodenv init -`
- nvm via `$NVM_DIR/nvm.sh`, then `nvm use default`, `nvm use node`, or `nvm use --lts`
- installed nvm versions under `$NVM_DIR/versions/node/*/bin`
If launch fails with `node: command not found`, a port-scan failure, or a message that the remote Node version does not satisfy the required range, SSH into the host and check the same non-interactive shell path T3 Code uses:
```bash
ssh [email protected] 'sh -lc "command -v node && node --version"'
```
If that does not print a compatible Node version, configure your version manager for non-interactive shells or install a compatible Node binary in one of the searched locations. For example, with nvm you may need a default alias:
```bash
nvm alias default 24
```
With mise/asdf/fnm/nodenv, make sure the tool's shim directory is installed and points at a Node version satisfying the range above.
If reconnecting after an app update fails, retry the SSH launch once. The launcher now compares its generated runner script, stops stale launcher-managed remote servers, clears the SSH launch PID/port state, and starts a fresh remote server. You should not normally need to delete `~/.t3/ssh-launch` or kill `t3` processes manually.
## How Pairing Works
The remote device does not need a long-lived secret up front.
+5 -7
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.22",
"version": "0.0.24",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -16,6 +16,10 @@
},
"dependencies": {
"@effect/platform-node": "catalog:",
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@t3tools/ssh": "workspace:*",
"@t3tools/tailscale": "workspace:*",
"effect": "catalog:",
"electron": "41.5.0",
"electron-updater": "^6.6.2"
@@ -23,13 +27,7 @@
"devDependencies": {
"@effect/language-service": "catalog:",
"@effect/vitest": "catalog:",
"@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:"
@@ -3,7 +3,7 @@ import * as NodeOS from "node:os";
import {
createAdvertisedEndpoint,
type CreateAdvertisedEndpointInput,
} from "@t3tools/client-runtime";
} from "@t3tools/shared/advertisedEndpoint";
import type {
AdvertisedEndpoint,
AdvertisedEndpointProvider,
@@ -1,4 +1,4 @@
import { createAdvertisedEndpoint } from "@t3tools/client-runtime";
import { createAdvertisedEndpoint } from "@t3tools/shared/advertisedEndpoint";
import type { AdvertisedEndpoint, AdvertisedEndpointProvider } from "@t3tools/contracts";
import {
buildTailscaleHttpsBaseUrl,
+6 -1
View File
@@ -11,6 +11,7 @@ import * as Electron from "electron";
import * as NetService from "@t3tools/shared/Net";
import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command";
import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel";
import serverPackageJson from "../../server/package.json" with { type: "json" };
import type { DesktopSettings as DesktopSettingsValue } from "./settings/DesktopAppSettings.ts";
import * as DesktopIpc from "./ipc/DesktopIpc.ts";
@@ -65,7 +66,10 @@ const resolveDesktopSshCliRunner = (
): RemoteT3RunnerOptions => {
const devRemoteEntryPath = Option.getOrUndefined(environment.devRemoteT3ServerEntryPath);
if (environment.isDevelopment && devRemoteEntryPath !== undefined) {
return { nodeScriptPath: devRemoteEntryPath };
return {
nodeScriptPath: devRemoteEntryPath,
nodeEngineRange: serverPackageJson.engines.node,
};
}
return {
packageSpec: resolveRemoteT3CliPackageSpec({
@@ -73,6 +77,7 @@ const resolveDesktopSshCliRunner = (
updateChannel: settings.updateChannel,
isDevelopment: environment.isDevelopment,
}),
nodeEngineRange: serverPackageJson.engines.node,
};
};
+1 -1
View File
@@ -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,
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 244 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 358 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="257" preserveAspectRatio="xMidYMid" viewBox="0 0 256 257"><path fill="#D97757" d="m50.228 170.321 50.357-28.257.843-2.463-.843-1.361h-2.462l-8.426-.518-28.775-.778-24.952-1.037-24.175-1.296-6.092-1.297L0 125.796l.583-3.759 5.12-3.434 7.324.648 16.202 1.101 24.304 1.685 17.629 1.037 26.118 2.722h4.148l.583-1.685-1.426-1.037-1.101-1.037-25.147-17.045-27.22-18.017-14.258-10.37-7.713-5.25-3.888-4.925-1.685-10.758 7-7.713 9.397.649 2.398.648 9.527 7.323 20.35 15.75L94.817 91.9l3.889 3.24 1.555-1.102.195-.777-1.75-2.917-14.453-26.118-15.425-26.572-6.87-11.018-1.814-6.61c-.648-2.723-1.102-4.991-1.102-7.778l7.972-10.823L71.42 0 82.05 1.426l4.472 3.888 6.61 15.101 10.694 23.786 16.591 32.34 4.861 9.592 2.592 8.879.973 2.722h1.685v-1.556l1.36-18.211 2.528-22.36 2.463-28.776.843-8.1 4.018-9.722 7.971-5.25 6.222 2.981 5.12 7.324-.713 4.73-3.046 19.768-5.962 30.98-3.889 20.739h2.268l2.593-2.593 10.499-13.934 17.628-22.036 7.778-8.749 9.073-9.657 5.833-4.601h11.018l8.1 12.055-3.628 12.443-11.342 14.388-9.398 12.184-13.48 18.147-8.426 14.518.778 1.166 2.01-.194 30.46-6.481 16.462-2.982 19.637-3.37 8.88 4.148.971 4.213-3.5 8.62-20.998 5.184-24.628 4.926-36.682 8.685-.454.324.519.648 16.526 1.555 7.065.389h17.304l32.21 2.398 8.426 5.574 5.055 6.805-.843 5.184-12.962 6.611-17.498-4.148-40.83-9.721-14-3.5h-1.944v1.167l11.666 11.406 21.387 19.314 26.767 24.887 1.36 6.157-3.434 4.86-3.63-.518-23.526-17.693-9.073-7.972-20.545-17.304h-1.36v1.814l4.73 6.935 25.017 37.59 1.296 11.536-1.814 3.76-6.481 2.268-7.13-1.297-14.647-20.544-15.1-23.138-12.185-20.739-1.49.843-7.194 77.448-3.37 3.953-7.778 2.981-6.48-4.925-3.436-7.972 3.435-15.749 4.148-20.544 3.37-16.333 3.046-20.285 1.815-6.74-.13-.454-1.49.194-15.295 20.999-23.267 31.433-18.406 19.702-4.407 1.75-7.648-3.954.713-7.064 4.277-6.286 25.47-32.405 15.36-20.092 9.917-11.6-.065-1.686h-.583L44.07 198.125l-12.055 1.555-5.185-4.86.648-7.972 2.463-2.593 20.35-13.999-.064.065Z"></path></svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

@@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?><svg id="cursor_light__Ebene_1" xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0 0 466.73 532.09"><defs></defs><path class="cursor_light__st0" d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"></path></svg>

After

Width:  |  Height:  |  Size: 649 B

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="256" height="260" preserveAspectRatio="xMidYMid" viewBox="0 0 256 260"><path fill="#fff" d="M239.184 106.203a64.716 64.716 0 0 0-5.576-53.103C219.452 28.459 191 15.784 163.213 21.74A65.586 65.586 0 0 0 52.096 45.22a64.716 64.716 0 0 0-43.23 31.36c-14.31 24.602-11.061 55.634 8.033 76.74a64.665 64.665 0 0 0 5.525 53.102c14.174 24.65 42.644 37.324 70.446 31.36a64.72 64.72 0 0 0 48.754 21.744c28.481.025 53.714-18.361 62.414-45.481a64.767 64.767 0 0 0 43.229-31.36c14.137-24.558 10.875-55.423-8.083-76.483Zm-97.56 136.338a48.397 48.397 0 0 1-31.105-11.255l1.535-.87 51.67-29.825a8.595 8.595 0 0 0 4.247-7.367v-72.85l21.845 12.636c.218.111.37.32.409.563v60.367c-.056 26.818-21.783 48.545-48.601 48.601Zm-104.466-44.61a48.345 48.345 0 0 1-5.781-32.589l1.534.921 51.722 29.826a8.339 8.339 0 0 0 8.441 0l63.181-36.425v25.221a.87.87 0 0 1-.358.665l-52.335 30.184c-23.257 13.398-52.97 5.431-66.404-17.803ZM23.549 85.38a48.499 48.499 0 0 1 25.58-21.333v61.39a8.288 8.288 0 0 0 4.195 7.316l62.874 36.272-21.845 12.636a.819.819 0 0 1-.767 0L41.353 151.53c-23.211-13.454-31.171-43.144-17.804-66.405v.256Zm179.466 41.695-63.08-36.63L161.73 77.86a.819.819 0 0 1 .768 0l52.233 30.184a48.6 48.6 0 0 1-7.316 87.635v-61.391a8.544 8.544 0 0 0-4.4-7.213Zm21.742-32.69-1.535-.922-51.619-30.081a8.39 8.39 0 0 0-8.492 0L99.98 99.808V74.587a.716.716 0 0 1 .307-.665l52.233-30.133a48.652 48.652 0 0 1 72.236 50.391v.205ZM88.061 139.097l-21.845-12.585a.87.87 0 0 1-.41-.614V65.685a48.652 48.652 0 0 1 79.757-37.346l-1.535.87-51.67 29.825a8.595 8.595 0 0 0-4.246 7.367l-.051 72.697Zm11.868-25.58 28.138-16.217 28.188 16.218v32.434l-28.086 16.218-28.188-16.218-.052-32.434Z"></path></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" width="512" height="512"><svg width="512" height="512" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg"><rect width="512" height="512" fill="#131010"></rect><path d="M320 224V352H192V224H320Z" fill="#5A5858"></path><path fill-rule="evenodd" clip-rule="evenodd" d="M384 416H128V96H384V416ZM320 160H192V352H320V160Z" fill="white"></path></svg></svg>

After

Width:  |  Height:  |  Size: 464 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 138 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 110 KiB

@@ -0,0 +1,53 @@
---
interface Props {
class?: string;
idPrefix: string;
}
const { class: className, idPrefix } = Astro.props;
---
<svg
class={className}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 256 295"
aria-hidden="true"
>
<defs>
<linearGradient id={`${idPrefix}0`} x1="48.548%" x2="51.047%" y1="115.276%" y2="41.364%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}6`} x1="49.984%" x2="49.984%" y1="89.845%" y2="40.632%">
<stop offset="0%" stop-color="#FFEED7" />
<stop offset="100%" stop-color="#BDBFC2" />
</linearGradient>
<linearGradient id={`${idPrefix}8`} x1="49.841%" x2="50.241%" y1="13.229%" y2="94.673%">
<stop offset="0%" stop-color="#FFF" stop-opacity=".8" />
<stop offset="100%" stop-color="#FFF" stop-opacity="0" />
</linearGradient>
<linearGradient id={`${idPrefix}c`} x1="53.467%" x2="38.949%" y1="48.921%" y2="98.1%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}e`} x1="30.581%" x2="65.887%" y1="34.024%" y2="89.175%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
<linearGradient id={`${idPrefix}i`} x1="49.733%" x2="50.558%" y1="17.609%" y2="99.385%">
<stop offset="0%" stop-color="#FFA63F" />
<stop offset="100%" stop-color="#FF0" />
</linearGradient>
</defs>
<g fill="none">
<path fill="#000" d="M63.213 215.474c-11.387-16.346-13.591-69.606 12.947-102.39C89.292 97.383 92.69 86.455 93.7 71.67c.734-16.805-11.846-66.851 35.537-70.616 48.027-3.857 45.364 43.526 45.088 68.596-.183 21.12 15.52 33.15 26.355 49.68 19.927 30.303 18.274 82.461-3.765 110.745-27.916 35.354-51.791 20.018-67.678 21.304-29.752 1.745-30.762 17.54-66.024-35.905" />
<path fill={`url(#${idPrefix}6)`} d="M81.027 145.684c6.52-14.785 20.386-40.772 20.662-60.883 0-15.978 47.843-19.835 51.7-3.856 3.856 15.978 13.59 39.853 19.834 51.424 6.245 11.478 24.335 48.118 5.051 80.074-17.356 28.284-69.973 50.69-98.073-3.856-9.55-18.917-7.806-42.333.826-62.903" />
<path fill={`url(#${idPrefix}8)`} d="M166.428 151.285c0 16.162-15.519 37.1-42.15 36.916-27.456.183-39.118-20.754-39.118-36.916 0-16.161 18.182-29.293 40.588-29.293 22.498.092 40.68 13.132 40.68 29.293" />
<path fill="#000" stroke="#000" stroke-width=".977" d="M176.805 117.86c13.59 11.02 38.292 49.587 2.204 74.748-11.846 7.806 10.468 32.508 23.049 19.927 43.618-43.894-1.102-94.308-16.53-111.664-13.774-15.151-25.987 3.49-8.723 16.989z" />
<path fill="#000" stroke="#000" stroke-width="1.25" d="M79.925 122.727c-8.907 14.509-30.211 48.669-1.652 66.484 38.384 23.6 27.548 47.108-7.53 25.895-49.404-29.568-5.97-89.257 13.774-112.03 22.59-25.529 4.316 4.683-4.592 19.65z" />
<path fill={`url(#${idPrefix}c)`} stroke="#E68C3F" stroke-width="6.25" d="M51.835 258.542c-20.57-10.928-50.414 2.112-39.578-27.457 2.204-6.704-3.214-16.805.275-23.325 4.133-7.989 13.04-6.244 18.366-11.57 5.234-5.51 8.54-15.06 18.366-13.59 9.734 1.468 16.254 13.406 23.049 28.099 5.05 10.468 22.865 25.253 21.672 37.007-1.47 17.998-21.948 21.396-42.15 10.836z" transform="translate(10)" />
<path fill={`url(#${idPrefix}e)`} stroke="#E68C3F" stroke-width="6.251" d="M194.445 253.49c15.06-18.273 48.578-14.508 25.988-39.577-4.775-5.418-3.306-16.989-9.183-21.947-6.887-6.061-14.509-1.102-21.488-4.224-6.979-3.398-14.325-9.918-22.865-5.327-8.54 4.684-9.459 16.805-10.285 32.783-.735 11.479-11.203 30.671-5.602 41.231 8.081 16.346 29.11 14.142 43.435-2.938z" transform="translate(10)" />
<path fill={`url(#${idPrefix}i)`} stroke="#E68C3F" stroke-width="3.75" d="M97.107 66.344c3.673-3.398 12.58-13.774 29.477-2.939 3.122 2.02 5.693 2.204 11.662 4.775 12.03 4.96 6.336 16.897-6.52 20.937-5.51 1.745-10.468 8.449-20.386 7.806-8.54-.46-10.744-6.06-15.978-9.091-9.275-5.234-10.652-12.305-5.602-16.07 5.051-3.765 6.98-5.143 7.347-5.418z" transform="translate(10)" />
<path fill="#000" d="M133.186 57.712c-.092 5.234 2.48 9.458 5.877 9.458 3.306 0 6.153-4.224 6.245-9.366.091-5.234-2.48-9.459-5.878-9.459-3.397 0-6.152 4.225-6.244 9.367m-21.212.092c.459 4.316-1.194 7.989-3.582 8.356-2.387.276-4.683-2.938-5.142-7.254-.46-4.316 1.194-7.99 3.581-8.357 2.388-.275 4.684 2.939 5.143 7.255" />
</g>
</svg>
+254 -72
View File
@@ -6,7 +6,7 @@ interface Props {
const {
title = "T3 Code",
description = "T3 Code — The best way to code with AI.",
description = "T3 Code — The open-source control plane for coding agents.",
} = Astro.props;
---
@@ -18,7 +18,7 @@ const {
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&display=swap"
href="https://fonts.googleapis.com/css2?family=DM+Sans:opsz,[email protected],400;9..40,500;9..40,600&family=JetBrains+Mono:wght@400;500&display=swap"
rel="stylesheet"
/>
<link rel="icon" href="/favicon.ico" sizes="48x48" />
@@ -30,18 +30,25 @@ const {
<body>
<div class="page">
<nav class="nav">
<a href="/" class="nav-brand">
<img src="/icon.png" alt="T3" class="nav-icon" />
</a>
<a
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
class="nav-github"
>
GitHub
<span class="nav-github-arrow" aria-hidden="true">&#8599;</span>
</a>
<div class="nav-inner">
<a href="/" class="nav-brand" aria-label="T3 Code home">
<span class="nav-brand-name">T3 Code</span>
</a>
<div class="nav-right">
<a
class="nav-gh"
href="https://github.com/pingdotgg/t3code"
target="_blank"
rel="noopener noreferrer"
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
<path d="M12 .5C5.65.5.5 5.65.5 12a11.5 11.5 0 007.86 10.93c.58.1.79-.25.79-.56v-2c-3.2.69-3.88-1.37-3.88-1.37-.52-1.33-1.27-1.69-1.27-1.69-1.04-.71.08-.7.08-.7 1.15.08 1.76 1.18 1.76 1.18 1.02 1.76 2.68 1.25 3.33.96.1-.75.4-1.25.72-1.54-2.55-.29-5.24-1.27-5.24-5.67 0-1.25.45-2.28 1.18-3.08-.12-.29-.51-1.45.11-3.02 0 0 .96-.31 3.15 1.18a10.96 10.96 0 015.74 0c2.19-1.49 3.15-1.18 3.15-1.18.62 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.08 0 4.41-2.7 5.38-5.27 5.66.41.36.78 1.06.78 2.13v3.16c0 .31.21.67.8.56A11.5 11.5 0 0023.5 12C23.5 5.65 18.35.5 12 .5z"/>
</svg>
<span>GitHub</span>
</a>
<a class="btn btn-primary" href="/#download">Download</a>
</div>
</div>
</nav>
<main class="main">
@@ -49,23 +56,54 @@ const {
</main>
<footer class="footer">
<span class="footer-copy">&copy; {new Date().getFullYear()} T3 Tools Inc</span>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<div class="footer-inner">
<div class="footer-brand">
<img src="/icon.webp" alt="" />
<span>&copy; {new Date().getFullYear()} T3 Tools Inc · MIT licensed</span>
</div>
<div class="footer-links">
<a href="https://github.com/pingdotgg/t3code" target="_blank" rel="noopener noreferrer">GitHub</a>
<a href="https://discord.gg/jn4EGJjrvv" target="_blank" rel="noopener noreferrer">Discord</a>
<a href="/download">Download</a>
</div>
</div>
</footer>
</div>
<script>
const nav = document.querySelector(".nav");
const onScroll = () => {
if (!nav) return;
if (window.scrollY > 12) nav.classList.add("is-scrolled");
else nav.classList.remove("is-scrolled");
};
window.addEventListener("scroll", onScroll, { passive: true });
onScroll();
</script>
</body>
</html>
<style is:global>
:root {
--bg: #09090b;
--bg-elev: #0c0c0e;
--bg-card: #111113;
--fg: #fafafa;
--fg-muted: #a1a1aa;
--fg-dim: #71717a;
--fg-faint: #52525b;
--border: rgba(255, 255, 255, 0.08);
--border-strong: rgba(255, 255, 255, 0.14);
--accent-h: 250;
--accent: oklch(0.68 0.17 var(--accent-h));
--accent-dim: oklch(0.68 0.17 var(--accent-h) / 0.15);
--ok: oklch(0.72 0.16 150);
--warn: oklch(0.76 0.15 75);
--font-sans: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, Monaco, monospace;
--radius: 12px;
--radius-sm: 8px;
--radius-lg: 16px;
}
* {
@@ -76,16 +114,19 @@ const {
html {
color-scheme: dark;
scroll-behavior: smooth;
}
body {
background: var(--bg);
color: var(--fg);
font-family: "DM Sans", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
font-family: var(--font-sans);
font-feature-settings: "ss01", "ss02";
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
min-height: 100vh;
overflow-x: hidden;
line-height: 1.5;
}
body::after {
@@ -105,11 +146,103 @@ const {
text-decoration: none;
}
img {
button {
font-family: inherit;
cursor: pointer;
border: 0;
background: none;
color: inherit;
}
img,
svg {
display: block;
max-width: 100%;
}
.eyebrow {
font-family: var(--font-mono);
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--fg-dim);
font-weight: 500;
}
.display {
font-weight: 500;
letter-spacing: -0.035em;
line-height: 1.05;
}
.container {
width: 100%;
max-width: 1240px;
margin: 0 auto;
padding: 0 32px;
}
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
font-weight: 500;
font-size: 14px;
padding: 10px 18px;
border-radius: 8px;
transition: transform 0.18s ease, background 0.18s ease,
border-color 0.18s ease, color 0.18s ease;
white-space: nowrap;
}
.btn-primary {
background: var(--fg);
color: #09090b;
font-weight: 600;
}
.btn-primary:hover {
transform: translateY(-1px);
background: #fff;
}
.btn-primary:active {
transform: translateY(0);
}
.btn-ghost {
color: var(--fg-muted);
border: 1px solid var(--border);
background: transparent;
}
.btn-ghost:hover {
color: var(--fg);
border-color: var(--border-strong);
background: rgba(255, 255, 255, 0.02);
}
.btn-lg {
padding: 14px 22px;
font-size: 15px;
border-radius: 10px;
}
.tile {
position: relative;
border: 1px solid var(--border);
border-radius: var(--radius);
background: linear-gradient(180deg, rgba(255, 255, 255, 0.015), rgba(255, 255, 255, 0));
overflow: hidden;
}
:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
border-radius: 4px;
}
@keyframes fade-in {
from {
opacity: 0;
@@ -120,11 +253,26 @@ const {
transform: translateY(0);
}
}
@keyframes pulse {
50% { opacity: 0.4; }
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@keyframes floatDrift {
0%, 100% { translate: 0 0; }
50% { translate: 0 -10px; }
}
@keyframes blink {
50% { opacity: 0; }
}
</style>
<style>
/* ── Page ── */
.page {
min-height: 100vh;
display: flex;
@@ -132,97 +280,131 @@ const {
overflow-x: hidden;
}
/* ── Navbar ── */
.nav {
position: sticky;
top: 0;
z-index: 50;
backdrop-filter: blur(18px);
-webkit-backdrop-filter: blur(18px);
background: color-mix(in srgb, var(--bg) 75%, transparent);
border-bottom: 1px solid transparent;
transition: border-color 0.3s ease;
}
.nav.is-scrolled {
border-bottom-color: var(--border);
}
.nav-inner {
max-width: 1240px;
margin: 0 auto;
padding: 12px 32px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
opacity: 0.5;
transition: opacity 0.4s ease;
}
.nav:hover {
opacity: 1;
gap: 24px;
}
.nav-brand {
display: flex;
display: inline-flex;
align-items: center;
}
.nav-icon {
width: 28px;
height: 28px;
border-radius: 6px;
}
.nav-github {
display: flex;
align-items: center;
gap: 0.35rem;
color: var(--fg-muted);
font-size: 0.875rem;
transition: color 0.3s ease;
}
.nav-github:hover {
color: var(--fg);
transition: color 0.2s ease;
}
.nav-github-arrow {
display: inline-block;
transition: transform 0.3s ease;
.nav-brand:hover {
color: #fff;
}
.nav-github:hover .nav-github-arrow {
transform: translateX(2px) translateY(-1px);
.nav-brand-name {
font-size: 16px;
font-weight: 650;
letter-spacing: -0.025em;
line-height: 1;
}
/* ── Main content ── */
.nav-right {
display: inline-flex;
align-items: center;
gap: 8px;
}
.nav-gh {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 12px;
border: 1px solid var(--border);
border-radius: 8px;
color: var(--fg-muted);
font-family: var(--font-mono);
font-size: 12px;
transition: color 0.2s ease, background 0.2s ease, border-color 0.2s ease;
}
.nav-gh:hover {
color: var(--fg);
background: rgba(255, 255, 255, 0.04);
border-color: var(--border-strong);
}
.main {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
}
/* ── Footer ── */
.footer {
margin-top: auto;
border-top: 1px solid var(--border);
padding: 40px 0 32px;
}
.footer-inner {
max-width: 1240px;
margin: 0 auto;
padding: 0 32px;
display: flex;
flex-wrap: wrap;
gap: 24px;
align-items: center;
justify-content: space-between;
padding: 1.5rem 2.5rem;
font-size: 0.8rem;
}
.footer-brand {
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
color: var(--fg-dim);
}
.footer-brand img {
width: 20px;
height: 20px;
border-radius: 4px;
}
.footer-links {
display: flex;
gap: 1.25rem;
gap: 20px;
}
.footer-links a {
font-size: 13px;
color: var(--fg-dim);
transition: color 0.3s ease;
transition: color 0.2s ease;
}
.footer-links a:hover {
color: var(--fg);
}
/* ── Mobile ── */
@media (max-width: 640px) {
.nav {
padding: 1.25rem;
}
.footer {
padding: 1.25rem;
@media (max-width: 820px) {
.nav-inner,
.footer-inner {
padding-left: 20px;
padding-right: 20px;
}
}
</style>
+123
View File
@@ -0,0 +1,123 @@
export type Tweet = {
handle: string;
content: string;
excerpt?: string;
link: string;
};
export const tweets = [
{
handle: "Shay_Benshabtay",
content:
"T3 code is not perfect, but it's damn good. Open and fun , I can make my own fork for my uses and use the great tooling with my own needs.",
link: "https://x.com/Shay_Benshabtay/status/2054668503857156326",
},
{
handle: "teja2495",
content:
"I’ve completely switched to T3 Code for all my workflows. I just switch between different subscriptions and harnesses depending on what I need.",
excerpt: "I’ve completely switched to T3 Code for all my workflows.",
link: "https://x.com/teja2495/status/2052420254991581623",
},
{
handle: "developedbyed",
content: "might say alpha but T3 code is pretty awesome, really fast too",
link: "https://x.com/developedbyed/status/2030627970532921605",
},
{
handle: "tannerlinsley",
content:
"The minute T3 Code supports Claude Code, it could potentially become my daily driver. There's something special there.",
link: "https://x.com/tannerlinsley/status/2031102771529920966",
},
{
handle: "aronprins",
content:
"I already loved T3 Code by @theo and @jullerino, but their Connections implementation is next level epic and for this they should both earn maximum repect 🔥🫡",
excerpt: "I already loved T3 Code, but their Connections implementation is next level epic.",
link: "https://x.com/aronprins/status/2045102518196183109",
},
{
handle: "BennettBuhner",
content:
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere! The app is great but the website is even greater, so instead of needing to SSH into a machine, T3 IS my SSH!",
excerpt:
"T3 Code is literally Codex but better; all your favorite models and harnesses, accessible anywhere.",
link: "https://x.com/BennettBuhner/status/2054667115697754387",
},
{
handle: "ex0t1clol",
content: "T3 Code is proof electron apps don't have to suck",
link: "https://x.com/ex0t1clol/status/2054666870008021197",
},
{
handle: "Josikinz",
content:
"T3 code is better because it’s like if the codex Mac app didn’t make my computer run like shit 😋",
link: "https://x.com/Josikinz/status/2030367951694745870",
},
{
handle: "jetpackjoe_",
content: "T3 code is pretty alright I guess",
link: "https://x.com/jetpackjoe_/status/2054666792933404959",
},
{
handle: "mil000",
content: "T3 code saved my relationship!",
link: "https://x.com/mil000/status/2030120041451246071",
},
{
handle: "_winter_wonders",
content: "Heartbreaking: AI-hater has to admit T3 Code is really good.",
link: "https://x.com/_winter_wonders/status/2052350198764970434",
},
{
handle: "kostyniuk00",
content:
"I was not expecting a year ago, that my anti-AI colleagues would thank me a year later, for persuading them to try T3 Code Beta, that really helped them with organizing their workflows. \n\nFantastic product by @jullerino and @theo. Go try it out if you haven’t yet!",
excerpt:
"My anti-AI colleagues thanked me for persuading them to try T3 Code Beta. Fantastic product.",
link: "https://x.com/kostyniuk00/status/2052041388179468521",
},
{
handle: "gnukeith",
content:
"I tried T3 Code it actually fixed issues that Opus couldn’t solve in Claude Code + Theo has replied with “UwU” under my post. Dario has not.",
link: "https://x.com/gnukeith/status/2054670073579630730",
},
{
handle: "peculiarnewbie",
content: "T3 Code is iOS and other harnesses are androids",
link: "https://x.com/peculiarnewbie/status/2054671685027233827",
},
{
handle: "leodev",
content:
"T3 Code is probably the first coding gui that didn't suck performance wise and had a smart team behind it.",
link: "https://x.com/leodev/status/2054679746353537042",
},
{
handle: "pocarles",
content:
"Only using Codex and T3 now.\n\nI thought all AI coding harnesses had roughly the same impact. Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
excerpt:
"Using T3 Code taught me how wrong I was. The interface between you and the model changes everything.",
link: "https://x.com/pocarles/status/2054673964274758046",
},
{
handle: "DavidKPiano",
content: "It's like Claude Code if they didn't vibe-code the entire thing",
link: "https://x.com/DavidKPiano/status/2054682983504719930",
},
{
handle: "iamkaffe",
content: "T3Code was the first one to truly care about Linux users.",
link: "https://x.com/iamkaffe/status/2054675539311411280",
},
{
handle: "uwunetes",
content:
"claude code make me go *whine whine whine* and t3 code make me go woof woof awooooo!!!",
link: "https://x.com/uwunetes/status/2054683356022120640",
},
] satisfies Tweet[];
+8 -2
View File
@@ -4,6 +4,7 @@ import { RELEASES_URL } from "../lib/releases";
---
<Layout title="Download — T3 Code" description="Download T3 Code for macOS, Windows, or Linux.">
<div class="download-page">
<h1 class="heading">Download T3 Code</h1>
<p class="subheading">
<span id="version-label">Loading latest release&hellip;</span>
@@ -64,6 +65,7 @@ import { RELEASES_URL } from "../lib/releases";
GitHub releases page<span aria-hidden="true"> &#8599;</span>
</a>
</p>
</div>
</Layout>
<script>
@@ -111,7 +113,11 @@ import { RELEASES_URL } from "../lib/releases";
</script>
<style>
.main {
.download-page {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
padding: 8vh 1.5rem 4rem;
}
@@ -257,7 +263,7 @@ import { RELEASES_URL } from "../lib/releases";
/* ── Mobile ── */
@media (max-width: 640px) {
.main {
.download-page {
padding: 5vh 1.25rem 4rem;
}
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
https://x.com/Shay_Benshabtay/status/2054668503857156326
https://x.com/teja2495/status/2052420254991581623
https://x.com/developedbyed/status/2030627970532921605
https://x.com/tannerlinsley/status/2031102771529920966
https://x.com/aronprins/status/2045102518196183109
https://x.com/BennettBuhner/status/2054667115697754387
https://x.com/ex0t1clol/status/2054666870008021197
https://x.com/Josikinz/status/2030367951694745870
https://x.com/jetpackjoe_/status/2054666792933404959
https://x.com/mil000/status/2030120041451246071
https://x.com/_winter_wonders/status/2052350198764970434
https://x.com/kostyniuk00/status/2052041388179468521
https://x.com/gnukeith/status/2054670073579630730
https://x.com/peculiarnewbie/status/2054671685027233827
https://x.com/leodev/status/2054679746353537042
https://x.com/pocarles/status/2054673964274758046
https://x.com/DavidKPiano/status/2054682983504719930
https://x.com/iamkaffe/status/2054675539311411280
https://x.com/uwunetes/status/2054683356022120640
@@ -73,7 +73,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";
@@ -311,8 +310,11 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(serverSettingsLayer),
);
const gitWorkflowLayer = Layer.mock(GitWorkflowService)({
renameBranch: (input: Parameters<GitVcsDriver.GitVcsDriverShape["renameBranch"]>[0]) =>
Effect.succeed({ branch: input.newBranch }),
renameBranch: (input: {
readonly cwd: string;
readonly oldBranch: string;
readonly newBranch: string;
}) => Effect.succeed({ branch: input.newBranch }),
});
const textGenerationLayer = Layer.succeed(TextGeneration, {
generateBranchName: () => Effect.succeed({ branch: "update" }),
+4 -5
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.22",
"version": "0.0.24",
"license": "MIT",
"repository": {
"type": "git",
@@ -20,19 +20,18 @@
"build:bundle": "tsdown",
"start": "node dist/bin.mjs",
"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",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/platform-node-shared": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@opencode-ai/sdk": "^1.3.15",
"@pierre/diffs": "catalog:",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0"
"node-pty": "^1.1.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
+12 -3
View File
@@ -14,6 +14,7 @@ import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstab
import { AuthError, ServerAuth } from "./Services/ServerAuth.ts";
import { SessionCredentialService } from "./Services/SessionCredentialService.ts";
import { deriveAuthClientMetadata } from "./utils.ts";
import { browserApiCorsHeaders } from "../httpCors.ts";
export const respondToAuthError = (error: AuthError) =>
Effect.gen(function* () {
@@ -27,7 +28,7 @@ export const respondToAuthError = (error: AuthError) =>
{
error: error.message,
},
{ status: error.status ?? 500 },
{ status: error.status ?? 500, headers: browserApiCorsHeaders },
);
});
@@ -38,7 +39,10 @@ export const authSessionRouteLayer = HttpRouter.add(
const request = yield* HttpServerRequest.HttpServerRequest;
const serverAuth = yield* ServerAuth;
const session = yield* serverAuth.getSessionState(request);
return HttpServerResponse.jsonUnsafe(session, { status: 200 });
return HttpServerResponse.jsonUnsafe(session, {
status: 200,
headers: browserApiCorsHeaders,
});
}),
);
@@ -81,7 +85,10 @@ export const authBootstrapRouteLayer = HttpRouter.add(
deriveAuthClientMetadata({ request }),
);
return yield* HttpServerResponse.jsonUnsafe(result.response, { status: 200 }).pipe(
return yield* HttpServerResponse.jsonUnsafe(result.response, {
status: 200,
headers: browserApiCorsHeaders,
}).pipe(
HttpServerResponse.setCookie(sessions.cookieName, result.sessionToken, {
expires: DateTime.toDate(result.response.expiresAt),
httpOnly: true,
@@ -114,6 +121,7 @@ export const authBearerBootstrapRouteLayer = HttpRouter.add(
);
return HttpServerResponse.jsonUnsafe(result satisfies AuthBearerBootstrapResult, {
status: 200,
headers: browserApiCorsHeaders,
});
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
);
@@ -128,6 +136,7 @@ export const authWebSocketTokenRouteLayer = HttpRouter.add(
const result = yield* serverAuth.issueWebSocketToken(session);
return HttpServerResponse.jsonUnsafe(result satisfies AuthWebSocketTokenResult, {
status: 200,
headers: browserApiCorsHeaders,
});
}).pipe(Effect.catchTag("AuthError", (error) => respondToAuthError(error))),
);
@@ -41,11 +41,110 @@ function makeThreadCheckpointContext(input: {
}
describe("CheckpointDiffQueryLive", () => {
it("uses the narrow full-thread context lookup for all-turns diffs", async () => {
const projectId = ProjectId.make("project-full-thread");
const threadId = ThreadId.make("thread-full-thread");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 4);
let getThreadCheckpointContextCalls = 0;
let getFullThreadDiffContextCalls = 0;
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
readonly cwd: string;
readonly ignoreWhitespace: boolean;
}> = [];
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
diffCheckpointsCalls.push({
fromCheckpointRef,
toCheckpointRef,
cwd,
ignoreWhitespace,
});
return "full thread 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"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
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.sync(() => {
getThreadCheckpointContextCalls += 1;
return Option.none();
}),
getFullThreadDiffContext: () =>
Effect.sync(() => {
getFullThreadDiffContextCalls += 1;
return Option.some({
threadId,
projectId,
workspaceRoot: "/tmp/workspace",
worktreePath: "/tmp/worktree",
latestCheckpointTurnCount: 4,
toCheckpointRef,
});
}),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
),
);
const result = await Effect.runPromise(
Effect.gen(function* () {
const query = yield* CheckpointDiffQuery;
return yield* query.getFullThreadDiff({
threadId,
toTurnCount: 4,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
expect(getThreadCheckpointContextCalls).toBe(0);
expect(getFullThreadDiffContextCalls).toBe(1);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/worktree",
fromCheckpointRef: checkpointRefForThreadTurn(threadId, 0),
toCheckpointRef,
ignoreWhitespace: true,
},
]);
expect(result).toEqual({
threadId,
fromTurnCount: 0,
toTurnCount: 4,
diff: "full thread diff patch",
});
});
it("computes diffs using canonical turn-0 checkpoint refs", async () => {
const projectId = ProjectId.make("project-1");
const threadId = ThreadId.make("thread-1");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
const hasCheckpointRefCalls: Array<CheckpointRef> = [];
const diffCheckpointsCalls: Array<{
readonly fromCheckpointRef: CheckpointRef;
readonly toCheckpointRef: CheckpointRef;
@@ -65,11 +164,7 @@ describe("CheckpointDiffQueryLive", () => {
const checkpointStore: CheckpointStoreShape = {
isGitRepository: () => Effect.succeed(true),
captureCheckpoint: () => Effect.void,
hasCheckpointRef: ({ checkpointRef }) =>
Effect.sync(() => {
hasCheckpointRefCalls.push(checkpointRef);
return true;
}),
hasCheckpointRef: () => Effect.succeed(true),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: ({ fromCheckpointRef, toCheckpointRef, cwd, ignoreWhitespace }) =>
Effect.sync(() => {
@@ -94,12 +189,15 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
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)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -119,7 +217,6 @@ describe("CheckpointDiffQueryLive", () => {
);
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/workspace",
@@ -174,12 +271,15 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
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)),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -200,6 +300,74 @@ describe("CheckpointDiffQueryLive", () => {
expect(diffCheckpointsCalls).toEqual([{ ignoreWhitespace: true }]);
});
it("does not preflight checkpoint refs before diffing", async () => {
const projectId = ProjectId.make("project-no-preflight");
const threadId = ThreadId.make("thread-no-preflight");
const toCheckpointRef = checkpointRefForThreadTurn(threadId, 1);
let hasCheckpointRefCallCount = 0;
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.sync(() => {
hasCheckpointRefCallCount += 1;
return true;
}),
restoreCheckpoint: () => Effect.succeed(true),
diffCheckpoints: () => Effect.succeed("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"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
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)),
getFullThreadDiffContext: () => Effect.die("unused"),
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,
ignoreWhitespace: true,
});
}).pipe(Effect.provide(layer)),
);
expect(hasCheckpointRefCallCount).toBe(0);
});
it("fails when the thread is missing from the snapshot", async () => {
const threadId = ThreadId.make("thread-missing");
@@ -222,12 +390,15 @@ describe("CheckpointDiffQueryLive", () => {
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the orchestration shell snapshot"),
getArchivedShellSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request archived shell snapshots"),
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()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -1,6 +1,7 @@
import {
type CheckpointRef,
OrchestrationGetTurnDiffResult,
type OrchestrationGetFullThreadDiffInput,
type ThreadId,
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
@@ -20,6 +21,22 @@ import {
const isTurnDiffResult = Schema.is(OrchestrationGetTurnDiffResult);
function buildTurnDiffResult(
input: {
readonly threadId: ThreadId;
readonly fromTurnCount: number;
readonly toTurnCount: number;
},
diff: string,
): OrchestrationGetTurnDiffResultType {
return {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
}
const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
@@ -28,6 +45,12 @@ const make = Effect.gen(function* () {
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
yield* Effect.annotateCurrentSpan({
"checkpoint.thread_id": input.threadId,
"checkpoint.from_turn_count": input.fromTurnCount,
"checkpoint.to_turn_count": input.toTurnCount,
"checkpoint.ignore_whitespace": ignoreWhitespace,
});
if (input.fromTurnCount === input.toTurnCount) {
const emptyDiff: OrchestrationGetTurnDiffResultType = {
@@ -45,9 +68,9 @@ const make = Effect.gen(function* () {
return emptyDiff;
}
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
input.threadId,
);
const threadContext = yield* projectionSnapshotQuery
.getThreadCheckpointContext(input.threadId)
.pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
@@ -100,50 +123,17 @@ const make = Effect.gen(function* () {
});
}
const [fromExists, toExists] = yield* Effect.all(
[
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: fromCheckpointRef,
}),
checkpointStore.hasCheckpointRef({
cwd: workspaceCwd,
checkpointRef: toCheckpointRef,
}),
],
{ concurrency: "unbounded" },
);
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.turnDiff.diffCheckpoints"));
if (!fromExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.fromTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount}.`,
});
}
if (!toExists) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Filesystem checkpoint is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef,
toCheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
});
const turnDiff: OrchestrationGetTurnDiffResultType = {
threadId: input.threadId,
fromTurnCount: input.fromTurnCount,
toTurnCount: input.toTurnCount,
diff,
};
const turnDiff = buildTurnDiffResult(input, diff);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
@@ -155,15 +145,99 @@ const make = Effect.gen(function* () {
},
);
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
) =>
getTurnDiff({
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
ignoreWhitespace: input.ignoreWhitespace ?? true,
}).pipe(Effect.map((result): OrchestrationGetFullThreadDiffResult => result));
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = Effect.fn(
"CheckpointDiffQuery.getFullThreadDiff",
)(function* (input) {
const operation = "CheckpointDiffQuery.getFullThreadDiff";
const ignoreWhitespace = input.ignoreWhitespace ?? true;
yield* Effect.annotateCurrentSpan({
"checkpoint.thread_id": input.threadId,
"checkpoint.from_turn_count": 0,
"checkpoint.to_turn_count": input.toTurnCount,
"checkpoint.ignore_whitespace": ignoreWhitespace,
"checkpoint.diff_kind": "full-thread",
});
if (input.toTurnCount === 0) {
const emptyDiff = buildTurnDiffResult(
{
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: 0,
},
"",
);
if (!isTurnDiffResult(emptyDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
});
}
return emptyDiff satisfies OrchestrationGetFullThreadDiffResult;
}
const threadContext = yield* projectionSnapshotQuery
.getFullThreadDiffContext(input.threadId, input.toTurnCount)
.pipe(Effect.withSpan("checkpoint.fullThread.lookupContext"));
if (Option.isNone(threadContext)) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
if (input.toTurnCount > threadContext.value.latestCheckpointTurnCount) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Turn diff range exceeds current turn count: requested ${input.toTurnCount}, current ${threadContext.value.latestCheckpointTurnCount}.`,
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
detail: `Workspace path missing for thread '${input.threadId}' when computing full thread diff.`,
});
}
if (!threadContext.value.toCheckpointRef) {
return yield* new CheckpointUnavailableError({
threadId: input.threadId,
turnCount: input.toTurnCount,
detail: `Checkpoint ref is unavailable for turn ${input.toTurnCount}.`,
});
}
const diff = yield* checkpointStore
.diffCheckpoints({
cwd: workspaceCwd,
fromCheckpointRef: checkpointRefForThreadTurn(input.threadId, 0),
toCheckpointRef: threadContext.value.toCheckpointRef as CheckpointRef,
fallbackFromToHead: false,
ignoreWhitespace,
})
.pipe(Effect.withSpan("checkpoint.fullThread.diffCheckpoints"));
const turnDiff = buildTurnDiffResult(
{
threadId: input.threadId,
fromTurnCount: 0,
toTurnCount: input.toTurnCount,
},
diff,
);
if (!isTurnDiffResult(turnDiff)) {
return yield* new CheckpointInvariantError({
operation,
detail: "Computed full thread diff result does not satisfy contract schema.",
});
}
return turnDiff satisfies OrchestrationGetFullThreadDiffResult;
});
return {
getTurnDiff,
@@ -1,304 +1,79 @@
/**
* CheckpointStoreLive - Filesystem checkpoint store adapter layer.
*
* Implements hidden Git-ref checkpoint capture/restore directly with
* Effect-native child process execution (`effect/unstable/process`).
*
* This layer owns filesystem/Git interactions only; it does not persist
* checkpoint metadata and does not coordinate provider rollback semantics.
* Resolves the active VCS driver once per checkpoint operation and delegates
* checkpoint-specific behavior to the driver's optional checkpoint capability.
*
* @module CheckpointStoreLive
*/
import { randomUUID } from "node:crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { CheckpointInvariantError } from "../Errors.ts";
import { VcsProcessExitError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const CHECKPOINT_DIFF_MAX_OUTPUT_BYTES = 10_000_000;
import { VcsUnsupportedOperationError } from "@t3tools/contracts";
import { VcsDriverRegistry } from "../../vcs/VcsDriverRegistry.ts";
import type { VcsCheckpointOps } from "../../vcs/VcsDriver.ts";
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 resolveHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.resolveHeadCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const hasHeadCommit = (cwd: string) =>
vcs
.execute({
operation: "CheckpointStore.hasHeadCommit",
cwd,
args: ["rev-parse", "--verify", "HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.map((result) => result.exitCode === 0));
const resolveCheckpointCommit = (cwd: string, checkpointRef: CheckpointRef) =>
vcs
.execute({
operation: "CheckpointStore.resolveCheckpointCommit",
cwd,
args: ["rev-parse", "--verify", "--quiet", `${checkpointRef}^{commit}`],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => {
if (result.exitCode !== 0) {
return null;
}
const commit = result.stdout.trim();
return commit.length > 0 ? commit : null;
}),
);
const resolveCheckpoints = Effect.fn("CheckpointStore.resolveCheckpoints")(function* (
operation: string,
cwd: string,
) {
const handle = yield* vcsRegistry.resolve({ cwd });
if (!handle.driver.checkpoints) {
return yield* new VcsUnsupportedOperationError({
operation,
kind: handle.kind,
detail: `${handle.kind} driver does not implement checkpoint operations.`,
});
}
return handle.driver.checkpoints satisfies VcsCheckpointOps;
});
const isGitRepository: CheckpointStoreShape["isGitRepository"] = (cwd) =>
vcs
.execute({
operation: "CheckpointStore.isGitRepository",
cwd,
args: ["rev-parse", "--is-inside-work-tree"],
allowNonZeroExit: true,
})
.pipe(
Effect.map((result) => result.exitCode === 0 && result.stdout.trim() === "true"),
Effect.catch(() => Effect.succeed(false)),
);
vcsRegistry.resolve({ cwd, requestedKind: "git" }).pipe(
Effect.map(() => true),
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new VcsProcessExitError({
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({
operation,
cwd: input.cwd,
args: ["commit-tree", treeOid, "-m", message],
env: commitEnv,
});
const commitOid = commitTreeResult.stdout.trim();
if (commitOid.length === 0) {
return yield* new VcsProcessExitError({
operation,
command: "git commit-tree",
cwd: input.cwd,
exitCode: 0,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", input.checkpointRef, commitOid],
});
}),
(tempDir) => fs.remove(tempDir, { recursive: true }),
).pipe(
Effect.catchTags({
PlatformError: (error) =>
Effect.fail(
new CheckpointInvariantError({
operation: "CheckpointStore.captureCheckpoint",
detail: "Failed to capture checkpoint.",
cause: error,
}),
),
}),
);
const checkpoints = yield* resolveCheckpoints("CheckpointStore.captureCheckpoint", input.cwd);
return yield* checkpoints.captureCheckpoint(input);
});
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = Effect.fn("hasCheckpointRef")(
function* (input) {
const checkpoints = yield* resolveCheckpoints("CheckpointStore.hasCheckpointRef", input.cwd);
return yield* checkpoints.hasCheckpointRef(input);
},
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* vcs.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
const checkpoints = yield* resolveCheckpoints("CheckpointStore.restoreCheckpoint", input.cwd);
return yield* checkpoints.restoreCheckpoint(input);
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
const toCommitOid = yield* resolveCheckpointCommit(input.cwd, input.toCheckpointRef);
if (!fromCommitOid && input.fallbackFromToHead === true) {
const headCommit = yield* resolveHeadCommit(input.cwd);
if (headCommit) {
fromCommitOid = headCommit;
}
}
if (!fromCommitOid || !toCommitOid) {
return yield* new VcsProcessExitError({
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({
operation,
cwd: input.cwd,
args: diffArgs,
maxOutputBytes: CHECKPOINT_DIFF_MAX_OUTPUT_BYTES,
});
return result.stdout;
const checkpoints = yield* resolveCheckpoints("CheckpointStore.diffCheckpoints", input.cwd);
return yield* checkpoints.diffCheckpoints(input);
},
);
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
vcs.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
const checkpoints = yield* resolveCheckpoints(
"CheckpointStore.deleteCheckpointRefs",
input.cwd,
);
return yield* checkpoints.deleteCheckpointRefs(input);
});
return {
@@ -1,4 +1,4 @@
import { describe, expect, it } from "@effect/vitest";
import { assert, describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -66,6 +66,56 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows process JSON through schemas", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(`
[
{
"ProcessId": 4242,
"ParentProcessId": 100,
"CommandLine": "node server.js",
"WorkingSetSize": 4096.7,
"PercentProcessorTime": 2.5,
"Status": "Running"
},
{
"ProcessId": 0,
"ParentProcessId": 100,
"Name": "invalid.exe"
},
{
"ProcessId": 4243,
"ParentProcessId": 4242,
"Name": "child.exe"
}
]
`);
assert.deepEqual(rows, [
{
pid: 4242,
ppid: 100,
pgid: null,
status: "Running",
cpuPercent: 2.5,
rssBytes: 4097,
elapsed: "",
command: "node server.js",
},
{
pid: 4243,
ppid: 4242,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "child.exe",
},
]);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -15,7 +15,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { collectUint8StreamText } from "../stream/collectUint8StreamText.ts";
interface ProcessRow {
export interface ProcessRow {
readonly pid: number;
readonly ppid: number;
readonly pgid: number | null;
@@ -26,9 +26,23 @@ interface ProcessRow {
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;
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.String),
Name: Schema.optional(Schema.String),
WorkingSetSize: Schema.optional(Schema.Number),
PercentProcessorTime: Schema.optional(Schema.Number),
Status: Schema.optional(Schema.String),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const WindowsProcessJson = Schema.fromJsonString(Schema.Unknown);
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
const decodeWindowsProcessJson = Schema.decodeUnknownOption(WindowsProcessJson);
export interface ProcessDiagnosticsShape {
readonly read: Effect.Effect<ServerProcessDiagnosticsResult>;
@@ -74,6 +88,9 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
const nonEmptyWindowsString = (value: string | undefined): Option.Option<string> =>
Option.fromUndefinedOr(value).pipe(Option.filter((text) => text.trim().length > 0));
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -139,54 +156,64 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
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;
function normalizeWindowsProcessRow(record: WindowsProcessRecord): Option.Option<ProcessRow> {
const pid = Number.isInteger(record.ProcessId) ? Option.some(record.ProcessId) : Option.none();
const ppid = Number.isInteger(record.ParentProcessId)
? Option.some(record.ParentProcessId)
: Option.none();
const commandLine = nonEmptyWindowsString(record.CommandLine).pipe(
Option.orElse(() => nonEmptyWindowsString(record.Name)),
);
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
record.WorkingSetSize !== undefined && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
record.PercentProcessorTime !== undefined && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
if (
Option.isNone(pid) ||
pid.value <= 0 ||
Option.isNone(ppid) ||
ppid.value < 0 ||
Option.isNone(commandLine)
) {
return Option.none<ProcessRow>();
}
return Option.some({
pid: pid.value,
ppid: ppid.value,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
status: record.Status !== undefined && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
command: commandLine.value,
});
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
export 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] : [];
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) return [];
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) => {
const decoded = decodeWindowsProcessRecord(record);
return Option.match(decoded, {
onNone: () => [],
onSome: (windowsRecord) =>
Option.match(normalizeWindowsProcessRow(windowsRecord), {
onNone: () => [],
onSome: (row) => [row],
}),
});
} catch {
return [];
}
});
}
function buildDescendantEntries(
export function buildDescendantEntries(
rows: ReadonlyArray<ProcessRow>,
serverPid: number,
): ReadonlyArray<ServerProcessDiagnosticsEntry> {
@@ -230,7 +257,7 @@ function buildDescendantEntries(
return entries;
}
function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
export function isDiagnosticsQueryProcess(row: ProcessRow, serverPid: number): boolean {
if (row.ppid !== serverPid) return false;
const command = row.command.trim();
@@ -309,7 +336,7 @@ const runProcess = Effect.fn("runProcess")(
(effect, input) =>
effect.pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(PROCESS_QUERY_TIMEOUT_MS)),
Effect.timeoutOption(PROCESS_QUERY_TIMEOUT),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () => Effect.fail(toProcessDiagnosticsError(`${input.errorMessage} timed out.`)),
@@ -370,7 +397,7 @@ function readWindowsProcessRows(): Effect.Effect<
);
}
const readProcessRows = (platform = process.platform) =>
export const readProcessRows = (platform = process.platform) =>
platform === "win32" ? readWindowsProcessRows() : readPosixProcessRows();
export function aggregateProcessDiagnostics(input: {
@@ -0,0 +1,231 @@
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import {
aggregateProcessResourceHistory,
collectMonitoredSamples,
} from "./ProcessResourceMonitor.ts";
describe("ProcessResourceMonitor", () => {
it.effect("samples the server root process and descendants", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
{
pid: 101,
ppid: 100,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 2_000,
elapsed: "00:20",
command: "codex app-server",
},
{
pid: 102,
ppid: 101,
pgid: 100,
status: "R",
cpuPercent: 50,
rssBytes: 3_000,
elapsed: "00:05",
command: "rg needle",
},
{
pid: 200,
ppid: 1,
pgid: 200,
status: "R",
cpuPercent: 99,
rssBytes: 9_000,
elapsed: "00:05",
command: "unrelated",
},
],
});
expect(samples.map((sample) => sample.pid)).toEqual([100, 101, 102]);
expect(samples.map((sample) => sample.depth)).toEqual([0, 1, 2]);
expect(samples[0]?.isServerRoot).toBe(true);
expect(samples[1]?.isServerRoot).toBe(false);
}),
);
it.effect("rolls samples up by process and CPU time", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.000Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 10,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 30,
rssBytes: 2_000,
elapsed: "01:05",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(Option.isNone(result.error)).toBe(true);
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.avgCpuPercent).toBe(20);
expect(result.topProcesses[0]?.maxCpuPercent).toBe(30);
expect(result.topProcesses[0]?.cpuSecondsApprox).toBe(2);
expect(result.totalCpuSecondsApprox).toBe(2);
expect(result.buckets.some((bucket) => bucket.maxCpuPercent === 30)).toBe(true);
}),
);
it.effect("keeps a process grouped when elapsed time drifts between samples", () =>
Effect.sync(() => {
const firstAt = DateTime.makeUnsafe("2026-05-05T10:00:00.400Z");
const secondAt = DateTime.makeUnsafe("2026-05-05T10:00:05.900Z");
const samples = [
...collectMonitoredSamples({
serverPid: 100,
sampledAt: firstAt,
sampledAtMs: DateTime.toEpochMillis(firstAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
],
}),
...collectMonitoredSamples({
serverPid: 100,
sampledAt: secondAt,
sampledAtMs: DateTime.toEpochMillis(secondAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 2,
rssBytes: 2_000,
elapsed: "01:06",
command: "t3 server",
},
],
}),
];
const result = aggregateProcessResourceHistory({
samples,
readAt: secondAt,
readAtMs: DateTime.toEpochMillis(secondAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(result.topProcesses).toHaveLength(1);
expect(result.topProcesses[0]?.isServerRoot).toBe(true);
expect(result.topProcesses[0]?.sampleCount).toBe(2);
expect(result.topProcesses[0]?.maxRssBytes).toBe(2_000);
}),
);
it.effect("returns all process summaries in the selected window", () =>
Effect.sync(() => {
const sampledAt = DateTime.makeUnsafe("2026-05-05T10:00:00.000Z");
const samples = collectMonitoredSamples({
serverPid: 100,
sampledAt,
sampledAtMs: DateTime.toEpochMillis(sampledAt),
rows: [
{
pid: 100,
ppid: 1,
pgid: 100,
status: "S",
cpuPercent: 1,
rssBytes: 1_000,
elapsed: "01:00",
command: "t3 server",
},
...Array.from({ length: 35 }, (_, index) => ({
pid: 200 + index,
ppid: index === 0 ? 100 : 199 + index,
pgid: 100,
status: "S",
cpuPercent: 35 - index,
rssBytes: 2_000 + index,
elapsed: "00:10",
command: `worker ${index}`,
})),
],
});
const result = aggregateProcessResourceHistory({
samples,
readAt: sampledAt,
readAtMs: DateTime.toEpochMillis(sampledAt),
windowMs: 60_000,
bucketMs: 10_000,
lastError: null,
});
expect(result.topProcesses).toHaveLength(36);
expect(result.topProcesses.some((process) => process.command === "worker 34")).toBe(true);
}),
);
});
@@ -0,0 +1,299 @@
import type {
ServerProcessResourceHistoryBucket,
ServerProcessResourceHistoryInput,
ServerProcessResourceHistoryResult,
ServerProcessResourceHistorySummary,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
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 Ref from "effect/Ref";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
buildDescendantEntries,
isDiagnosticsQueryProcess,
type ProcessRow,
readProcessRows,
} from "./ProcessDiagnostics.ts";
const SAMPLE_INTERVAL_MS = 5_000;
const RETENTION_MS = 60 * 60_000;
const MAX_RETAINED_SAMPLES = 20_000;
export interface ProcessResourceSample {
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
readonly processKey: string;
readonly pid: number;
readonly ppid: number;
readonly command: string;
readonly cpuPercent: number;
readonly rssBytes: number;
readonly depth: number;
readonly isServerRoot: boolean;
}
interface MonitorState {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly lastError: string | null;
}
export interface ProcessResourceMonitorShape {
readonly readHistory: (
input: ServerProcessResourceHistoryInput,
) => Effect.Effect<ServerProcessResourceHistoryResult>;
}
export class ProcessResourceMonitor extends Context.Service<
ProcessResourceMonitor,
ProcessResourceMonitorShape
>()("t3/diagnostics/ProcessResourceMonitor") {}
function dateTimeFromMillis(ms: number): DateTime.Utc {
return DateTime.makeUnsafe(ms);
}
function sampleKey(row: Pick<ProcessRow, "pid" | "command">): string {
return `${row.pid}:${row.command}`;
}
function findServerRootRow(rows: ReadonlyArray<ProcessRow>, serverPid: number): ProcessRow | null {
return rows.find((row) => row.pid === serverPid) ?? null;
}
export function collectMonitoredSamples(input: {
readonly rows: ReadonlyArray<ProcessRow>;
readonly serverPid: number;
readonly sampledAt: DateTime.Utc;
readonly sampledAtMs: number;
}): ReadonlyArray<ProcessResourceSample> {
const rows = input.rows.filter((row) => !isDiagnosticsQueryProcess(row, input.serverPid));
const root = findServerRootRow(rows, input.serverPid);
const descendants = buildDescendantEntries(rows, input.serverPid);
const samples: ProcessResourceSample[] = [];
if (root) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(root),
pid: root.pid,
ppid: root.ppid,
command: root.command,
cpuPercent: root.cpuPercent,
rssBytes: root.rssBytes,
depth: 0,
isServerRoot: true,
});
}
for (const process of descendants) {
samples.push({
sampledAt: input.sampledAt,
sampledAtMs: input.sampledAtMs,
processKey: sampleKey(process),
pid: process.pid,
ppid: process.ppid,
command: process.command,
cpuPercent: process.cpuPercent,
rssBytes: process.rssBytes,
depth: process.depth + 1,
isServerRoot: false,
});
}
return samples;
}
function trimSamples(
samples: ReadonlyArray<ProcessResourceSample>,
nowMs: number,
): ReadonlyArray<ProcessResourceSample> {
const minSampledAtMs = nowMs - RETENTION_MS;
const retained = samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
return retained.length <= MAX_RETAINED_SAMPLES
? retained
: retained.slice(retained.length - MAX_RETAINED_SAMPLES);
}
function summarizeProcesses(
samples: ReadonlyArray<ProcessResourceSample>,
): ReadonlyArray<ServerProcessResourceHistorySummary> {
const groups = new Map<string, ProcessResourceSample[]>();
for (const sample of samples) {
const processSamples = groups.get(sample.processKey) ?? [];
processSamples.push(sample);
groups.set(sample.processKey, processSamples);
}
return [...groups.entries()]
.map(([processKey, processSamples]) => {
const sorted = processSamples.toSorted((left, right) => left.sampledAtMs - right.sampledAtMs);
const first = sorted[0]!;
const latest = sorted[sorted.length - 1]!;
const cpuPercentTotal = sorted.reduce((total, sample) => total + sample.cpuPercent, 0);
const maxCpuPercent = Math.max(...sorted.map((sample) => sample.cpuPercent));
const maxRssBytes = Math.max(...sorted.map((sample) => sample.rssBytes));
const cpuSecondsApprox = sorted.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
processKey,
pid: latest.pid,
ppid: latest.ppid,
command: latest.command,
depth: latest.depth,
isServerRoot: latest.isServerRoot,
firstSeenAt: first.sampledAt,
lastSeenAt: latest.sampledAt,
currentCpuPercent: latest.cpuPercent,
avgCpuPercent: cpuPercentTotal / sorted.length,
maxCpuPercent,
cpuSecondsApprox,
currentRssBytes: latest.rssBytes,
maxRssBytes,
sampleCount: sorted.length,
} satisfies ServerProcessResourceHistorySummary;
})
.toSorted((left, right) => right.cpuSecondsApprox - left.cpuSecondsApprox);
}
function buildBuckets(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly nowMs: number;
readonly windowMs: number;
readonly bucketMs: number;
}): ReadonlyArray<ServerProcessResourceHistoryBucket> {
const bucketMs = Math.max(1_000, input.bucketMs);
const windowStartMs = input.nowMs - input.windowMs;
const buckets: ServerProcessResourceHistoryBucket[] = [];
for (let startedAtMs = windowStartMs; startedAtMs < input.nowMs; startedAtMs += bucketMs) {
const endedAtMs = Math.min(input.nowMs, startedAtMs + bucketMs);
const bucketSamples = input.samples.filter(
(sample) =>
sample.sampledAtMs >= startedAtMs &&
(endedAtMs === input.nowMs
? sample.sampledAtMs <= endedAtMs
: sample.sampledAtMs < endedAtMs),
);
const samplesByRead = new Map<number, ProcessResourceSample[]>();
for (const sample of bucketSamples) {
const samplesAtTime = samplesByRead.get(sample.sampledAtMs) ?? [];
samplesAtTime.push(sample);
samplesByRead.set(sample.sampledAtMs, samplesAtTime);
}
const readTotals = [...samplesByRead.values()].map((samplesAtTime) => ({
cpuPercent: samplesAtTime.reduce((total, sample) => total + sample.cpuPercent, 0),
rssBytes: samplesAtTime.reduce((total, sample) => total + sample.rssBytes, 0),
processCount: samplesAtTime.length,
}));
const avgCpuPercent =
readTotals.length === 0
? 0
: readTotals.reduce((total, read) => total + read.cpuPercent, 0) / readTotals.length;
buckets.push({
startedAt: dateTimeFromMillis(startedAtMs),
endedAt: dateTimeFromMillis(endedAtMs),
avgCpuPercent,
maxCpuPercent: readTotals.length ? Math.max(...readTotals.map((read) => read.cpuPercent)) : 0,
maxRssBytes: readTotals.length ? Math.max(...readTotals.map((read) => read.rssBytes)) : 0,
maxProcessCount: readTotals.length
? Math.max(...readTotals.map((read) => read.processCount))
: 0,
});
}
return buckets;
}
export function aggregateProcessResourceHistory(input: {
readonly samples: ReadonlyArray<ProcessResourceSample>;
readonly readAt: DateTime.Utc;
readonly readAtMs: number;
readonly windowMs: number;
readonly bucketMs: number;
readonly lastError: string | null;
}): ServerProcessResourceHistoryResult {
const windowMs = Math.max(1_000, input.windowMs);
const bucketMs = Math.max(1_000, input.bucketMs);
const minSampledAtMs = input.readAtMs - windowMs;
const samples = input.samples.filter((sample) => sample.sampledAtMs >= minSampledAtMs);
const topProcesses = summarizeProcesses(samples);
const totalCpuSecondsApprox = samples.reduce(
(total, sample) => total + (sample.cpuPercent / 100) * (SAMPLE_INTERVAL_MS / 1_000),
0,
);
return {
readAt: input.readAt,
windowMs,
bucketMs,
sampleIntervalMs: SAMPLE_INTERVAL_MS,
retainedSampleCount: input.samples.length,
totalCpuSecondsApprox,
buckets: buildBuckets({ samples, nowMs: input.readAtMs, windowMs, bucketMs }),
topProcesses,
error: input.lastError ? Option.some({ message: input.lastError }) : Option.none(),
};
}
export const make = Effect.fn("makeProcessResourceMonitor")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const state = yield* Ref.make<MonitorState>({ samples: [], lastError: null });
const sampleOnce = Effect.gen(function* () {
const sampledAt = yield* DateTime.now;
const sampledAtMs = DateTime.toEpochMillis(sampledAt);
const rows = yield* readProcessRows().pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
const samples = collectMonitoredSamples({
rows,
serverPid: process.pid,
sampledAt,
sampledAtMs,
});
yield* Ref.update(state, (current) => ({
samples: trimSamples([...current.samples, ...samples], sampledAtMs),
lastError: null,
}));
}).pipe(
Effect.catch((error: unknown) =>
Ref.update(state, (current) => ({
...current,
lastError: error instanceof Error ? error.message : "Failed to sample process resources.",
})),
),
);
yield* Effect.forever(sampleOnce.pipe(Effect.andThen(Effect.sleep(SAMPLE_INTERVAL_MS)))).pipe(
Effect.forkScoped,
);
const readHistory: ProcessResourceMonitorShape["readHistory"] = (input) =>
Effect.gen(function* () {
const readAt = yield* DateTime.now;
const readAtMs = DateTime.toEpochMillis(readAt);
const current = yield* Ref.get(state);
return aggregateProcessResourceHistory({
samples: current.samples,
readAt,
readAtMs,
windowMs: input.windowMs,
bucketMs: input.bucketMs,
lastError: current.lastError,
});
});
return ProcessResourceMonitor.of({ readHistory });
});
export const layer = Layer.effect(ProcessResourceMonitor, make());
@@ -6,6 +6,7 @@ import * as Path from "effect/Path";
import * as Random from "effect/Random";
import { ServerConfig } from "../../config.ts";
import { layer as ProcessRunnerLive } from "../../processRunner.ts";
import { ServerEnvironment, type ServerEnvironmentShape } from "../Services/ServerEnvironment.ts";
import packageJson from "../../../package.json" with { type: "json" };
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
@@ -93,4 +94,6 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
} satisfies ServerEnvironmentShape;
});
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment());
export const ServerEnvironmentLive = Layer.effect(ServerEnvironment, makeServerEnvironment()).pipe(
Layer.provide(ProcessRunnerLive),
);
@@ -1,20 +1,36 @@
import { afterEach, describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import { vi } from "vitest";
vi.mock("../../processRunner.ts", () => ({
runProcess: vi.fn(),
}));
import { runProcess } from "../../processRunner.ts";
import { ProcessRunner, ProcessSpawnError, type ProcessRunnerShape } from "../../processRunner.ts";
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
import { ChildProcessSpawner } from "effect/unstable/process";
const mockedRunProcess = vi.mocked(runProcess);
const runMock = vi.fn<ProcessRunnerShape["run"]>();
const ProcessRunnerTest = Layer.succeed(
ProcessRunner,
ProcessRunner.of({
run: (input) => runMock(input),
}),
);
const NoopFileSystemLayer = FileSystem.layerNoop({});
const TestLayer = Layer.merge(NoopFileSystemLayer, ProcessRunnerTest);
const LinuxMachineInfoLayer = Layer.merge(
ProcessRunnerTest,
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
);
afterEach(() => {
mockedRunProcess.mockReset();
runMock.mockReset();
});
describe("resolveServerEnvironmentLabel", () => {
@@ -24,7 +40,7 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "macbook-pro",
}).pipe(Effect.provide(NoopFileSystemLayer));
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("macbook-pro");
}),
@@ -32,25 +48,30 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("prefers the macOS ComputerName", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: " Julius's MacBook Pro \n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: " Julius's MacBook Pro \n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(NoopFileSystemLayer));
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("Julius's MacBook Pro");
expect(mockedRunProcess).toHaveBeenCalledWith(
"scutil",
["--get", "ComputerName"],
expect.objectContaining({ allowNonZeroExit: true }),
expect(runMock).toHaveBeenCalledWith(
expect.objectContaining({
command: "scutil",
args: ["--get", "ComputerName"],
timeoutBehavior: "timedOutResult",
}),
);
}),
);
@@ -61,44 +82,39 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "linux",
hostname: "buildbox",
}).pipe(
Effect.provide(
FileSystem.layerNoop({
exists: (path) => Effect.succeed(path === "/etc/machine-info"),
readFileString: (path) =>
path === "/etc/machine-info"
? Effect.succeed('PRETTY_HOSTNAME="Build Agent 01"\nICON_NAME="computer-vm"\n')
: Effect.succeed(""),
}),
),
);
}).pipe(Effect.provide(LinuxMachineInfoLayer));
expect(result).toBe("Build Agent 01");
expect(mockedRunProcess).not.toHaveBeenCalled();
expect(runMock).not.toHaveBeenCalled();
}),
);
it.effect("falls back to hostnamectl pretty hostname on Linux", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: "CI Runner\n",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: "CI Runner\n",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: "runner-01",
}).pipe(Effect.provide(NoopFileSystemLayer));
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("CI Runner");
expect(mockedRunProcess).toHaveBeenCalledWith(
"hostnamectl",
["--pretty"],
expect.objectContaining({ allowNonZeroExit: true }),
expect(runMock).toHaveBeenCalledWith(
expect.objectContaining({
command: "hostnamectl",
args: ["--pretty"],
timeoutBehavior: "timedOutResult",
}),
);
}),
);
@@ -109,7 +125,7 @@ describe("resolveServerEnvironmentLabel", () => {
cwdBaseName: "t3code",
platform: "win32",
hostname: "JULIUS-LAPTOP",
}).pipe(Effect.provide(NoopFileSystemLayer));
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("JULIUS-LAPTOP");
}),
@@ -117,13 +133,21 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("falls back to the hostname when the friendly-label command is missing", () =>
Effect.gen(function* () {
mockedRunProcess.mockRejectedValueOnce(new Error("spawn scutil ENOENT"));
runMock.mockReturnValueOnce(
Effect.fail(
new ProcessSpawnError({
command: "scutil",
args: ["--get", "ComputerName"],
cause: new Error("spawn scutil ENOENT"),
}),
),
);
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "darwin",
hostname: "macbook-pro",
}).pipe(Effect.provide(NoopFileSystemLayer));
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("macbook-pro");
}),
@@ -131,19 +155,22 @@ describe("resolveServerEnvironmentLabel", () => {
it.effect("falls back to the cwd basename when the hostname is blank", () =>
Effect.gen(function* () {
mockedRunProcess.mockResolvedValueOnce({
stdout: " ",
stderr: "",
code: 0,
signal: null,
timedOut: false,
});
runMock.mockReturnValueOnce(
Effect.succeed({
stdout: " ",
stderr: "",
code: ChildProcessSpawner.ExitCode(0),
timedOut: false,
stdoutTruncated: false,
stderrTruncated: false,
}),
);
const result = yield* resolveServerEnvironmentLabel({
cwdBaseName: "t3code",
platform: "linux",
hostname: " ",
}).pipe(Effect.provide(NoopFileSystemLayer));
}).pipe(Effect.provide(TestLayer));
expect(result).toBe("t3code");
}),
@@ -2,8 +2,9 @@ import * as OS from "node:os";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import { runProcess } from "../../processRunner.ts";
import { ProcessRunner } from "../../processRunner.ts";
interface ResolveServerEnvironmentLabelInput {
readonly cwdBaseName: string;
@@ -52,19 +53,21 @@ const runFriendlyLabelCommand = Effect.fn("runFriendlyLabelCommand")(function* (
command: string,
args: readonly string[],
) {
const result = yield* Effect.tryPromise({
try: () =>
runProcess(command, args, {
allowNonZeroExit: true,
}),
catch: () => null,
}).pipe(Effect.orElseSucceed(() => null));
const processRunner = yield* ProcessRunner;
const result = yield* processRunner
.run({
command,
args,
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
if (!result || result.code !== 0) {
if (Option.isNone(result) || result.value.code !== 0) {
return null;
}
return normalizeLabel(result.stdout);
return normalizeLabel(result.value.stdout);
});
const resolveFriendlyHostLabel = Effect.fn("resolveFriendlyHostLabel")(function* (
+11 -3
View File
@@ -28,6 +28,11 @@ import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolve
import { ServerAuth } from "./auth/Services/ServerAuth.ts";
import { respondToAuthError } from "./auth/http.ts";
import { ServerEnvironment } from "./environment/Services/ServerEnvironment.ts";
import {
browserApiCorsAllowedHeaders,
browserApiCorsAllowedMethods,
browserApiCorsHeaders,
} from "./httpCors.ts";
const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
@@ -35,8 +40,8 @@ const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
const LOOPBACK_HOSTNAMES = new Set(["127.0.0.1", "::1", "localhost"]);
export const browserApiCorsLayer = HttpRouter.cors({
allowedMethods: ["GET", "POST", "OPTIONS"],
allowedHeaders: ["authorization", "b3", "traceparent", "content-type"],
allowedMethods: [...browserApiCorsAllowedMethods],
allowedHeaders: [...browserApiCorsAllowedHeaders],
maxAge: 600,
});
@@ -69,7 +74,10 @@ export const serverEnvironmentRouteLayer = HttpRouter.add(
const descriptor = yield* Effect.service(ServerEnvironment).pipe(
Effect.flatMap((serverEnvironment) => serverEnvironment.getDescriptor),
);
return HttpServerResponse.jsonUnsafe(descriptor, { status: 200 });
return HttpServerResponse.jsonUnsafe(descriptor, {
status: 200,
headers: browserApiCorsHeaders,
});
}),
);
+13
View File
@@ -0,0 +1,13 @@
export const browserApiCorsAllowedMethods = ["GET", "POST", "OPTIONS"] as const;
export const browserApiCorsAllowedHeaders = [
"authorization",
"b3",
"traceparent",
"content-type",
] as const;
export const browserApiCorsHeaders = {
"access-control-allow-origin": "*",
"access-control-allow-methods": browserApiCorsAllowedMethods.join(", "),
"access-control-allow-headers": browserApiCorsAllowedHeaders.join(", "),
} as const;
@@ -18,6 +18,7 @@ const DEFAULT_RPC_SPAN_ATTRIBUTES = {
const RPC_METHODS_WITH_TRACING_DISABLED: ReadonlySet<string> = new Set([
WS_METHODS.serverGetTraceDiagnostics,
WS_METHODS.serverGetProcessDiagnostics,
WS_METHODS.serverGetProcessResourceHistory,
WS_METHODS.serverSignalProcess,
]);
-241
View File
@@ -1,241 +0,0 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Open - Browser/editor launch service interface.
*
* Owns process launch helpers for opening URLs in a browser and workspace
* paths in a configured editor.
*
* @module Open
*/
import { spawn } from "node:child_process";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
// ==============================
// Definitions
// ==============================
export { OpenError };
export { isCommandAvailable } from "@t3tools/shared/shell";
export interface OpenInEditorInput {
readonly cwd: string;
readonly editor: EditorId;
}
interface EditorLaunch {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
function parseTargetPathAndPosition(target: string): {
path: string;
line: string | undefined;
column: string | undefined;
} | null {
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
if (!match?.[1] || !match[2]) {
return null;
}
return {
path: match[1],
line: match[2],
column: match[3],
};
}
function resolveCommandEditorArgs(
editor: (typeof EDITORS)[number],
target: string,
): ReadonlyArray<string> {
const parsedTarget = parseTargetPathAndPosition(target);
switch (editor.launchStyle) {
case "direct-path":
return [target];
case "goto":
return parsedTarget ? ["--goto", target] : [target];
case "line-column": {
if (!parsedTarget) {
return [target];
}
const { path, line, column } = parsedTarget;
return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
}
}
}
function resolveEditorArgs(
editor: (typeof EDITORS)[number],
target: string,
): ReadonlyArray<string> {
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
}
function resolveAvailableCommand(
commands: ReadonlyArray<string>,
options: CommandAvailabilityOptions = {},
): string | null {
for (const command of commands) {
if (isCommandAvailable(command, options)) {
return command;
}
}
return null;
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.commands === null) {
const command = fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
continue;
}
const command = resolveAvailableCommand(editor.commands, { platform, env });
if (command !== null) {
available.push(editor.id);
}
}
return available;
}
/**
* OpenShape - Service API for browser and editor launch actions.
*/
export interface OpenShape {
/**
* Open a URL target in the default browser.
*/
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
/**
* Open a workspace path in a selected editor integration.
*
* Launches the editor as a detached process so server startup is not blocked.
*/
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
}
/**
* Open - Service tag for browser/editor launch operations.
*/
export class Open extends Context.Service<Open, OpenShape>()("t3/open") {}
// ==============================
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<EditorLaunch, OpenError> {
yield* Effect.annotateCurrentSpan({
"open.editor": input.editor,
"open.cwd": input.cwd,
"open.platform": platform,
});
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.commands) {
const command =
resolveAvailableCommand(editorDef.commands, { platform, env }) ?? editorDef.commands[0];
return {
command,
args: resolveEditorArgs(editorDef, input.cwd),
};
}
if (editorDef.id !== "file-manager") {
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
});
export const launchDetached = (launch: EditorLaunch) =>
Effect.gen(function* () {
if (!isCommandAvailable(launch.command)) {
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
const isWin32 = process.platform === "win32";
child = spawn(
launch.command,
isWin32 ? launch.args.map((a) => `"${a}"`) : [...launch.args],
{
detached: true,
stdio: "ignore",
shell: isWin32,
},
);
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
});
const make = Effect.gen(function* () {
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
return {
openBrowser: (target) =>
Effect.tryPromise({
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
} satisfies OpenShape;
});
export const OpenLive = Layer.effect(Open, make);
@@ -9,6 +9,7 @@ import {
type OrchestrationEvent,
ProviderInstanceId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
@@ -37,7 +38,6 @@ import {
} from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asMessageId = (value: string): MessageId => MessageId.make(value);
@@ -183,6 +183,13 @@ describe("OrchestrationEngine", () => {
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getArchivedShellSnapshot: () =>
Effect.succeed({
snapshotSequence: projectionSnapshot.snapshotSequence,
projects: [],
threads: [],
updatedAt: projectionSnapshot.updatedAt,
}),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: projectionSnapshot.snapshotSequence }),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
@@ -190,6 +197,7 @@ describe("OrchestrationEngine", () => {
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -778,6 +786,7 @@ describe("OrchestrationEngine", () => {
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provide(NodeServices.layer),
),
);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -920,6 +929,7 @@ describe("OrchestrationEngine", () => {
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolverLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provide(NodeServices.layer),
),
);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
@@ -8,6 +8,7 @@ import {
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -29,6 +30,7 @@ const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provideMerge(RepositoryIdentityResolverLive),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
),
);
@@ -441,6 +443,126 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
}),
);
it.effect("keeps archived threads out of the main shell snapshot", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-archive-test',
'Archive Test',
'/tmp/archive-test',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-04-06T00:00:00.000Z',
'2026-04-06T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
latest_user_message_at,
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-active',
'project-archive-test',
'Active Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-06T00:00:02.000Z',
'2026-04-06T00:00:03.000Z',
NULL,
NULL
),
(
'thread-archived',
'project-archive-test',
'Archived Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
NULL,
0,
0,
0,
'2026-04-06T00:00:04.000Z',
'2026-04-06T00:00:05.000Z',
'2026-04-06T00:00:06.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES
(${ORCHESTRATION_PROJECTOR_NAMES.projects}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threads}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadMessages}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadActivities}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.threadSessions}, 4, '2026-04-06T00:00:07.000Z'),
(${ORCHESTRATION_PROJECTOR_NAMES.checkpoints}, 4, '2026-04-06T00:00:07.000Z')
`;
const shellSnapshot = yield* snapshotQuery.getShellSnapshot();
assert.deepEqual(
shellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-active")],
);
const archivedShellSnapshot = yield* snapshotQuery.getArchivedShellSnapshot();
assert.deepEqual(
archivedShellSnapshot.threads.map((thread) => thread.id),
[ThreadId.make("thread-archived")],
);
assert.equal(archivedShellSnapshot.threads[0]?.archivedAt, "2026-04-06T00:00:06.000Z");
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
@@ -1,5 +1,6 @@
import {
ChatAttachment,
CheckpointRef,
IsoDateTime,
MessageId,
NonNegativeInt,
@@ -49,6 +50,7 @@ import { RepositoryIdentityResolver } from "../../project/Services/RepositoryIde
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
ProjectionSnapshotQuery,
type ProjectionFullThreadDiffContext,
type ProjectionSnapshotCounts,
type ProjectionThreadCheckpointContext,
type ProjectionSnapshotQueryShape,
@@ -122,6 +124,18 @@ const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({
workspaceRoot: Schema.String,
worktreePath: Schema.NullOr(Schema.String),
});
const FullThreadDiffContextLookupInput = Schema.Struct({
threadId: ThreadId,
checkpointTurnCount: NonNegativeInt,
});
const ProjectionFullThreadDiffContextRowSchema = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
workspaceRoot: Schema.String,
worktreePath: Schema.NullOr(Schema.String),
latestCheckpointTurnCount: Schema.NullOr(NonNegativeInt),
toCheckpointRef: Schema.NullOr(CheckpointRef),
});
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -327,6 +341,66 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActiveThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NULL
ORDER BY project_id ASC, created_at ASC, thread_id ASC
`,
});
const listArchivedThreadRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadDbRowSchema,
execute: () =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
worktree_path AS "worktreePath",
latest_turn_id AS "latestTurnId",
created_at AS "createdAt",
updated_at AS "updatedAt",
archived_at AS "archivedAt",
latest_user_message_at AS "latestUserMessageAt",
pending_approval_count AS "pendingApprovalCount",
pending_user_input_count AS "pendingUserInputCount",
has_actionable_proposed_plan AS "hasActionableProposedPlan",
deleted_at AS "deletedAt"
FROM projection_threads
WHERE deleted_at IS NULL
AND archived_at IS NOT NULL
ORDER BY project_id ASC, archived_at DESC, thread_id DESC
`,
});
const listThreadMessageRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadMessageDbRowSchema,
@@ -411,6 +485,56 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listActiveThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
execute: () =>
sql`
SELECT
sessions.thread_id AS "threadId",
sessions.status,
sessions.provider_name AS "providerName",
sessions.provider_instance_id AS "providerInstanceId",
sessions.provider_session_id AS "providerSessionId",
sessions.provider_thread_id AS "providerThreadId",
sessions.runtime_mode AS "runtimeMode",
sessions.active_turn_id AS "activeTurnId",
sessions.last_error AS "lastError",
sessions.updated_at AS "updatedAt"
FROM projection_thread_sessions sessions
INNER JOIN projection_threads threads
ON threads.thread_id = sessions.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
ORDER BY sessions.thread_id ASC
`,
});
const listArchivedThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
execute: () =>
sql`
SELECT
sessions.thread_id AS "threadId",
sessions.status,
sessions.provider_name AS "providerName",
sessions.provider_instance_id AS "providerInstanceId",
sessions.provider_session_id AS "providerSessionId",
sessions.provider_thread_id AS "providerThreadId",
sessions.runtime_mode AS "runtimeMode",
sessions.active_turn_id AS "activeTurnId",
sessions.last_error AS "lastError",
sessions.updated_at AS "updatedAt"
FROM projection_thread_sessions sessions
INNER JOIN projection_threads threads
ON threads.thread_id = sessions.thread_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NOT NULL
ORDER BY sessions.thread_id ASC
`,
});
const listCheckpointRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionCheckpointDbRowSchema,
@@ -475,6 +599,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NULL
AND threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
});
const listArchivedLatestTurnRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionLatestTurnDbRowSchema,
execute: () =>
sql`
SELECT
turns.thread_id AS "threadId",
turns.turn_id AS "turnId",
turns.state,
turns.requested_at AS "requestedAt",
turns.started_at AS "startedAt",
turns.completed_at AS "completedAt",
turns.assistant_message_id AS "assistantMessageId",
turns.source_proposed_plan_thread_id AS "sourceProposedPlanThreadId",
turns.source_proposed_plan_id AS "sourceProposedPlanId"
FROM projection_threads threads
JOIN projection_turns turns
ON turns.thread_id = threads.thread_id
AND turns.turn_id = threads.latest_turn_id
WHERE threads.deleted_at IS NULL
AND threads.archived_at IS NOT NULL
AND threads.latest_turn_id IS NOT NULL
ORDER BY turns.thread_id ASC
`,
@@ -557,6 +708,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE project_id = ${projectId}
AND deleted_at IS NULL
AND archived_at IS NULL
ORDER BY created_at ASC, thread_id ASC
LIMIT 1
`,
@@ -607,6 +759,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
FROM projection_threads
WHERE thread_id = ${threadId}
AND deleted_at IS NULL
AND archived_at IS NULL
LIMIT 1
`,
});
@@ -717,6 +870,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
AND turns.turn_id = threads.latest_turn_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
AND threads.archived_at IS NULL
LIMIT 1
`,
});
@@ -742,6 +896,38 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const getFullThreadDiffContextRow = SqlSchema.findOneOption({
Request: FullThreadDiffContextLookupInput,
Result: ProjectionFullThreadDiffContextRowSchema,
execute: ({ threadId, checkpointTurnCount }) =>
sql`
SELECT
threads.thread_id AS "threadId",
threads.project_id AS "projectId",
projects.workspace_root AS "workspaceRoot",
threads.worktree_path AS "worktreePath",
(
SELECT MAX(turns.checkpoint_turn_count)
FROM projection_turns AS turns
WHERE turns.thread_id = threads.thread_id
AND turns.checkpoint_turn_count IS NOT NULL
) AS "latestCheckpointTurnCount",
(
SELECT turns.checkpoint_ref
FROM projection_turns AS turns
WHERE turns.thread_id = threads.thread_id
AND turns.checkpoint_turn_count = ${checkpointTurnCount}
LIMIT 1
) AS "toCheckpointRef"
FROM projection_threads AS threads
INNER JOIN projection_projects AS projects
ON projects.project_id = threads.project_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
LIMIT 1
`,
});
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
sql
.withTransaction(
@@ -1232,7 +1418,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadRows(undefined).pipe(
listActiveThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listThreads:query",
@@ -1240,7 +1426,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadSessionRows(undefined).pipe(
listActiveThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getShellSnapshot:listThreadSessions:query",
@@ -1350,6 +1536,139 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getArchivedShellSnapshot: ProjectionSnapshotQueryShape["getArchivedShellSnapshot"] = () =>
sql
.withTransaction(
Effect.all([
listProjectRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjects:decodeRows",
),
),
),
listArchivedThreadRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreads:decodeRows",
),
),
),
listArchivedThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listThreadSessions:decodeRows",
),
),
),
listArchivedLatestTurnRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listLatestTurns:decodeRows",
),
),
),
listProjectionStateRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:query",
"ProjectionSnapshotQuery.getArchivedShellSnapshot:listProjectionState:decodeRows",
),
),
),
]),
)
.pipe(
Effect.flatMap(([projectRows, threadRows, sessionRows, latestTurnRows, stateRows]) =>
Effect.gen(function* () {
let updatedAt: string | null = null;
for (const row of projectRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of threadRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of sessionRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
for (const row of latestTurnRows) {
updatedAt = maxIso(updatedAt, row.requestedAt);
if (row.startedAt !== null) {
updatedAt = maxIso(updatedAt, row.startedAt);
}
if (row.completedAt !== null) {
updatedAt = maxIso(updatedAt, row.completedAt);
}
}
for (const row of stateRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
}
const activeProjectIds = new Set(threadRows.map((row) => row.projectId));
const repositoryIdentities = yield* resolveRepositoryIdentitiesForProjects(
projectRows.filter((row) => activeProjectIds.has(row.projectId)),
);
const latestTurnByThread = new Map(
latestTurnRows.map((row) => [row.threadId, mapLatestTurn(row)] as const),
);
const sessionByThread = new Map(
sessionRows.map((row) => [row.threadId, mapSessionRow(row)] as const),
);
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
projects: projectRows
.filter((row) => row.deletedAt === null && activeProjectIds.has(row.projectId))
.map((row) =>
mapProjectShellRow(row, repositoryIdentities.get(row.projectId) ?? null),
),
threads: threadRows.map(
(row): OrchestrationThreadShell => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
};
return yield* decodeShellSnapshot(snapshot).pipe(
Effect.mapError(
toPersistenceDecodeError(
"ProjectionSnapshotQuery.getArchivedShellSnapshot:decodeShellSnapshot",
),
),
);
}),
),
Effect.mapError((error) => {
if (isPersistenceError(error)) {
return error;
}
return toPersistenceSqlError("ProjectionSnapshotQuery.getArchivedShellSnapshot:query")(
error,
);
}),
);
const getSnapshotSequence: ProjectionSnapshotQueryShape["getSnapshotSequence"] = () =>
listProjectionStateRows(undefined).pipe(
Effect.mapError(
@@ -1486,6 +1805,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
});
const getFullThreadDiffContext: NonNullable<
ProjectionSnapshotQueryShape["getFullThreadDiffContext"]
> = (threadId, toTurnCount) =>
Effect.gen(function* () {
const row = yield* getFullThreadDiffContextRow({
threadId,
checkpointTurnCount: toTurnCount,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getFullThreadDiffContext:query",
"ProjectionSnapshotQuery.getFullThreadDiffContext:decodeRow",
),
),
);
if (Option.isNone(row)) {
return Option.none<ProjectionFullThreadDiffContext>();
}
return Option.some({
threadId: row.value.threadId,
projectId: row.value.projectId,
workspaceRoot: row.value.workspaceRoot,
worktreePath: row.value.worktreePath,
latestCheckpointTurnCount: row.value.latestCheckpointTurnCount ?? 0,
toCheckpointRef: row.value.toCheckpointRef,
});
});
const getThreadShellById: ProjectionSnapshotQueryShape["getThreadShellById"] = (threadId) =>
Effect.gen(function* () {
const [threadRow, latestTurnRow, sessionRow] = yield* Effect.all([
@@ -1683,12 +2031,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
getCommandReadModel,
getSnapshot,
getShellSnapshot,
getArchivedShellSnapshot,
getSnapshotSequence,
getCounts,
getActiveProjectByWorkspaceRoot,
getProjectShellById,
getFirstActiveThreadIdByProjectId,
getThreadCheckpointContext,
getFullThreadDiffContext,
getThreadShellById,
getThreadDetailById,
} satisfies ProjectionSnapshotQueryShape;
@@ -7,6 +7,7 @@
* @module ProjectionSnapshotQuery
*/
import type {
CheckpointRef,
OrchestrationCheckpointSummary,
OrchestrationProject,
OrchestrationProjectShell,
@@ -40,6 +41,15 @@ export interface ProjectionThreadCheckpointContext {
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
}
export interface ProjectionFullThreadDiffContext {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly latestCheckpointTurnCount: number;
readonly toCheckpointRef: CheckpointRef | null;
}
/**
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
@@ -72,6 +82,17 @@ export interface ProjectionSnapshotQueryShape {
ProjectionRepositoryError
>;
/**
* Read archived thread shell summaries for the archive page.
*
* This query is separate from the main shell snapshot so archived threads
* are never bootstrapped into normal navigation state.
*/
readonly getArchivedShellSnapshot: () => Effect.Effect<
OrchestrationShellSnapshot,
ProjectionRepositoryError
>;
/**
* Read the latest projection snapshot sequence without hydrating read-model
* entities.
@@ -114,6 +135,15 @@ export interface ProjectionSnapshotQueryShape {
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
/**
* Read only the narrow context needed to compute a full-thread diff from
* checkpoint 0 to a specific turn count.
*/
readonly getFullThreadDiffContext: (
threadId: ThreadId,
toTurnCount: number,
) => Effect.Effect<Option.Option<ProjectionFullThreadDiffContext>, ProjectionRepositoryError>;
/**
* Read a single active thread shell row by id.
*/
@@ -42,6 +42,7 @@ import Migration0026 from "./Migrations/026_CanonicalizeModelSelectionOptions.ts
import Migration0027 from "./Migrations/027_ProviderSessionRuntimeInstanceId.ts";
import Migration0028 from "./Migrations/028_ProjectionThreadSessionInstanceId.ts";
import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexes.ts";
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -83,6 +84,7 @@ export const migrationEntries = [
[27, "ProviderSessionRuntimeInstanceId", Migration0027],
[28, "ProjectionThreadSessionInstanceId", Migration0028],
[29, "ProjectionThreadDetailOrderingIndexes", Migration0029],
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_active
ON projection_threads(deleted_at, archived_at, project_id, created_at, thread_id)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_shell_archived
ON projection_threads(deleted_at, archived_at, project_id, thread_id)
`;
});
@@ -2,16 +2,52 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
isCommandAvailable,
launchDetached,
launchBrowser,
launchEditorProcess,
resolveAvailableEditors,
resolveBrowserLaunch,
resolveEditorLaunch,
} from "./open.ts";
} from "./externalLauncher.ts";
function encodeUtf16LeBase64(input: string): string {
const bytes = new Uint8Array(input.length * 2);
for (let index = 0; index < input.length; index += 1) {
const code = input.charCodeAt(index);
bytes[index * 2] = code & 0xff;
bytes[index * 2 + 1] = code >>> 8;
}
return Encoding.encodeBase64(bytes);
}
function makeMockDetachedHandle(onUnref: () => void = () => undefined) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
isRunning: Effect.succeed(true),
kill: () => Effect.void,
unref: Effect.sync(() => {
onUnref();
return Effect.void;
}),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
@@ -216,70 +252,70 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
});
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "cursor" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
});
const traeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLineAndColumn, {
command: "trae",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
});
const kiroLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "kiro" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "kiro" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(kiroLineAndColumn, {
command: "kiro",
args: ["ide", "--goto", "/tmp/workspace/src/open.ts:71:5"],
args: ["ide", "--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
});
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLineAndColumn, {
command: "code-insiders",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
});
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLineAndColumn, {
command: "codium",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
args: ["--goto", "/tmp/workspace/src/process/externalLauncher.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "zed" },
"darwin",
{ PATH: "" },
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
args: ["/tmp/workspace/src/process/externalLauncher.ts:71:5"],
});
const zedLineOnly = yield* resolveEditorLaunch(
@@ -302,102 +338,102 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
});
const ideaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineAndColumn, {
command: "idea",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const aquaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "aqua" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "aqua" },
"darwin",
);
assert.deepEqual(aquaLineAndColumn, {
command: "aqua",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const clionLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "clion" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "clion" },
"darwin",
);
assert.deepEqual(clionLineAndColumn, {
command: "clion",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const datagripLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "datagrip" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "datagrip" },
"darwin",
);
assert.deepEqual(datagripLineAndColumn, {
command: "datagrip",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const dataspellLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "dataspell" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "dataspell" },
"darwin",
);
assert.deepEqual(dataspellLineAndColumn, {
command: "dataspell",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const golandLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "goland" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "goland" },
"darwin",
);
assert.deepEqual(golandLineAndColumn, {
command: "goland",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const phpstormLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "phpstorm" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "phpstorm" },
"darwin",
);
assert.deepEqual(phpstormLineAndColumn, {
command: "phpstorm",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const pycharmLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "pycharm" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "pycharm" },
"darwin",
);
assert.deepEqual(pycharmLineAndColumn, {
command: "pycharm",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const riderLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rider" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rider" },
"darwin",
);
assert.deepEqual(riderLineAndColumn, {
command: "rider",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const rubymineLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rubymine" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rubymine" },
"darwin",
);
assert.deepEqual(rubymineLineAndColumn, {
command: "rubymine",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const rustroverLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "rustrover" },
{ cwd: "/tmp/workspace/src/process/externalLauncher.ts:71:5", editor: "rustrover" },
"darwin",
);
assert.deepEqual(rustroverLineAndColumn, {
command: "rustrover",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/process/externalLauncher.ts"],
});
const webstormLineOnly = yield* resolveEditorLaunch(
@@ -415,7 +451,7 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
yield* fs.writeFileString(path.join(dir, "zeditor"), "#!/bin/sh\nexit 0\n");
yield* fs.chmod(path.join(dir, "zeditor"), 0o755);
@@ -477,23 +513,147 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
);
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
it("resolveBrowserLaunch maps default browser launchers by platform", () => {
const target = "https://example.com/some path?name=o'hara";
assert.deepEqual(resolveBrowserLaunch(target, "darwin").command, "open");
assert.deepEqual(resolveBrowserLaunch(target, "darwin").args, [target]);
assert.deepEqual(resolveBrowserLaunch(target, "darwin").options, {
detached: true,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).command, "xdg-open");
assert.deepEqual(resolveBrowserLaunch(target, "linux", {}).args, [target]);
const windows = resolveBrowserLaunch(target, "win32", {
SYSTEMROOT: "C:\\Windows",
});
assert.equal(windows.command, "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe");
assert.deepEqual(windows.args, [
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
encodeUtf16LeBase64(
"$ProgressPreference = 'SilentlyContinue'; Start 'https://example.com/some path?name=o''hara'",
),
]);
assert.deepEqual(windows.options, {
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
});
it("resolveBrowserLaunch opens through Windows from WSL when not remote", () => {
const launch = resolveBrowserLaunch("https://example.com", "linux", {
WSL_DISTRO_NAME: "Ubuntu",
});
assert.equal(launch.command, "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe");
assert.equal(launch.options.detached, true);
});
it("resolveBrowserLaunch keeps xdg-open for WSL over SSH", () => {
const launch = resolveBrowserLaunch("https://example.com", "linux", {
WSL_DISTRO_NAME: "Ubuntu",
SSH_CONNECTION: "client server",
});
assert.equal(launch.command, "xdg-open");
});
it.layer(NodeServices.layer)("launchBrowser", (it) => {
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
let spawnedCommand: ChildProcess.StandardCommand | undefined;
let didUnref = false;
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) =>
Effect.sync(() => {
assert.equal(ChildProcess.isStandardCommand(command), true);
if (!ChildProcess.isStandardCommand(command)) {
throw new Error("Expected a standard command");
}
spawnedCommand = command;
return makeMockDetachedHandle(() => {
didUnref = true;
});
}),
});
const result = yield* launchBrowser("https://example.com").pipe(
Effect.provide(spawnerLayer),
Effect.result,
);
assertSuccess(result, undefined);
assert.ok(spawnedCommand);
const expectedLaunch = resolveBrowserLaunch("https://example.com");
assert.equal(spawnedCommand.command, expectedLaunch.command);
assert.deepEqual(spawnedCommand.args, expectedLaunch.args);
assert.deepEqual(spawnedCommand.options, expectedLaunch.options);
assert.equal(didUnref, true);
}),
);
});
it.layer(NodeServices.layer)("launchEditorProcess", (it) => {
it.effect("spawns through the ChildProcessSpawner service and unrefs the handle", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.StandardCommand | undefined;
let didUnref = false;
const expectedArgs = ["-e", "process.exit(0)"];
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {
spawn: (command) =>
Effect.sync(() => {
assert.equal(ChildProcess.isStandardCommand(command), true);
if (!ChildProcess.isStandardCommand(command)) {
throw new Error("Expected a standard command");
}
spawnedCommand = command;
return makeMockDetachedHandle(() => {
didUnref = true;
});
}),
});
const result = yield* launchEditorProcess({
command: process.execPath,
args: expectedArgs,
}).pipe(Effect.provide(spawnerLayer), Effect.result);
assertSuccess(result, undefined);
assert.ok(spawnedCommand);
assert.equal(spawnedCommand.command, process.execPath);
assert.deepEqual(
spawnedCommand.args,
process.platform === "win32" ? expectedArgs.map((arg) => `"${arg}"`) : expectedArgs,
);
assert.deepEqual(spawnedCommand.options, {
detached: true,
shell: process.platform === "win32",
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
});
assert.equal(didUnref, true);
}),
);
it.effect("rejects when command does not exist", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
const spawnerLayer = Layer.mock(ChildProcessSpawner.ChildProcessSpawner, {});
const result = yield* launchEditorProcess({
command: `t3code-no-such-command-${yield* Random.nextUUIDv4}`,
args: [],
}).pipe(Effect.result);
}).pipe(Effect.provide(spawnerLayer), Effect.result);
assert.equal(result._tag, "Failure");
}),
);
@@ -504,7 +664,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
@@ -526,7 +686,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
const env = {
PATH: dir,
@@ -540,7 +700,7 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
@@ -554,8 +714,8 @@ it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-external-launcher-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
+364
View File
@@ -0,0 +1,364 @@
/**
* ExternalLauncher - external application launch service interface.
*
* Owns process launch helpers for browser URLs and workspace paths
* in configured editor integrations.
*
* @module ExternalLauncher
*/
import {
EDITORS,
ExternalLauncherError,
type EditorId,
type LaunchEditorInput,
} from "@t3tools/contracts";
import { isCommandAvailable, type CommandAvailabilityOptions } from "@t3tools/shared/shell";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
// ==============================
// Definitions
// ==============================
export { ExternalLauncherError };
export type { LaunchEditorInput };
export { isCommandAvailable } from "@t3tools/shared/shell";
interface EditorLaunch {
readonly command: string;
readonly args: ReadonlyArray<string>;
}
interface ProcessLaunch {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly options: ChildProcess.CommandOptions;
}
interface TargetPathAndPosition {
readonly path: string;
readonly line: string;
readonly column: Option.Option<string>;
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
const POWERSHELL_ARGUMENTS_PREFIX = [
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
] as const;
const DETACHED_IGNORE_STDIO_OPTIONS = {
detached: true,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
} as const satisfies ChildProcess.CommandOptions;
function parseTargetPathAndPosition(target: string): Option.Option<TargetPathAndPosition> {
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
if (!match?.[1] || !match[2]) {
return Option.none();
}
return Option.some({
path: match[1],
line: match[2],
column: Option.fromUndefinedOr(match[3]),
});
}
function resolveCommandEditorArgs(
editor: (typeof EDITORS)[number],
target: string,
): ReadonlyArray<string> {
const parsedTarget = parseTargetPathAndPosition(target);
switch (editor.launchStyle) {
case "direct-path":
return [target];
case "goto":
return Option.isSome(parsedTarget) ? ["--goto", target] : [target];
case "line-column":
return Option.match(parsedTarget, {
onNone: () => [target],
onSome: ({ path, line, column }) => [
"--line",
line,
...Option.match(column, {
onNone: () => [],
onSome: (value) => ["--column", value],
}),
path,
],
});
}
}
function resolveEditorArgs(
editor: (typeof EDITORS)[number],
target: string,
): ReadonlyArray<string> {
const baseArgs = "baseArgs" in editor ? editor.baseArgs : [];
return [...baseArgs, ...resolveCommandEditorArgs(editor, target)];
}
function resolveAvailableCommand(
commands: ReadonlyArray<string>,
options: CommandAvailabilityOptions = {},
): Option.Option<string> {
for (const command of commands) {
if (isCommandAvailable(command, options)) {
return Option.some(command);
}
}
return Option.none();
}
function encodeUtf16LeBase64(input: string): string {
const bytes = new Uint8Array(input.length * 2);
for (let index = 0; index < input.length; index += 1) {
const code = input.charCodeAt(index);
bytes[index * 2] = code & 0xff;
bytes[index * 2 + 1] = code >>> 8;
}
return Encoding.encodeBase64(bytes);
}
function escapePowerShellStringLiteral(input: string): string {
return `'${input.replaceAll("'", "''")}'`;
}
function resolvePowerShellPath(env: NodeJS.ProcessEnv = process.env): string {
return `${env.SYSTEMROOT || env.windir || String.raw`C:\Windows`}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`;
}
function resolveWslPowerShellPath(): string {
return "/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe";
}
function shouldUseWindowsBrowserFromWsl(
platform: NodeJS.Platform,
env: NodeJS.ProcessEnv = process.env,
): boolean {
return (
platform === "linux" &&
(env.WSL_DISTRO_NAME !== undefined || env.WSL_INTEROP !== undefined) &&
env.SSH_CONNECTION === undefined &&
env.SSH_TTY === undefined &&
env.container === undefined
);
}
function resolveWindowsBrowserLaunch(target: string, command: string): ProcessLaunch {
const encodedCommand = encodeUtf16LeBase64(
`$ProgressPreference = 'SilentlyContinue'; Start ${escapePowerShellStringLiteral(target)}`,
);
return {
command,
args: [...POWERSHELL_ARGUMENTS_PREFIX, encodedCommand],
options: {
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
};
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
export function resolveBrowserLaunch(
target: string,
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ProcessLaunch {
if (platform === "darwin") {
return {
command: "open",
args: [target],
options: DETACHED_IGNORE_STDIO_OPTIONS,
};
}
if (platform === "win32") {
return resolveWindowsBrowserLaunch(target, resolvePowerShellPath(env));
}
if (shouldUseWindowsBrowserFromWsl(platform, env)) {
return resolveWindowsBrowserLaunch(target, resolveWslPowerShellPath());
}
return {
command: "xdg-open",
args: [target],
options: DETACHED_IGNORE_STDIO_OPTIONS,
};
}
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.commands === null) {
const command = fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
continue;
}
const command = resolveAvailableCommand(editor.commands, { platform, env });
if (Option.isSome(command)) {
available.push(editor.id);
}
}
return available;
}
/**
* ExternalLauncherShape - Service API for browser and editor launch actions.
*/
export interface ExternalLauncherShape {
/**
* Launch a URL target in the default browser.
*/
readonly launchBrowser: (target: string) => Effect.Effect<void, ExternalLauncherError>;
/**
* Launch a workspace path in a selected editor integration.
*
* Launches the editor as a detached process so server startup is not blocked.
*/
readonly launchEditor: (input: LaunchEditorInput) => Effect.Effect<void, ExternalLauncherError>;
}
/**
* ExternalLauncher - Service tag for browser/editor launch operations.
*/
export class ExternalLauncher extends Context.Service<ExternalLauncher, ExternalLauncherShape>()(
"t3/process/ExternalLauncher",
) {}
// ==============================
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
input: LaunchEditorInput,
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<EditorLaunch, ExternalLauncherError> {
yield* Effect.annotateCurrentSpan({
"externalLauncher.editor": input.editor,
"externalLauncher.cwd": input.cwd,
"externalLauncher.platform": platform,
});
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new ExternalLauncherError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.commands) {
const command = Option.getOrElse(
resolveAvailableCommand(editorDef.commands, { platform, env }),
() => editorDef.commands[0],
);
return {
command,
args: resolveEditorArgs(editorDef, input.cwd),
};
}
if (editorDef.id !== "file-manager") {
return yield* new ExternalLauncherError({ message: `Unsupported editor: ${input.editor}` });
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
});
const launchAndUnref = Effect.fn("externalLauncher.launchAndUnref")(function* (
launch: ProcessLaunch,
errorMessage: string,
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make(launch.command, launch.args, launch.options);
yield* spawner.spawn(command).pipe(
Effect.flatMap((handle) => handle.unref),
Effect.asVoid,
Effect.scoped,
Effect.mapError((cause) => new ExternalLauncherError({ message: errorMessage, cause })),
);
});
export const launchBrowser = Effect.fn("externalLauncher.launchBrowser")(function* (
target: string,
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
return yield* launchAndUnref(resolveBrowserLaunch(target), "Browser auto-open failed");
});
export const launchEditorProcess = Effect.fn("externalLauncher.launchEditorProcess")(function* (
launch: EditorLaunch,
): Effect.fn.Return<void, ExternalLauncherError, ChildProcessSpawner.ChildProcessSpawner> {
if (!isCommandAvailable(launch.command)) {
return yield* new ExternalLauncherError({
message: `Editor command not found: ${launch.command}`,
});
}
const isWin32 = process.platform === "win32";
yield* launchAndUnref(
{
command: launch.command,
args: isWin32 ? launch.args.map((arg) => `"${arg}"`) : [...launch.args],
options: {
detached: true,
shell: isWin32,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
},
"failed to spawn detached process",
);
});
const make = Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return {
launchBrowser: (target) =>
launchBrowser(target).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
launchEditor: (input) =>
Effect.flatMap(resolveEditorLaunch(input), (launch) =>
launchEditorProcess(launch).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
),
),
} satisfies ExternalLauncherShape;
});
export const layer = Layer.effect(ExternalLauncher, make);
+273 -16
View File
@@ -1,25 +1,282 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import { ChildProcessSpawner } from "effect/unstable/process";
import { isWindowsCommandNotFound, runProcess } from "./processRunner.ts";
import {
isWindowsCommandNotFound,
ProcessOutputLimitError,
ProcessRunner,
ProcessTimeoutError,
layer as ProcessRunnerLive,
type ProcessRunInput,
} from "./processRunner.ts";
type ChildProcessCommand = {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
// Accesses private properties of ChildProcessCommand for testing purposes
function asChildProcessCommand(command: unknown): ChildProcessCommand {
return command as ChildProcessCommand;
}
function makeHandle(input: {
readonly stdout?: string | Stream.Stream<Uint8Array>;
readonly stderr?: string | Stream.Stream<Uint8Array>;
readonly code?: number;
readonly stdin?: ChildProcessSpawner.ChildProcessHandle["stdin"];
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
}) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: input.exitCode ?? Effect.succeed(ChildProcessSpawner.ExitCode(input.code ?? 0)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: input.stdin ?? Sink.drain,
stdout:
typeof input.stdout === "string"
? Stream.encodeText(Stream.make(input.stdout))
: (input.stdout ?? Stream.empty),
stderr:
typeof input.stderr === "string"
? Stream.encodeText(Stream.make(input.stderr))
: (input.stderr ?? Stream.empty),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function makeSpawner(
f: (command: ChildProcessCommand) => Effect.Effect<ChildProcessSpawner.ChildProcessHandle>,
) {
return ChildProcessSpawner.make((command) => f(asChildProcessCommand(command)));
}
const runWith =
(spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]) => (input: ProcessRunInput) =>
Effect.service(ProcessRunner).pipe(
Effect.flatMap((runner) =>
runner.run({
...input,
shell: input.shell ?? false,
}),
),
Effect.provide(
ProcessRunnerLive.pipe(
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
),
),
);
describe("runProcess", () => {
it("fails when output exceeds max buffer in default mode", async () => {
await expect(
runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], { maxBufferBytes: 128 }),
).rejects.toThrow("exceeded stdout buffer limit");
it.effect("collects stdout through an injected ChildProcessSpawner", () =>
Effect.gen(function* () {
const spawner = makeSpawner((command) =>
Effect.sync(() => {
expect(command.command).toBe("fake");
expect(command.args).toEqual(["stdout-bytes", "32"]);
return makeHandle({ stdout: "x".repeat(32) });
}),
);
const result = yield* runWith(spawner)({
command: "fake",
args: ["stdout-bytes", "32"],
});
expect(result.code).toBe(0);
expect(result.stdout).toBe("x".repeat(32));
expect(result.timedOut).toBe(false);
}),
);
it.effect("runs through the ProcessRunner service", () => {
const spawner = makeSpawner((command) =>
Effect.sync(() => {
expect(command.command).toBe("fake");
expect(command.args).toEqual(["--service"]);
return makeHandle({ stdout: "service ok" });
}),
);
const layer = ProcessRunnerLive.pipe(
Layer.provide(Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)),
);
return Effect.gen(function* () {
const runner = yield* ProcessRunner;
const result = yield* runner.run({
command: "fake",
args: ["--service"],
});
expect(result.stdout).toBe("service ok");
}).pipe(Effect.provide(layer));
});
it("truncates output when outputMode is truncate", async () => {
const result = await runProcess("node", ["-e", "process.stdout.write('x'.repeat(2048))"], {
maxBufferBytes: 128,
outputMode: "truncate",
});
it.effect("fails when output exceeds max buffer in default mode", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
});
const error = yield* runWith(spawner)({
command: "fake",
args: ["stdout-bytes", "2048"],
maxOutputBytes: 128,
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(ProcessOutputLimitError);
}),
);
it.effect("fails fast on output limit before timeout for long-running output", () =>
Effect.gen(function* () {
const textChunk = "x".repeat(64);
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
stdout: Stream.fromIterable(Array.from({ length: 10 }, () => textChunk)).pipe(
Stream.encodeText,
),
exitCode: Effect.never,
}),
),
);
const error = yield* runWith(spawner)({
command: "fake",
args: ["spam-stdout"],
maxOutputBytes: 128,
timeout: "2 seconds",
}).pipe(Effect.flip);
expect(error).toBeInstanceOf(ProcessOutputLimitError);
}),
);
it.effect("truncates output when outputMode is truncate", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stdout: "x".repeat(2048) })));
const result = yield* runWith(spawner)({
command: "fake",
args: ["stdout-bytes", "2048"],
maxOutputBytes: 128,
outputMode: "truncate",
});
expect(result.code).toBe(0);
expect(result.stdout.length).toBeLessThanOrEqual(128);
expect(result.stdoutTruncated).toBe(true);
expect(result.stderrTruncated).toBe(false);
}),
);
it.effect("writes stdin before waiting for exit", () =>
Effect.gen(function* () {
const stdinWritten = yield* Deferred.make<void>();
const decoder = new TextDecoder();
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
stdout: "stdin payload",
stdin: Sink.forEach((chunk: Uint8Array) => {
const text = decoder.decode(chunk, { stream: true });
return text.includes("stdin payload")
? Deferred.succeed(stdinWritten, undefined)
: Effect.void;
}),
exitCode: Deferred.await(stdinWritten).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
);
const result = yield* runWith(spawner)({
command: "fake",
args: ["stdin-echo"],
stdin: "stdin payload",
});
expect(result.stdout).toBe("stdin payload");
expect(result.code).toBe(0);
}),
);
it.effect("returns output for non-zero exit codes", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() => Effect.succeed(makeHandle({ stderr: "boom", code: 2 })));
const result = yield* runWith(spawner)({
command: "fake",
args: ["stderr-exit", "boom", "2"],
});
expect(result.code).toBe(2);
expect(result.stderr).toBe("boom");
}),
);
it.effect("fails on timeout", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
exitCode: Effect.never,
}),
),
);
const errorFiber = yield* runWith(spawner)({
command: "fake",
args: ["sleep"],
timeout: "50 millis",
}).pipe(Effect.flip, Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(errorFiber);
expect(error).toBeInstanceOf(ProcessTimeoutError);
}),
);
it.effect("returns a synthetic timed out result when timeoutBehavior is timedOutResult", () =>
Effect.gen(function* () {
const spawner = makeSpawner(() =>
Effect.succeed(
makeHandle({
exitCode: Effect.never,
}),
),
);
const resultFiber = yield* runWith(spawner)({
command: "fake",
args: ["sleep"],
timeout: "50 millis",
timeoutBehavior: "timedOutResult",
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(50));
const result = yield* Fiber.join(resultFiber);
expect(result).toMatchObject({
stdout: "",
stderr: "",
code: null,
timedOut: true,
stdoutTruncated: false,
stderrTruncated: false,
});
}),
);
});
describe("isWindowsCommandNotFound", () => {
+295 -245
View File
@@ -1,42 +1,100 @@
// @effect-diagnostics nodeBuiltinImport:off
import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
import * as NodeTimers from "node:timers";
export interface ProcessRunOptions {
cwd?: string | undefined;
timeoutMs?: number | undefined;
env?: NodeJS.ProcessEnv | undefined;
stdin?: string | undefined;
allowNonZeroExit?: boolean | undefined;
maxBufferBytes?: number | undefined;
outputMode?: "error" | "truncate" | undefined;
import * as Data from "effect/Data";
import * as Context from "effect/Context";
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 PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
collectUint8StreamText,
type CollectedUint8StreamText,
} from "./stream/collectUint8StreamText.ts";
export interface ProcessRunInput {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly spawnCwd?: string | undefined;
readonly timeout?: Duration.Input | undefined;
readonly env?: NodeJS.ProcessEnv | undefined;
readonly stdin?: string | undefined;
readonly maxOutputBytes?: number | undefined;
readonly outputMode?: "error" | "truncate" | undefined;
readonly truncatedMarker?: string | undefined;
readonly shell?: boolean | string | undefined;
/**
* On timeout, return a synthetic timedOut result.
* Partial stdout/stderr are not preserved.
*/
readonly timeoutBehavior?: "error" | "timedOutResult" | undefined;
}
export interface ProcessRunResult {
stdout: string;
stderr: string;
code: number | null;
signal: NodeJS.Signals | null;
timedOut: boolean;
stdoutTruncated?: boolean | undefined;
stderrTruncated?: boolean | undefined;
export interface ProcessRunOutput {
readonly stdout: string;
readonly stderr: string;
readonly code: ChildProcessSpawner.ExitCode | null;
readonly timedOut: boolean;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
function commandLabel(command: string, args: readonly string[]): string {
return [command, ...args].join(" ");
export class ProcessSpawnError extends Data.TaggedError("ProcessSpawnError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly cause: unknown;
}> {}
export class ProcessStdinError extends Data.TaggedError("ProcessStdinError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly cause: unknown;
}> {}
export class ProcessOutputLimitError extends Data.TaggedError("ProcessOutputLimitError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly stream: "stdout" | "stderr";
readonly maxBytes: number;
}> {}
export class ProcessReadError extends Data.TaggedError("ProcessReadError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly stream: "stdout" | "stderr" | "exitCode";
readonly cause: unknown;
}> {}
export class ProcessTimeoutError extends Data.TaggedError("ProcessTimeoutError")<{
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly timeoutMs: number;
}> {}
export type ProcessRunError =
| ProcessSpawnError
| ProcessStdinError
| ProcessOutputLimitError
| ProcessReadError
| ProcessTimeoutError;
export interface ProcessRunnerShape {
readonly run: (input: ProcessRunInput) => Effect.Effect<ProcessRunOutput, ProcessRunError>;
}
function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to run ${commandLabel(command, args)}.`);
}
export class ProcessRunner extends Context.Service<ProcessRunner, ProcessRunnerShape>()(
"t3/process/ProcessRunner",
) {}
const maybeCode = (error as NodeJS.ErrnoException).code;
if (maybeCode === "ENOENT") {
return new Error(`Command not found: ${command}`);
}
return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
}
const DEFAULT_TIMEOUT = "60 seconds";
const DEFAULT_MAX_OUTPUT_BYTES = 8 * 1024 * 1024;
const WINDOWS_COMMAND_NOT_FOUND_PATTERNS = [
/is not recognized as an internal or external command/i,
@@ -57,230 +115,222 @@ export function isWindowsCommandNotFound(code: number | null, stderr: string): b
return hasWindowsCommandNotFoundMessage(stderr);
}
function normalizeExitError(
command: string,
args: readonly string[],
result: ProcessRunResult,
): Error {
if (isWindowsCommandNotFound(result.code, result.stderr)) {
return new Error(`Command not found: ${command}`);
const collectText = Effect.fn("processRunner.collectText")(function* (input: {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly cwd?: string | undefined;
readonly streamName: "stdout" | "stderr";
readonly stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly maxOutputBytes: number;
readonly outputMode: "error" | "truncate";
readonly truncatedMarker: string;
}) {
const stream = input.stream.pipe(
Stream.mapError(
(cause) =>
new ProcessReadError({
command: input.command,
args: input.args,
cwd: input.cwd,
stream: input.streamName,
cause,
}),
),
);
if (input.outputMode === "truncate") {
return yield* collectUint8StreamText({
stream,
maxBytes: input.maxOutputBytes,
truncatedMarker: input.truncatedMarker,
});
}
const reason = result.timedOut
? "timed out"
: `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
const stderr = result.stderr.trim();
const detail = stderr.length > 0 ? ` ${stderr}` : "";
return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
}
return yield* stream.pipe(
Stream.runFoldEffect<
{
readonly chunks: Uint8Array<ArrayBufferLike>[];
readonly bytes: number;
},
Uint8Array<ArrayBufferLike>,
ProcessOutputLimitError | ProcessReadError,
never
>(
() => ({ chunks: [], bytes: 0 }),
(state, chunk) => {
const remainingBytes = input.maxOutputBytes - state.bytes;
if (remainingBytes <= 0 || chunk.byteLength > remainingBytes) {
return Effect.fail(
new ProcessOutputLimitError({
command: input.command,
args: input.args,
cwd: input.cwd,
stream: input.streamName,
maxBytes: input.maxOutputBytes,
}),
);
}
function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
if (!(error instanceof Error)) {
return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
}
return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
}
state.chunks.push(chunk);
return Effect.succeed({
chunks: state.chunks,
bytes: state.bytes + chunk.byteLength,
});
},
),
Effect.map(
(state): CollectedUint8StreamText => ({
text: Buffer.concat(state.chunks, state.bytes).toString("utf8"),
bytes: state.bytes,
truncated: false,
}),
),
);
});
function normalizeBufferError(
command: string,
args: readonly string[],
stream: "stdout" | "stderr",
maxBufferBytes: number,
): Error {
return new Error(
`${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
function finalizeRunProcess<R>(
effect: Effect.Effect<ProcessRunOutput, ProcessRunError, R | Scope.Scope>,
input: ProcessRunInput,
): Effect.Effect<ProcessRunOutput, ProcessRunError, Exclude<R, Scope.Scope>> {
const timeout = Duration.fromInputUnsafe(input.timeout ?? DEFAULT_TIMEOUT);
const timeoutBehavior = input.timeoutBehavior ?? "error";
return effect.pipe(
Effect.scoped,
Effect.timeoutOption(timeout),
Effect.flatMap((result) => {
if (Option.isSome(result)) {
return Effect.succeed(result.value);
}
if (timeoutBehavior === "timedOutResult") {
return Effect.succeed({
stdout: "",
stderr: "",
code: null,
timedOut: true,
stdoutTruncated: false,
stderrTruncated: false,
} satisfies ProcessRunOutput);
}
return Effect.fail(
new ProcessTimeoutError({
command: input.command,
args: input.args,
cwd: input.cwd,
timeoutMs: Duration.toMillis(timeout),
}),
);
}),
);
}
const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
const runProcessCore = Effect.fn("processRunner.runProcessCore")(function* (
spawner: ChildProcessSpawner.ChildProcessSpawner["Service"],
input: ProcessRunInput,
): Effect.fn.Return<ProcessRunOutput, ProcessRunError, Scope.Scope> {
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const outputMode = input.outputMode ?? "error";
const truncatedMarker = input.truncatedMarker ?? "";
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill(signal);
}
const child = yield* spawner
.spawn(
ChildProcess.make(input.command, [...input.args], {
...((input.spawnCwd ?? input.cwd) ? { cwd: input.spawnCwd ?? input.cwd } : {}),
...(input.env !== undefined
? {
env: input.env,
extendEnv: true,
}
: {}),
...(input.shell !== undefined ? { shell: input.shell } : {}),
}),
)
.pipe(
Effect.mapError(
(cause) =>
new ProcessSpawnError({
command: input.command,
args: input.args,
cwd: input.cwd,
cause,
}),
),
);
const writeStdin =
input.stdin === undefined
? Effect.void
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
Effect.mapError(
(cause) =>
new ProcessStdinError({
command: input.command,
args: input.args,
cwd: input.cwd,
cause,
}),
),
);
const [stdout, stderr] = yield* Effect.all(
[
collectText({
command: input.command,
args: input.args,
cwd: input.cwd,
streamName: "stdout",
stream: child.stdout,
maxOutputBytes,
outputMode,
truncatedMarker,
}),
collectText({
command: input.command,
args: input.args,
cwd: input.cwd,
streamName: "stderr",
stream: child.stderr,
maxOutputBytes,
outputMode,
truncatedMarker,
}),
writeStdin,
],
{ concurrency: "unbounded" },
);
const exitCode = yield* child.exitCode.pipe(
Effect.mapError(
(cause) =>
new ProcessReadError({
command: input.command,
args: input.args,
cwd: input.cwd,
stream: "exitCode",
cause,
}),
),
);
function appendChunkWithinLimit(
target: string,
currentBytes: number,
chunk: Buffer,
maxBytes: number,
): {
next: string;
nextBytes: number;
truncated: boolean;
} {
const remaining = maxBytes - currentBytes;
if (remaining <= 0) {
return { next: target, nextBytes: currentBytes, truncated: true };
}
if (chunk.length <= remaining) {
return {
next: `${target}${chunk.toString()}`,
nextBytes: currentBytes + chunk.length,
truncated: false,
};
}
return {
next: `${target}${chunk.subarray(0, remaining).toString()}`,
nextBytes: currentBytes + remaining,
truncated: true,
};
}
stdout: stdout.text,
stderr: stderr.text,
code: exitCode,
timedOut: false,
stdoutTruncated: stdout.truncated,
stderrTruncated: stderr.truncated,
} satisfies ProcessRunOutput;
});
export async function runProcess(
command: string,
args: readonly string[],
options: ProcessRunOptions = {},
): Promise<ProcessRunResult> {
const timeoutMs = options.timeoutMs ?? 60_000;
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
const outputMode = options.outputMode ?? "error";
export const make = Effect.fn("makeProcessRunner")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return new Promise<ProcessRunResult>((resolve, reject) => {
const child = spawn(command, args, {
cwd: options.cwd,
env: options.env,
stdio: "pipe",
shell: process.platform === "win32",
});
const run: ProcessRunnerShape["run"] = (input) =>
finalizeRunProcess(runProcessCore(spawner, input), input);
let stdout = "";
let stderr = "";
let stdoutBytes = 0;
let stderrBytes = 0;
let stdoutTruncated = false;
let stderrTruncated = false;
let timedOut = false;
let settled = false;
let forceKillTimer: ReturnType<typeof NodeTimers.setTimeout> | null = null;
// @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; moving this runner to Effect timers is a separate refactor.
const timeoutTimer = NodeTimers.setTimeout(() => {
timedOut = true;
killChild(child, "SIGTERM");
// @effect-diagnostics-next-line globalTimers:off - Promise/child_process boundary; see timeout timer above.
forceKillTimer = NodeTimers.setTimeout(() => {
killChild(child, "SIGKILL");
}, 1_000);
}, timeoutMs);
const finalize = (callback: () => void): void => {
if (settled) return;
settled = true;
NodeTimers.clearTimeout(timeoutTimer);
if (forceKillTimer) {
NodeTimers.clearTimeout(forceKillTimer);
}
callback();
};
const fail = (error: Error): void => {
killChild(child, "SIGTERM");
finalize(() => {
reject(error);
});
};
const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
const text = chunkBuffer.toString();
const byteLength = chunkBuffer.length;
if (stream === "stdout") {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
stdout = appended.next;
stdoutBytes = appended.nextBytes;
stdoutTruncated = stdoutTruncated || appended.truncated;
return null;
}
stdout += text;
stdoutBytes += byteLength;
if (stdoutBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stdout", maxBufferBytes);
}
} else {
if (outputMode === "truncate") {
const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
stderr = appended.next;
stderrBytes = appended.nextBytes;
stderrTruncated = stderrTruncated || appended.truncated;
return null;
}
stderr += text;
stderrBytes += byteLength;
if (stderrBytes > maxBufferBytes) {
return normalizeBufferError(command, args, "stderr", maxBufferBytes);
}
}
return null;
};
child.stdout.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stdout", chunk);
if (error) {
fail(error);
}
});
child.stderr.on("data", (chunk: Buffer | string) => {
const error = appendOutput("stderr", chunk);
if (error) {
fail(error);
}
});
child.once("error", (error) => {
finalize(() => {
reject(normalizeSpawnError(command, args, error));
});
});
child.once("close", (code, signal) => {
const result: ProcessRunResult = {
stdout,
stderr,
code,
signal,
timedOut,
stdoutTruncated,
stderrTruncated,
};
finalize(() => {
if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
reject(normalizeExitError(command, args, result));
return;
}
resolve(result);
});
});
child.stdin.once("error", (error) => {
fail(normalizeStdinError(command, args, error));
});
if (options.stdin !== undefined) {
child.stdin.write(options.stdin, (error) => {
if (error) {
fail(normalizeStdinError(command, args, error));
return;
}
child.stdin.end();
});
return;
}
child.stdin.end();
return ProcessRunner.of({
run,
});
}
});
export const layer = Layer.effect(ProcessRunner, make());
@@ -25,6 +25,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 1 }),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: (workspaceRoot) =>
@@ -35,6 +36,7 @@ const makeProjectionSnapshotQueryLayer = (project: OrchestrationProject) =>
Effect.succeed(projectId === project.id ? Option.some(project) : Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
});
@@ -1,15 +1,13 @@
// @effect-diagnostics nodeBuiltinImport:off
import { realpathSync } from "node:fs";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
import * as Path from "effect/Path";
import { TestClock } from "effect/testing";
import { runProcess } from "../../processRunner.ts";
import * as ProcessRunner from "../../processRunner.ts";
import { RepositoryIdentityResolver } from "../Services/RepositoryIdentityResolver.ts";
import {
makeRepositoryIdentityResolver,
@@ -17,11 +15,17 @@ import {
} from "./RepositoryIdentityResolver.ts";
const normalizePathSeparators = (value: string) => value.replaceAll("\\", "/");
const normalizeResolvedPath = (value: string) =>
normalizePathSeparators(realpathSync.native(value));
const normalizeResolvedPath = (value: string) => normalizePathSeparators(value);
const git = (cwd: string, args: ReadonlyArray<string>) =>
Effect.promise(() => runProcess("git", ["-C", cwd, ...args]));
Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
return yield* processRunner.run({
command: "git",
args: ["-C", cwd, ...args],
shell: process.platform === "win32",
});
}).pipe(Effect.provide(ProcessRunner.layer));
const makeRepositoryIdentityResolverTestLayer = (options: {
readonly positiveCacheTtl?: Duration.Input;
@@ -33,7 +37,7 @@ const makeRepositoryIdentityResolverTestLayer = (options: {
cacheCapacity: 16,
...options,
}),
);
).pipe(Layer.provide(ProcessRunner.layer));
it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
it.effect("normalizes equivalent GitHub remotes into a stable repository identity", () =>
@@ -48,10 +52,13 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(cwd);
const resolvedIdentityRoot =
identity?.rootPath === undefined ? "" : yield* fileSystem.realPath(identity.rootPath);
const resolvedCwd = yield* fileSystem.realPath(cwd);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(cwd));
expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe(normalizeResolvedPath(resolvedCwd));
expect(identity?.displayName).toBe("t3tools/t3code");
expect(identity?.provider).toBe("github");
expect(identity?.owner).toBe("t3tools");
@@ -62,10 +69,11 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
it.effect("returns the git top-level root path when resolving from a nested workspace", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const repoRoot = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-repository-identity-nested-root-test-",
});
const nestedWorkspace = `${repoRoot}/packages/web`;
const nestedWorkspace = path.join(repoRoot, "packages", "web");
yield* fileSystem.makeDirectory(nestedWorkspace, { recursive: true });
yield* git(repoRoot, ["init"]);
@@ -73,10 +81,15 @@ it.layer(NodeServices.layer)("RepositoryIdentityResolverLive", (it) => {
const resolver = yield* RepositoryIdentityResolver;
const identity = yield* resolver.resolve(nestedWorkspace);
const resolvedIdentityRoot =
identity?.rootPath === undefined ? "" : yield* fileSystem.realPath(identity.rootPath);
const resolvedRepoRoot = yield* fileSystem.realPath(repoRoot);
expect(identity).not.toBeNull();
expect(identity?.canonicalKey).toBe("github.com/t3tools/t3code");
expect(normalizeResolvedPath(identity?.rootPath ?? "")).toBe(normalizeResolvedPath(repoRoot));
expect(normalizeResolvedPath(resolvedIdentityRoot)).toBe(
normalizeResolvedPath(resolvedRepoRoot),
);
}).pipe(Effect.provide(RepositoryIdentityResolverLive)),
);
@@ -9,7 +9,7 @@ import {
normalizeGitRemoteUrl,
} from "@t3tools/shared/git";
import { runProcess } from "../../processRunner.ts";
import * as ProcessRunner from "../../processRunner.ts";
import {
RepositoryIdentityResolver,
type RepositoryIdentityResolverShape,
@@ -83,50 +83,63 @@ interface RepositoryIdentityResolverOptions {
readonly negativeCacheTtl?: Duration.Input;
}
async function resolveRepositoryIdentityCacheKey(cwd: string): Promise<string> {
const resolveRepositoryIdentityCacheKey = Effect.fn("resolveRepositoryIdentityCacheKey")(function* (
cwd: string,
) {
const processRunner = yield* ProcessRunner.ProcessRunner;
let cacheKey = cwd;
try {
const topLevelResult = await runProcess("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
allowNonZeroExit: true,
});
if (topLevelResult.code !== 0) {
return cacheKey;
}
const candidate = topLevelResult.stdout.trim();
if (candidate.length > 0) {
cacheKey = candidate;
}
} catch {
const topLevelResult = yield* processRunner
.run({
command: "git",
args: ["-C", cwd, "rev-parse", "--show-toplevel"],
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
if (topLevelResult._tag === "None" || topLevelResult.value.code !== 0) {
return cacheKey;
}
return cacheKey;
}
const candidate = topLevelResult.value.stdout.trim();
if (candidate.length > 0) {
cacheKey = candidate;
}
async function resolveRepositoryIdentityFromCacheKey(
cacheKey: string,
): Promise<RepositoryIdentity | null> {
try {
const remoteResult = await runProcess("git", ["-C", cacheKey, "remote", "-v"], {
allowNonZeroExit: true,
});
if (remoteResult.code !== 0) {
return cacheKey;
});
const resolveRepositoryIdentityFromCacheKey = Effect.fn("resolveRepositoryIdentityFromCacheKey")(
function* (
cacheKey: string,
): Effect.fn.Return<RepositoryIdentity | null, never, ProcessRunner.ProcessRunner> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const remoteResult = yield* processRunner
.run({
command: "git",
args: ["-C", cacheKey, "remote", "-v"],
timeoutBehavior: "timedOutResult",
shell: process.platform === "win32",
})
.pipe(Effect.option);
if (remoteResult._tag === "None" || remoteResult.value.code !== 0) {
return null;
}
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.stdout));
const remote = pickPrimaryRemote(parseRemoteFetchUrls(remoteResult.value.stdout));
return remote ? buildRepositoryIdentity({ ...remote, rootPath: cacheKey }) : null;
} catch {
return null;
}
}
},
);
export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityResolver")(
function* (options: RepositoryIdentityResolverOptions = {}) {
const processRunner = yield* ProcessRunner.ProcessRunner;
const repositoryIdentityCache = yield* Cache.makeWith<string, RepositoryIdentity | null>(
(cacheKey) => Effect.promise(() => resolveRepositoryIdentityFromCacheKey(cacheKey)),
(cacheKey) =>
resolveRepositoryIdentityFromCacheKey(cacheKey).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
),
{
capacity: options.cacheCapacity ?? DEFAULT_REPOSITORY_IDENTITY_CACHE_CAPACITY,
timeToLive: Exit.match({
@@ -142,7 +155,9 @@ export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityR
const resolve: RepositoryIdentityResolverShape["resolve"] = Effect.fn(
"RepositoryIdentityResolver.resolve",
)(function* (cwd) {
const cacheKey = yield* Effect.promise(() => resolveRepositoryIdentityCacheKey(cwd));
const cacheKey = yield* resolveRepositoryIdentityCacheKey(cwd).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
);
return yield* Cache.get(repositoryIdentityCache, cacheKey);
});
@@ -155,4 +170,4 @@ export const makeRepositoryIdentityResolver = Effect.fn("makeRepositoryIdentityR
export const RepositoryIdentityResolverLive = Layer.effect(
RepositoryIdentityResolver,
makeRepositoryIdentityResolver(),
);
).pipe(Layer.provide(ProcessRunner.layer));
@@ -18,6 +18,7 @@ import {
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
query as claudeQuery,
type SlashCommand as ClaudeSlashCommand,
@@ -36,7 +37,6 @@ import {
spawnAndCollect,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import { makeClaudeEnvironment } from "../Drivers/ClaudeHome.ts";
const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabilities({
@@ -180,7 +180,7 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
];
function supportsClaudeOpus47(version: string | null | undefined): boolean {
return version ? compareCliVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
return version ? compareSemverVersions(version, MINIMUM_CLAUDE_OPUS_4_7_VERSION) >= 0 : false;
}
function getBuiltInClaudeModelsForVersion(
@@ -5,6 +5,7 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Types from "effect/Types";
import { ChildProcessSpawner } from "effect/unstable/process";
import * as CodexClient from "effect-codex-app-server/client";
@@ -22,13 +23,15 @@ import type {
import { ServerSettingsError } from "@t3tools/contracts";
import { createModelCapabilities } from "@t3tools/shared/model";
import { buildServerProvider, type ServerProviderDraft } from "../providerSnapshot.ts";
import {
AUTH_PROBE_TIMEOUT_MS,
buildServerProvider,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { expandHomePath } from "../../pathExpansion.ts";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
import packageJson from "../../../package.json" with { type: "json" };
const isCodexAppServerSpawnError = Schema.is(CodexErrors.CodexAppServerSpawnError);
const PROVIDER_PROBE_TIMEOUT_MS = 8_000;
const CODEX_PRESENTATION = {
displayName: "Codex",
showInteractionModeToggle: true,
@@ -245,12 +248,6 @@ export function buildCodexInitializeParams(): CodexSchema.V1InitializeParams {
};
}
// Wrapped with `scopedSafeTeardown("codex-probe")` rather than the usual
// `Effect.scoped` so that a defect from the `Layer.build` finalizer (e.g.
// `ChildProcess.kill` throwing because the `codex app-server` child exited
// early) cannot override a successful probe body. Without this guard the
// defect bubbles past `Effect.result` in `checkCodexProviderStatus`, dies
// `refreshOneSource`, and `providersRef` never receives the snapshot.
const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(function* (input: {
readonly binaryPath: string;
readonly homePath?: string;
@@ -320,7 +317,7 @@ const probeCodexAppServerProvider = Effect.fn("probeCodexAppServerProvider")(fun
models: appendCustomCodexModels(models, input.customModels ?? []),
skills: parseCodexSkillsListResponse(skillsResponse, input.cwd),
} satisfies CodexAppServerProviderSnapshot;
}, scopedSafeTeardown("codex-probe"));
});
const emptyCodexModelsFromSettings = (codexSettings: CodexSettings): ServerProvider["models"] =>
codexSettings.customModels
@@ -413,7 +410,7 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
}) => Effect.Effect<
CodexAppServerProviderSnapshot,
CodexErrors.CodexAppServerError,
ChildProcessSpawner.ChildProcessSpawner
ChildProcessSpawner.ChildProcessSpawner | Scope.Scope
> = probeCodexAppServerProvider,
environment: NodeJS.ProcessEnv = process.env,
): Effect.fn.Return<
@@ -447,7 +444,11 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
cwd: process.cwd(),
customModels: codexSettings.customModels,
environment,
}).pipe(Effect.timeoutOption(Duration.millis(PROVIDER_PROBE_TIMEOUT_MS)), Effect.result);
}).pipe(
Effect.scoped,
Effect.timeoutOption(Duration.millis(AUTH_PROBE_TIMEOUT_MS)),
Effect.result,
);
if (Result.isFailure(probeResult)) {
const error = probeResult.failure;
@@ -53,6 +53,7 @@ const BENIGN_ERROR_LOG_SNIPPETS = [
"state db missing rollout path for thread",
"state db record_discrepancy: find_thread_path_by_id_str_in_subdir, falling_back",
];
const CODEX_APP_SERVER_FORCE_KILL_AFTER = "2 seconds" as const;
const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"not found",
"missing thread",
@@ -721,6 +722,7 @@ export const makeCodexSessionRuntime = (
ChildProcess.make(options.binaryPath, ["app-server"], {
cwd: options.cwd,
env,
forceKillAfter: CODEX_APP_SERVER_FORCE_KILL_AFTER,
shell: process.platform === "win32",
}),
)
@@ -559,17 +559,98 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
}),
);
it.effect("deduplicates overlapping assistant text deltas after part updates", () =>
it.effect("appends raw assistant text deltas and reconciles part update snapshots", () =>
Effect.sync(() => {
const firstUpdate = mergeOpenCodeAssistantText(undefined, "Hello");
const overlapDelta = appendOpenCodeAssistantTextDelta(firstUpdate.latestText, "lo world");
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hello world!");
const secondUpdate = mergeOpenCodeAssistantText(overlapDelta.nextText, "Hellolo world");
assert.deepEqual(
[firstUpdate.deltaToEmit, overlapDelta.deltaToEmit, secondUpdate.deltaToEmit],
["Hello", " world", "!"],
["Hello", "lo world", ""],
);
assert.equal(secondUpdate.latestText, "Hello world!");
assert.equal(secondUpdate.latestText, "Hellolo world");
}),
);
it.effect("does not strip coincidental prefix overlap from OpenCode part deltas", () =>
Effect.gen(function* () {
const adapter = yield* OpenCodeAdapter;
const threadId = asThreadId("thread-opencode-raw-delta");
const part = {
id: "part-raw-delta",
sessionID: "http://127.0.0.1:9999/session",
messageID: "msg-raw-delta",
type: "text",
text: "A B",
time: { start: 1 },
};
runtimeMock.state.subscribedEvents = [
{
type: "message.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
info: {
id: "msg-raw-delta",
role: "assistant",
},
},
},
{
type: "message.part.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
part,
time: 1,
},
},
{
type: "message.part.delta",
properties: {
sessionID: "http://127.0.0.1:9999/session",
messageID: "msg-raw-delta",
partID: "part-raw-delta",
field: "text",
delta: "Bonus",
},
},
{
type: "message.part.updated",
properties: {
sessionID: "http://127.0.0.1:9999/session",
part: {
...part,
text: "A BBonus",
time: { start: 1, end: 2 },
},
time: 2,
},
},
];
const eventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.threadId === threadId),
Stream.take(5),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.startSession({
provider: ProviderDriverKind.make("opencode"),
threadId,
runtimeMode: "full-access",
});
const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));
const deltas = events.filter((event) => event.type === "content.delta");
assert.deepEqual(
deltas.map((event) => (event.type === "content.delta" ? event.payload.delta : "")),
["A B", "Bonus"],
);
assert.equal(events.at(-1)?.type, "item.completed");
const completed = events.at(-1);
if (completed?.type === "item.completed") {
assert.equal(completed.payload.detail, "A BBonus");
}
}),
);
@@ -311,16 +311,6 @@ function commonPrefixLength(left: string, right: string): number {
return index;
}
function suffixPrefixOverlap(text: string, delta: string): number {
const maxLength = Math.min(text.length, delta.length);
for (let length = maxLength; length > 0; length -= 1) {
if (text.endsWith(delta.slice(0, length))) {
return length;
}
}
return 0;
}
function resolveLatestAssistantText(previousText: string | undefined, nextText: string): string {
if (previousText && previousText.length > nextText.length && previousText.startsWith(nextText)) {
return previousText;
@@ -349,10 +339,9 @@ export function appendOpenCodeAssistantTextDelta(
readonly nextText: string;
readonly deltaToEmit: string;
} {
const deltaToEmit = delta.slice(suffixPrefixOverlap(previousText, delta));
return {
nextText: previousText + deltaToEmit,
deltaToEmit,
nextText: previousText + delta,
deltaToEmit: delta,
};
}
@@ -10,6 +10,7 @@ import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import { createModelCapabilities } from "@t3tools/shared/model";
import { compareSemverVersions } from "@t3tools/shared/semver";
import {
buildServerProvider,
nonEmptyTrimmed,
@@ -17,7 +18,6 @@ import {
providerModelsFromSettings,
type ServerProviderDraft,
} from "../providerSnapshot.ts";
import { compareCliVersions } from "../cliVersion.ts";
import {
OpenCodeRuntime,
openCodeRuntimeErrorDetail,
@@ -383,7 +383,7 @@ export const checkOpenCodeProviderStatus = Effect.fn("checkOpenCodeProviderStatu
null,
);
}
if (compareCliVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
if (compareSemverVersions(version, MINIMUM_OPENCODE_VERSION) < 0) {
return buildServerProvider({
presentation: OPENCODE_PRESENTATION,
enabled: openCodeSettings.enabled,
@@ -2,6 +2,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
@@ -27,6 +28,7 @@ import { HttpClient, HttpClientResponse } from "effect/unstable/http";
import { ChildProcessSpawner } from "effect/unstable/process";
import { deepMerge } from "@t3tools/shared/Struct";
import { createModelCapabilities } from "@t3tools/shared/model";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { checkCodexProviderStatus, type CodexAppServerProviderSnapshot } from "./CodexProvider.ts";
import { checkClaudeProviderStatus } from "./ClaudeProvider.ts";
@@ -48,6 +50,8 @@ import { ProviderInstanceRegistry } from "../Services/ProviderInstanceRegistry.t
import { ProviderRegistry } from "../Services/ProviderRegistry.ts";
import { makeManualOnlyProviderMaintenanceCapabilities } from "../providerMaintenance.ts";
const decodeServerSettings = Schema.decodeSync(ServerSettings);
const encodeServerSettings = Schema.encodeSync(ServerSettings);
const encodedDefaultServerSettings = encodeServerSettings(DEFAULT_SERVER_SETTINGS);
const defaultClaudeSettings: ClaudeSettings = Schema.decodeSync(ClaudeSettings)({});
const defaultCodexSettings: CodexSettings = Schema.decodeSync(CodexSettings)({});
@@ -206,6 +210,31 @@ function failingSpawnerLayer(description: string) {
);
}
function hangingScopedSpawnerLayer(killCalls: Ref.Ref<number>) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.gen(function* () {
const handle = ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.never,
isRunning: Effect.succeed(true),
kill: () => Ref.update(killCalls, (current) => current + 1),
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.never,
stderr: Stream.never,
all: Stream.never,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
yield* Effect.addFinalizer(() => handle.kill().pipe(Effect.ignore));
return handle;
}),
),
);
}
const codexModelCapabilities = createModelCapabilities({
optionDescriptors: [
selectDescriptor("reasoningEffort", "Reasoning", [
@@ -256,7 +285,8 @@ function makeMutableServerSettingsService(
updateSettings: (patch) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = decodeServerSettings(deepMerge(current, patch));
const next = applyServerSettingsPatch(current, patch);
encodeServerSettings(next);
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
@@ -417,6 +447,28 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
);
}),
);
it.effect("closes the app-server probe scope when provider status times out", () =>
Effect.gen(function* () {
const killCalls = yield* Ref.make(0);
const statusFiber = yield* checkCodexProviderStatus(defaultCodexSettings).pipe(
Effect.provide(hangingScopedSpawnerLayer(killCalls)),
Effect.forkChild,
);
yield* Effect.yieldNow;
yield* TestClock.adjust("11 seconds");
yield* Effect.yieldNow;
const status = yield* Fiber.join(statusFiber);
assert.strictEqual(status.status, "error");
assert.strictEqual(
status.message,
"Timed out while checking Codex app-server provider status.",
);
assert.strictEqual(yield* Ref.get(killCalls), 1);
}),
);
});
describe("ProviderRegistryLive", () => {
@@ -930,7 +982,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const missingBinary = `t3code_codex_missing_`;
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
// Disable every built-in probe that would otherwise spawn
// on the CI host. `enabled: false` short-circuits each
@@ -1029,7 +1081,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
const secondMissing = `t3code_codex_second_`;
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
codex: { enabled: true, binaryPath: firstMissing },
claudeAgent: { enabled: false },
@@ -1124,7 +1176,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
codex: { enabled: false },
claudeAgent: { enabled: false },
@@ -1180,7 +1232,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest(), T
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService(
decodeServerSettings(
deepMerge(DEFAULT_SERVER_SETTINGS, {
deepMerge(encodedDefaultServerSettings, {
providers: {
codex: {
enabled: false,
@@ -194,6 +194,7 @@ describe("ProviderSessionReaper", () => {
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () =>
Effect.succeed({ snapshotSequence: input.readModel.snapshotSequence }),
getCounts: () => Effect.die("unused"),
@@ -201,6 +202,7 @@ describe("ProviderSessionReaper", () => {
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.die("unused"),
getThreadCheckpointContext: () => Effect.die("unused"),
getFullThreadDiffContext: () => Effect.die("unused"),
getThreadShellById: (threadId) =>
Effect.succeed(
input.readModel.threads.find((thread) => thread.id === threadId)
@@ -1,96 +0,0 @@
import { it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import { describe, expect } from "vitest";
import { scopedSafeTeardown } from "./scopedSafeTeardown.ts";
describe("scopedSafeTeardown", () => {
it.effect("returns the body's value when teardown is clean", () =>
Effect.gen(function* () {
const finalizers: string[] = [];
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
finalizers.push("clean");
}),
);
return "body-ok";
}).pipe(scopedSafeTeardown("test"));
const value = yield* wrapped;
expect(value).toBe("body-ok");
expect(finalizers).toEqual(["clean"]);
}),
);
it.effect("preserves body success when a finalizer dies", () =>
// The production failure mode: `Layer.build(...)` registers a finalizer
// that kills a subprocess; if the kill fails, the defect would otherwise
// override a successful probe body.
Effect.gen(function* () {
const finalizers: string[] = [];
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
finalizers.push("ran-before-die");
}),
);
yield* Effect.addFinalizer(() =>
Effect.die(new Error("simulated subprocess kill failure")),
);
return "body-ok";
}).pipe(scopedSafeTeardown("test"));
const value = yield* wrapped;
expect(value).toBe("body-ok");
// The clean finalizer still ran; teardown defect was logged + swallowed.
expect(finalizers).toEqual(["ran-before-die"]);
}),
);
it.effect("preserves typed body failures even when teardown is clean", () =>
Effect.gen(function* () {
class BodyError {
readonly _tag = "BodyError" as const;
}
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() => Effect.void);
return yield* Effect.fail(new BodyError());
}).pipe(scopedSafeTeardown("test"));
const exit = yield* Effect.exit(wrapped);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
// Body's typed failure should surface, not a defect.
const squashed = Cause.squash(exit.cause);
expect(squashed).toBeInstanceOf(BodyError);
}
}),
);
it.effect("prefers the body's typed failure over a teardown defect", () =>
// Even when both the body fails AND teardown defects, the body's typed
// failure is what callers see. This matters because `Effect.result` /
// `.pipe(Effect.exit)` in callers expects a typed Failure, not a Die.
Effect.gen(function* () {
class BodyError {
readonly _tag = "BodyError" as const;
}
const wrapped = Effect.gen(function* () {
yield* Effect.addFinalizer(() =>
Effect.die(new Error("simulated subprocess kill failure")),
);
return yield* Effect.fail(new BodyError());
}).pipe(scopedSafeTeardown("test"));
const exit = yield* Effect.exit(wrapped);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
const squashed = Cause.squash(exit.cause);
expect(squashed).toBeInstanceOf(BodyError);
}
}),
);
});
@@ -1,63 +0,0 @@
/**
* scopedSafeTeardown — run a scope-requiring effect so that finalizer
* failures during scope close cannot override the body's Exit.
*
* Motivation
* ----------
* The obvious pattern is `body.pipe(Effect.scoped)`: provide a fresh
* Scope, run the body, close the scope with the body's Exit. If a
* finalizer (e.g. `ChildProcess.kill` from an effect-codex-app-server
* spawn) dies during that close, the combined Exit becomes the
* finalizer's defect — even when the body already succeeded.
*
* Concretely this bit us in the Codex provider probe: a successful
* `initialize` → `account/read` → `skills/list` → `model/list`
* round-trip produced a `CodexAppServerProviderSnapshot`, but the
* `Layer.build(CodexClient.layerCommand(...))` finalizer then failed to
* kill the `codex app-server` subprocess with a `PlatformError`. The
* defect bubbled past `Effect.result` in `checkCodexProviderStatus`,
* died `refreshOneSource`, and `providersRef` never saw the snapshot.
*
* Strategy
* --------
* 1. Make a fresh scope manually.
* 2. Run the body against that scope, capturing its Exit via
* `Effect.exit`.
* 3. Close the scope, catching any cause (typed failure *or* defect)
* with a log.
* 4. Replay the captured Exit so typed body failures still surface and
* successes still return their value.
*
* The helper deliberately logs teardown causes at `Warning` level —
* silently swallowing them is dangerous because they usually indicate a
* real bug in a downstream Layer's finalizer.
*
* @module provider/Layers/scopedSafeTeardown
*/
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
/**
* Run `effect` with a freshly made `Scope.Scope`, guaranteeing that
* teardown failures cannot override the body's Exit.
*
* Shape matches `Effect.scoped`: takes an effect whose env includes
* `Scope.Scope`, returns one whose env excludes it.
*
* @param label Short label for the warning log emitted when teardown
* fails. Use something like `"codex-probe"`.
*/
export const scopedSafeTeardown =
(label: string) =>
<A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, Exclude<R, Scope.Scope>> =>
Effect.gen(function* () {
const scope = yield* Scope.make();
const bodyExit = yield* effect.pipe(Effect.provideService(Scope.Scope, scope), Effect.exit);
yield* Scope.close(scope, Exit.void).pipe(
Effect.catchCause((cause) =>
Effect.logWarning(`${label} teardown errored; preserving body result`, cause),
),
);
return yield* bodyExit;
}) as Effect.Effect<A, E, Exclude<R, Scope.Scope>>;
@@ -1,17 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { compareCliVersions, normalizeCliVersion } from "./cliVersion.ts";
describe("cliVersion", () => {
it("normalizes versions with a missing patch segment", () => {
assert.strictEqual(normalizeCliVersion("2.1"), "2.1.0");
});
it("compares prerelease versions before stable versions", () => {
assert.isTrue(compareCliVersions("2.1.111-beta.1", "2.1.111") < 0);
});
it("rejects malformed numeric segments", () => {
assert.isTrue(compareCliVersions("1.2.3abc", "1.2.10") > 0);
});
});
-123
View File
@@ -1,123 +0,0 @@
interface ParsedCliSemver {
readonly major: number;
readonly minor: number;
readonly patch: number;
readonly prerelease: ReadonlyArray<string>;
}
const CLI_VERSION_NUMBER_SEGMENT = /^\d+$/;
export function normalizeCliVersion(version: string): string {
const [main, prerelease] = version.trim().split("-", 2);
const segments = (main ?? "")
.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0);
if (segments.length === 2) {
segments.push("0");
}
return prerelease ? `${segments.join(".")}-${prerelease}` : segments.join(".");
}
function parseCliSemver(version: string): ParsedCliSemver | null {
const normalized = normalizeCliVersion(version);
const [main = "", prerelease] = normalized.split("-", 2);
const segments = main.split(".");
if (segments.length !== 3) {
return null;
}
const [majorSegment, minorSegment, patchSegment] = segments;
if (majorSegment === undefined || minorSegment === undefined || patchSegment === undefined) {
return null;
}
if (
!CLI_VERSION_NUMBER_SEGMENT.test(majorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(minorSegment) ||
!CLI_VERSION_NUMBER_SEGMENT.test(patchSegment)
) {
return null;
}
const major = Number.parseInt(majorSegment, 10);
const minor = Number.parseInt(minorSegment, 10);
const patch = Number.parseInt(patchSegment, 10);
if (![major, minor, patch].every(Number.isInteger)) {
return null;
}
return {
major,
minor,
patch,
prerelease:
prerelease
?.split(".")
.map((segment) => segment.trim())
.filter((segment) => segment.length > 0) ?? [],
};
}
function comparePrereleaseIdentifier(left: string, right: string): number {
const leftNumeric = /^\d+$/.test(left);
const rightNumeric = /^\d+$/.test(right);
if (leftNumeric && rightNumeric) {
return Number.parseInt(left, 10) - Number.parseInt(right, 10);
}
if (leftNumeric) {
return -1;
}
if (rightNumeric) {
return 1;
}
return left.localeCompare(right);
}
export function compareCliVersions(left: string, right: string): number {
const parsedLeft = parseCliSemver(left);
const parsedRight = parseCliSemver(right);
if (!parsedLeft || !parsedRight) {
return left.localeCompare(right);
}
if (parsedLeft.major !== parsedRight.major) {
return parsedLeft.major - parsedRight.major;
}
if (parsedLeft.minor !== parsedRight.minor) {
return parsedLeft.minor - parsedRight.minor;
}
if (parsedLeft.patch !== parsedRight.patch) {
return parsedLeft.patch - parsedRight.patch;
}
if (parsedLeft.prerelease.length === 0 && parsedRight.prerelease.length === 0) {
return 0;
}
if (parsedLeft.prerelease.length === 0) {
return 1;
}
if (parsedRight.prerelease.length === 0) {
return -1;
}
const length = Math.max(parsedLeft.prerelease.length, parsedRight.prerelease.length);
for (let index = 0; index < length; index += 1) {
const leftIdentifier = parsedLeft.prerelease[index];
const rightIdentifier = parsedRight.prerelease[index];
if (leftIdentifier === undefined) {
return -1;
}
if (rightIdentifier === undefined) {
return 1;
}
const comparison = comparePrereleaseIdentifier(leftIdentifier, rightIdentifier);
if (comparison !== 0) {
return comparison;
}
}
return 0;
}
@@ -3,6 +3,7 @@ import {
type ServerProvider,
type ServerProviderVersionAdvisory,
} from "@t3tools/contracts";
import { compareSemverVersions } from "@t3tools/shared/semver";
import { resolveCommandPath } from "@t3tools/shared/shell";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -11,8 +12,6 @@ import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
import { compareCliVersions } from "./cliVersion.ts";
const LATEST_VERSION_CACHE_TTL_MS = 60 * 60 * 1_000;
const LATEST_VERSION_TIMEOUT_MS = 4_000;
const PROVIDER_UPDATE_ACTION_TOAST_MESSAGE = "Install the update now or review provider settings.";
@@ -365,7 +364,7 @@ function deriveVersionAdvisory(input: {
if (!input.latestVersion) {
return { status: "unknown", message: null };
}
if (compareCliVersions(input.currentVersion, input.latestVersion) < 0) {
if (compareSemverVersions(input.currentVersion, input.latestVersion) < 0) {
return {
status: "behind_latest",
message: PROVIDER_UPDATE_ACTION_TOAST_MESSAGE,
+142 -27
View File
@@ -10,7 +10,7 @@ import {
GitCommandError,
KeybindingRule,
MessageId,
OpenError,
ExternalLauncherError,
type OrchestrationThreadShell,
TerminalNotRunningError,
type OrchestrationCommand,
@@ -63,7 +63,7 @@ import {
} from "./checkpointing/Services/CheckpointDiffQuery.ts";
import { GitManager, type GitManagerShape } from "./git/GitManager.ts";
import { Keybindings, type KeybindingsShape } from "./keybindings.ts";
import { Open, type OpenShape } from "./open.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
@@ -115,6 +115,7 @@ import * as SourceControlRepositoryService from "./sourceControl/SourceControlRe
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import * as Data from "effect/Data";
@@ -319,7 +320,7 @@ const buildAppUnderTest = (options?: {
keybindings?: Partial<KeybindingsShape>;
providerRegistry?: Partial<ProviderRegistryShape>;
serverSettings?: Partial<ServerSettingsShape>;
open?: Partial<OpenShape>;
externalLauncher?: Partial<ExternalLauncher.ExternalLauncherShape>;
vcsDriver?: Partial<VcsDriver.VcsDriverShape>;
vcsDriverRegistry?: Partial<VcsDriverRegistry.VcsDriverRegistryShape>;
gitVcsDriver?: Partial<GitVcsDriver.GitVcsDriverShape>;
@@ -540,8 +541,8 @@ const buildAppUnderTest = (options?: {
}),
),
Layer.provide(
Layer.mock(Open)({
...options?.layers?.open,
Layer.mock(ExternalLauncher.ExternalLauncher)({
...options?.layers?.externalLauncher,
}),
),
Layer.provide(
@@ -564,6 +565,22 @@ const buildAppUnderTest = (options?: {
}),
}),
),
Layer.provide(
Layer.mock(ProcessResourceMonitor.ProcessResourceMonitor)({
readHistory: (input) =>
Effect.succeed({
readAt: TEST_EPOCH,
windowMs: input.windowMs,
bucketMs: input.bucketMs,
sampleIntervalMs: 5_000,
retainedSampleCount: 0,
totalCpuSecondsApprox: 0,
buckets: [],
topProcesses: [],
error: Option.none(),
}),
}),
),
Layer.provide(
Layer.mock(TraceDiagnostics.TraceDiagnostics)({
read: () =>
@@ -630,6 +647,13 @@ const buildAppUnderTest = (options?: {
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
}),
getArchivedShellSnapshot: () =>
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "1970-01-01T00:00:00.000Z",
}),
getSnapshotSequence: () => Effect.succeed({ snapshotSequence: 0 }),
getProjectShellById: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
@@ -795,7 +819,12 @@ const bootstrapBrowserSession = (
};
});
const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
const bootstrapBearerSession = (
credential = defaultDesktopBootstrapToken,
options?: {
readonly headers?: Record<string, string>;
},
) =>
Effect.gen(function* () {
const bootstrapUrl = yield* getHttpServerUrl("/api/auth/bootstrap/bearer");
const response = yield* Effect.promise(() =>
@@ -803,6 +832,7 @@ const bootstrapBearerSession = (credential = defaultDesktopBootstrapToken) =>
method: "POST",
headers: {
"content-type": "application/json",
...options?.headers,
},
body: JSON.stringify({
credential,
@@ -878,6 +908,22 @@ const splitHeaderTokens = (value: string | null) =>
.filter((token) => token.length > 0)
.toSorted();
const assertBrowserApiCorsHeaders = (headers: Headers) => {
assert.equal(headers.get("access-control-allow-origin"), "*");
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-methods")), [
"GET",
"OPTIONS",
"POST",
]);
assert.deepEqual(splitHeaderTokens(headers.get("access-control-allow-headers")), [
"authorization",
"b3",
"content-type",
"traceparent",
]);
};
const crossOriginClientOrigin = "http://remote-client.test:3773";
const getWsServerUrl = (
pathname = "",
options?: { authenticated?: boolean; credential?: string },
@@ -999,6 +1045,28 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("includes CORS headers on public environment descriptor responses", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const url = yield* getHttpServerUrl("/.well-known/t3/environment");
const response = yield* Effect.promise(() =>
fetch(url, {
headers: {
origin: crossOriginClientOrigin,
},
}),
);
const body = (yield* Effect.promise(() =>
response.json(),
)) as typeof testEnvironmentDescriptor;
assert.equal(response.status, 200);
assertBrowserApiCorsHeaders(response.headers);
assert.deepEqual(body, testEnvironmentDescriptor);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("reports unauthenticated session state without requiring auth", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -1122,6 +1190,62 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("includes CORS headers on remote auth success responses", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
const origin = crossOriginClientOrigin;
const { response: bootstrapResponse, body: bootstrapBody } = yield* bootstrapBearerSession(
defaultDesktopBootstrapToken,
{
headers: { origin },
},
);
assert.equal(bootstrapResponse.status, 200);
assertBrowserApiCorsHeaders(bootstrapResponse.headers);
assert.equal(bootstrapBody.authenticated, true);
assert.equal(typeof bootstrapBody.sessionToken, "string");
const sessionUrl = yield* getHttpServerUrl("/api/auth/session");
const sessionResponse = yield* Effect.promise(() =>
fetch(sessionUrl, {
headers: {
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
origin,
},
}),
);
const sessionBody = (yield* Effect.promise(() => sessionResponse.json())) as {
readonly authenticated: boolean;
readonly sessionMethod?: string;
};
assert.equal(sessionResponse.status, 200);
assertBrowserApiCorsHeaders(sessionResponse.headers);
assert.equal(sessionBody.authenticated, true);
assert.equal(sessionBody.sessionMethod, "bearer-session-token");
const wsTokenUrl = yield* getHttpServerUrl("/api/auth/ws-token");
const wsTokenResponse = yield* Effect.promise(() =>
fetch(wsTokenUrl, {
method: "POST",
headers: {
authorization: `Bearer ${bootstrapBody.sessionToken ?? ""}`,
origin,
},
}),
);
const wsTokenBody = (yield* Effect.promise(() => wsTokenResponse.json())) as {
readonly token: string;
};
assert.equal(wsTokenResponse.status, 200);
assertBrowserApiCorsHeaders(wsTokenResponse.headers);
assert.equal(typeof wsTokenBody.token, "string");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"responds to remote auth websocket-token preflight requests with authorization CORS headers",
() =>
@@ -1133,7 +1257,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fetch(wsTokenUrl, {
method: "OPTIONS",
headers: {
origin: "http://192.168.86.35:3773",
origin: crossOriginClientOrigin,
"access-control-request-method": "POST",
"access-control-request-headers": "authorization",
},
@@ -1141,18 +1265,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
);
assert.equal(response.status, 204);
assert.equal(response.headers.get("access-control-allow-origin"), "*");
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-methods")), [
"GET",
"OPTIONS",
"POST",
]);
assert.deepEqual(splitHeaderTokens(response.headers.get("access-control-allow-headers")), [
"authorization",
"b3",
"content-type",
"traceparent",
]);
assertBrowserApiCorsHeaders(response.headers);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -1165,7 +1278,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fetch(wsTokenUrl, {
method: "POST",
headers: {
origin: "http://192.168.86.35:3773",
origin: crossOriginClientOrigin,
},
}),
);
@@ -1174,7 +1287,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
};
assert.equal(response.status, 401);
assert.equal(response.headers.get("access-control-allow-origin"), "*");
assertBrowserApiCorsHeaders(response.headers);
assert.equal(body.error, "Authentication required.");
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
@@ -2421,8 +2534,8 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
let openedInput: { cwd: string; editor: EditorId } | null = null;
yield* buildAppUnderTest({
layers: {
open: {
openInEditor: (input) =>
externalLauncher: {
launchEditor: (input) =>
Effect.sync(() => {
openedInput = input;
}),
@@ -2446,11 +2559,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
it.effect("routes websocket rpc shell.openInEditor errors", () =>
Effect.gen(function* () {
const openError = new OpenError({ message: "Editor command not found: cursor" });
const externalLauncherError = new ExternalLauncherError({
message: "Editor command not found: cursor",
});
yield* buildAppUnderTest({
layers: {
open: {
openInEditor: () => Effect.fail(openError),
externalLauncher: {
launchEditor: () => Effect.fail(externalLauncherError),
},
},
});
@@ -2465,7 +2580,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
).pipe(Effect.result),
);
assertFailure(result, openError);
assertFailure(result, externalLauncherError);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
+4 -2
View File
@@ -13,7 +13,7 @@ import {
} from "./http.ts";
import { fixPath } from "./os-jank.ts";
import { websocketRpcRouteLayer } from "./ws.ts";
import { OpenLive } from "./open.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
import { ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.ts";
@@ -76,6 +76,7 @@ import {
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
import {
@@ -280,9 +281,10 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
// Misc.
Layer.provideMerge(ProcessDiagnostics.layer),
Layer.provideMerge(ProcessResourceMonitor.layer),
Layer.provideMerge(TraceDiagnostics.layer),
Layer.provideMerge(AnalyticsServiceLayerLive),
Layer.provideMerge(OpenLive),
Layer.provideMerge(ExternalLauncher.layer),
Layer.provideMerge(ServerLifecycleEventsLive),
Layer.provide(NetService.layer),
);
@@ -85,6 +85,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () =>
Deferred.await(releaseCounts).pipe(
@@ -97,6 +98,7 @@ it.effect("launchStartupHeartbeat does not block the caller while counts are loa
getProjectShellById: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.succeed(Option.none()),
getThreadDetailById: () => Effect.succeed(Option.none()),
}),
@@ -139,6 +141,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () =>
@@ -157,6 +160,7 @@ it.effect("resolveAutoBootstrapWelcomeTargets returns existing project and threa
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.some(bootstrapThreadId)),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
}),
@@ -191,12 +195,14 @@ it.effect("resolveAutoBootstrapWelcomeTargets creates a project and thread when
getCommandReadModel: () => Effect.die("unused"),
getSnapshot: () => Effect.die("unused"),
getShellSnapshot: () => Effect.die("unused"),
getArchivedShellSnapshot: () => Effect.die("unused"),
getSnapshotSequence: () => Effect.die("unused"),
getCounts: () => Effect.die("unused"),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getProjectShellById: () => Effect.die("unused"),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
getFullThreadDiffContext: () => Effect.succeed(Option.none()),
getThreadShellById: () => Effect.die("unused"),
getThreadDetailById: () => Effect.die("unused"),
}),
+3 -3
View File
@@ -23,7 +23,7 @@ import * as DateTime from "effect/DateTime";
import { ServerConfig } from "./config.ts";
import { Keybindings } from "./keybindings.ts";
import { Open } from "./open.ts";
import * as ExternalLauncher from "./process/externalLauncher.ts";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor.ts";
@@ -261,9 +261,9 @@ const maybeOpenBrowser = (target: string) =>
if (serverConfig.noBrowser) {
return;
}
const { openBrowser } = yield* Open;
const externalLauncher = yield* ExternalLauncher.ExternalLauncher;
yield* openBrowser(target).pipe(
yield* externalLauncher.launchBrowser(target).pipe(
Effect.catch(() =>
Effect.logInfo("browser auto-open unavailable", {
hint: `Open ${target} in your browser.`,
+3
View File
@@ -9,6 +9,7 @@ import {
import { createModelSelection } from "@t3tools/shared/model";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Duration from "effect/Duration";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
@@ -437,6 +438,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
serverPassword: "secret-password",
},
},
automaticGitFetchInterval: Duration.seconds(10),
});
assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
@@ -458,6 +460,7 @@ it.layer(NodeServices.layer)("server settings", (it) => {
serverPassword: "secret-password",
},
},
automaticGitFetchInterval: 10_000,
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
+58 -46
View File
@@ -45,15 +45,33 @@ import * as Semaphore from "effect/Semaphore";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { ServerConfig } from "./config.ts";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings";
import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
import { ServerSecretStore } from "./auth/Services/ServerSecretStore.ts";
const decodeServerSettings = Schema.decodeEffect(ServerSettings);
const encodeServerSettings = Schema.encodeEffect(ServerSettings);
const encodeServerSettingsJson = Schema.encodeUnknownEffect(fromJsonStringPretty(ServerSettings));
const decodeServerSettings = Schema.decodeUnknownEffect(ServerSettings);
const textEncoder = new TextEncoder();
const textDecoder = new TextDecoder();
const normalizeServerSettings = (
settings: ServerSettings,
): Effect.Effect<ServerSettings, ServerSettingsError> =>
encodeServerSettings(settings).pipe(
Effect.flatMap(decodeServerSettings),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
);
function providerEnvironmentSecretName(input: {
readonly instanceId: string;
readonly name: string;
@@ -117,9 +135,15 @@ export class ServerSettingsService extends Context.Service<
Layer.effect(
ServerSettingsService,
Effect.gen(function* () {
const currentSettingsRef = yield* Ref.make<ServerSettings>(
deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
);
const { automaticGitFetchInterval, ...overridesForMerge } = overrides;
const merged = deepMerge(DEFAULT_SERVER_SETTINGS, overridesForMerge);
const initialSettings = yield* normalizeServerSettings({
...merged,
...(automaticGitFetchInterval !== undefined
? { automaticGitFetchInterval: automaticGitFetchInterval as Duration.Duration }
: {}),
});
const currentSettingsRef = yield* Ref.make<ServerSettings>(initialSettings);
return {
start: Effect.void,
@@ -127,18 +151,8 @@ export class ServerSettingsService extends Context.Service<
getSettings: Ref.get(currentSettingsRef),
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
Effect.flatMap((currentSettings) =>
decodeServerSettings(applyServerSettingsPatch(currentSettings, patch)).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
),
),
Effect.map((currentSettings) => applyServerSettingsPatch(currentSettings, patch)),
Effect.flatMap(normalizeServerSettings),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
streamChanges: Stream.empty,
@@ -200,7 +214,10 @@ function fallbackTextGenerationProvider(settings: ServerSettings): ServerSetting
}
// Values under these keys are compared as a whole — never stripped field-by-field.
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set([
"automaticGitFetchInterval",
"textGenerationModelSelection",
]);
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
@@ -430,25 +447,29 @@ const makeServerSettings = Effect.gen(function* () {
};
});
const writeSettingsAtomically = (settings: ServerSettings) => {
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
const writeSettingsAtomically = Effect.fnUntraced(
function* (settings: ServerSettings) {
const sparseSettingsJson = yield* encodeServerSettingsJson(
stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {},
);
return writeFileStringAtomically({
filePath: settingsPath,
contents: `${JSON.stringify(sparseSettings, null, 2)}\n`,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, pathService),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
cause,
}),
),
);
};
return yield* writeFileStringAtomically({
filePath: settingsPath,
contents: `${sparseSettingsJson}\n`,
}).pipe(
Effect.provideService(FileSystem.FileSystem, fs),
Effect.provideService(Path.Path, pathService),
);
},
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
cause,
}),
),
);
const revalidateAndEmit = writeSemaphore.withPermits(1)(
Effect.gen(function* () {
@@ -533,16 +554,7 @@ const makeServerSettings = Effect.gen(function* () {
current,
applyServerSettingsPatch(current, patch),
);
const next = yield* decodeServerSettings(nextPersisted).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
);
const next = yield* normalizeServerSettings(nextPersisted);
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
@@ -100,7 +100,7 @@ export const layer = Layer.effect(
cwd: config.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
appendTruncationMarker: true,
})
.pipe(
Effect.map(
@@ -139,7 +139,7 @@ function probeCli(input: {
cwd: input.cwd,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
appendTruncationMarker: true,
})
.pipe(
Effect.map(
@@ -216,7 +216,7 @@ export function probeSourceControlProvider(input: {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 8_000,
truncateOutputAtMaxBytes: true,
appendTruncationMarker: true,
})
.pipe(
Effect.map(
@@ -8,7 +8,7 @@ export interface CollectedUint8StreamText {
}
interface CollectState {
readonly text: string;
chunks: Uint8Array[];
readonly bytes: number;
readonly truncated: boolean;
}
@@ -18,18 +18,21 @@ export const collectUint8StreamText = <E>(input: {
readonly maxBytes?: number | undefined;
readonly truncatedMarker?: string | null | undefined;
}): Effect.Effect<CollectedUint8StreamText, E> => {
const decoder = new TextDecoder();
const maxBytes = input.maxBytes ?? Number.POSITIVE_INFINITY;
const truncatedMarker = input.truncatedMarker ?? "";
return input.stream.pipe(
Stream.runFold(
(): CollectState => ({
text: "",
chunks: [],
bytes: 0,
truncated: false,
}),
(state, chunk): CollectState => {
/*
* keep draining after truncation so the child process can exit normally.
* its a know issue that on windows killing after the output cap can force an expensive taskkill operation and hurt performance
*/
if (state.truncated) {
return state;
}
@@ -38,30 +41,30 @@ export const collectUint8StreamText = <E>(input: {
if (remainingBytes <= 0) {
return {
...state,
text: `${state.text}${truncatedMarker}`,
truncated: true,
};
}
const nextChunk =
chunk.byteLength > remainingBytes ? chunk.slice(0, remainingBytes) : chunk;
const text = `${state.text}${decoder.decode(nextChunk, { stream: true })}`;
state.chunks.push(nextChunk);
const bytes = state.bytes + nextChunk.byteLength;
const truncated = chunk.byteLength > remainingBytes;
return {
text: truncated ? `${text}${truncatedMarker}` : text,
chunks: state.chunks,
bytes,
truncated,
};
},
),
Effect.map(
(state): CollectedUint8StreamText => ({
text: state.truncated ? state.text : `${state.text}${decoder.decode()}`,
Effect.map((state): CollectedUint8StreamText => {
const text = Buffer.concat(state.chunks, state.bytes).toString("utf8");
return {
text: state.truncated && truncatedMarker.length > 0 ? `${text}${truncatedMarker}` : text,
bytes: state.bytes,
truncated: state.truncated,
}),
),
};
}),
);
};
+149 -60
View File
@@ -6,21 +6,24 @@ import {
type TerminalOpenInput,
type TerminalRestartInput,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Scope from "effect/Scope";
import * as TestClock from "effect/testing/TestClock";
import { TestClock } from "effect/testing";
import { expect } from "vitest";
import * as ProcessRunner from "../../processRunner.ts";
import type { TerminalManagerShape } from "../Services/Manager.ts";
import {
type PtyAdapterShape,
@@ -31,6 +34,10 @@ import {
} from "../Services/PTY.ts";
import { makeTerminalManagerWithOptions } from "./Manager.ts";
class WaitForConditionError extends Data.TaggedError("WaitForConditionError")<{
readonly message: string;
}> {}
class FakePtyProcess implements PtyProcess {
readonly writes: string[] = [];
readonly resizeCalls: Array<{ cols: number; rows: number }> = [];
@@ -127,11 +134,21 @@ class FakePtyAdapter implements PtyAdapterShape {
const waitFor = <E, R>(
predicate: Effect.Effect<boolean, E, R>,
timeout: Duration.Input = 800,
): Effect.Effect<void, E | Cause.TimeoutError, R> =>
): Effect.Effect<void, WaitForConditionError | E, R> =>
predicate.pipe(
Effect.filter((done) => done),
Effect.filterOrFail(
(done) => done,
() => new WaitForConditionError({ message: "Condition not met" }),
),
Effect.retry(Schedule.spaced("15 millis")),
Effect.timeout(timeout),
Effect.timeoutOption(timeout),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(new WaitForConditionError({ message: "Timed out waiting for condition" })),
onSome: () => Effect.void,
}),
),
);
function openInput(overrides: Partial<TerminalOpenInput> = {}): TerminalOpenInput {
@@ -156,33 +173,27 @@ function restartInput(overrides: Partial<TerminalRestartInput> = {}): TerminalRe
};
}
function historyLogName(threadId: string): string {
return `terminal_${Encoding.encodeBase64Url(threadId)}.log`;
}
const historyLogPath = (logsDir: string, threadId = "thread-1") =>
Effect.service(Path.Path).pipe(
Effect.map(({ join }) => join(logsDir, `terminal_${Encoding.encodeBase64Url(threadId)}.log`)),
);
function multiTerminalHistoryLogName(threadId: string, terminalId: string): string {
const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`;
if (terminalId === DEFAULT_TERMINAL_ID) {
return `${threadPart}.log`;
}
return `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`;
}
function historyLogPath(logsDir: string, threadId = "thread-1"): string {
return joinPath(logsDir, historyLogName(threadId));
}
function multiTerminalHistoryLogPath(
const multiTerminalHistoryLogPath = (
logsDir: string,
threadId = "thread-1",
terminalId = "default",
): string {
return joinPath(logsDir, multiTerminalHistoryLogName(threadId, terminalId));
}
function joinPath(...segments: ReadonlyArray<string>): string {
return segments.join("/");
}
terminalId = DEFAULT_TERMINAL_ID,
) =>
Effect.service(Path.Path).pipe(
Effect.map(({ join }) => {
const threadPart = `terminal_${Encoding.encodeBase64Url(threadId)}`;
return join(
logsDir,
terminalId === DEFAULT_TERMINAL_ID
? `${threadPart}.log`
: `${threadPart}_${Encoding.encodeBase64Url(terminalId)}.log`,
);
}),
);
interface CreateManagerOptions {
shellResolver?: () => string;
@@ -209,13 +220,13 @@ const createManager = (
): Effect.Effect<
ManagerFixture,
PlatformError.PlatformError,
FileSystem.FileSystem | Path.Path | Scope.Scope
FileSystem.FileSystem | Path.Path | Scope.Scope | ProcessRunner.ProcessRunner
> =>
Effect.flatMap(Effect.service(FileSystem.FileSystem), (fs) =>
Effect.gen(function* () {
const pathService = yield* Path.Path;
const { join } = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-terminal-" });
const logsDir = pathService.join(baseDir, "userdata", "logs", "terminals");
const logsDir = join(baseDir, "userdata", "logs", "terminals");
const ptyAdapter = options.ptyAdapter ?? new FakePtyAdapter();
const manager = yield* makeTerminalManagerWithOptions({
@@ -246,6 +257,7 @@ const createManager = (
return {
baseDir,
logsDir,
join,
ptyAdapter,
manager,
getEvents: Ref.get(eventsRef),
@@ -253,7 +265,12 @@ const createManager = (
}),
);
it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (it) => {
it.layer(
Layer.merge(NodeServices.layer, ProcessRunner.layer.pipe(Layer.provide(NodeServices.layer))),
{ excludeTestServices: true },
)("TerminalManager", (it) => {
const itEffectSkipOnWindows = process.platform === "win32" ? it.effect.skip : it.effect;
it.effect("spawns lazily and reuses running terminal per thread", () =>
Effect.gen(function* () {
const { manager, ptyAdapter } = yield* createManager();
@@ -290,13 +307,13 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
fs.writeFileString(filePath, contents),
);
it.effect("preserves non-notFound cwd stat failures", () =>
itEffectSkipOnWindows("preserves non-notFound cwd stat failures", () =>
Effect.gen(function* () {
if (process.platform === "win32") return;
const path = yield* Path.Path;
const { manager, baseDir } = yield* createManager();
const blockedRoot = joinPath(baseDir, "blocked-root");
const blockedCwd = joinPath(blockedRoot, "cwd");
const blockedRoot = path.join(baseDir, "blocked-root");
const blockedCwd = path.join(blockedRoot, "cwd");
yield* makeDirectory(blockedCwd);
yield* chmod(blockedRoot, 0o000);
@@ -390,15 +407,27 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
it.effect("clears transcript and emits cleared event", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
const path = yield* Path.Path;
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("hello\n");
yield* waitFor(pathExists(historyLogPath(logsDir)));
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* manager.clear({ threadId: "thread-1", terminalId: DEFAULT_TERMINAL_ID });
yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === ""));
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(readFileString),
Effect.map((text) => text === ""),
),
);
const events = yield* getEvents;
expect(events.some((event) => event.type === "cleared")).toBe(true);
@@ -421,21 +450,34 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
expect(firstProcess).toBeDefined();
if (!firstProcess) return;
firstProcess.emitData("before restart\n");
yield* waitFor(pathExists(historyLogPath(logsDir)));
const path = yield* Path.Path;
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
const snapshot = yield* manager.restart(restartInput());
assert.equal(snapshot.history, "");
assert.equal(snapshot.status, "running");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
yield* waitFor(Effect.map(readFileString(historyLogPath(logsDir)), (text) => text === ""));
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(readFileString),
Effect.map((text) => text === ""),
),
);
}),
);
it.effect("propagates explicit worktree metadata through snapshots and lifecycle events", () =>
Effect.gen(function* () {
const { manager, getEvents, baseDir } = yield* createManager();
const firstWorktreePath = joinPath(baseDir, "worktrees", "feature-a");
const secondWorktreePath = joinPath(baseDir, "worktrees", "feature-b");
const path = yield* Path.Path;
const firstWorktreePath = path.join(baseDir, "worktrees", "feature-a");
const secondWorktreePath = path.join(baseDir, "worktrees", "feature-b");
yield* makeDirectory(firstWorktreePath);
yield* makeDirectory(secondWorktreePath);
const startedSnapshot = yield* manager.open(
@@ -471,7 +513,8 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
it.effect("preserves worktree metadata when reopening an exited session", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, getEvents, baseDir } = yield* createManager();
const worktreePath = joinPath(baseDir, "worktrees", "feature-a");
const path = yield* Path.Path;
const worktreePath = path.join(baseDir, "worktrees", "feature-a");
yield* makeDirectory(worktreePath);
yield* manager.open(
@@ -513,12 +556,18 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
it.effect("emits exited event and reopens with clean transcript after exit", () =>
Effect.gen(function* () {
const { manager, ptyAdapter, logsDir, getEvents } = yield* createManager();
const path = yield* Path.Path;
yield* manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("old data\n");
yield* waitFor(pathExists(historyLogPath(logsDir)));
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
process.emitExit({ exitCode: 0, signal: 0 });
yield* waitFor(
@@ -528,7 +577,12 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
assert.equal(reopened.history, "");
expect(ptyAdapter.spawnInputs).toHaveLength(2);
expect(yield* readFileString(historyLogPath(logsDir))).toBe("");
expect(
yield* historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(readFileString),
),
).toBe("");
}),
);
@@ -715,10 +769,21 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
expect(process).toBeDefined();
if (!process) return;
process.emitData("bye\n");
yield* waitFor(pathExists(historyLogPath(logsDir)));
const path = yield* Path.Path;
yield* waitFor(
historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* manager.close({ threadId: "thread-1", deleteHistory: true });
expect(yield* pathExists(historyLogPath(logsDir))).toBe(false);
expect(
yield* historyLogPath(logsDir).pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
).toBe(false);
}),
);
@@ -735,19 +800,36 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
defaultProcess.emitData("default\n");
sidecarProcess.emitData("sidecar\n");
yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default")));
yield* waitFor(pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar")));
const path = yield* Path.Path;
yield* waitFor(
multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* waitFor(
multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
yield* manager.close({ threadId: "thread-1", deleteHistory: true });
assert.equal(defaultProcess.killed, true);
assert.equal(sidecarProcess.killed, true);
expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "default"))).toBe(
false,
);
expect(yield* pathExists(multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar"))).toBe(
false,
);
expect(
yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "default").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
).toBe(false);
expect(
yield* multiTerminalHistoryLogPath(logsDir, "thread-1", "sidecar").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
).toBe(false);
}),
);
@@ -786,7 +868,13 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
first.emitData("first-history\n");
second.emitData("second-history\n");
yield* waitFor(pathExists(historyLogPath(logsDir, "thread-1")));
const path = yield* Path.Path;
yield* waitFor(
historyLogPath(logsDir, "thread-1").pipe(
Effect.provideService(Path.Path, path),
Effect.flatMap(pathExists),
),
);
first.emitExit({ exitCode: 0, signal: 0 });
yield* Effect.sleep(Duration.millis(5));
second.emitExit({ exitCode: 0, signal: 0 });
@@ -809,8 +897,9 @@ it.layer(NodeServices.layer, { excludeTestServices: true })("TerminalManager", (
it.effect("migrates legacy transcript filenames to terminal-scoped history path on open", () =>
Effect.gen(function* () {
const { manager, logsDir } = yield* createManager();
const legacyPath = joinPath(logsDir, "thread-1.log");
const nextPath = historyLogPath(logsDir);
const path = yield* Path.Path;
const legacyPath = path.join(logsDir, "thread-1.log");
const nextPath = yield* historyLogPath(logsDir);
yield* writeFileString(legacyPath, "legacy-line\n");
const snapshot = yield* manager.open(openInput());
+113 -77
View File
@@ -5,13 +5,13 @@ import {
type TerminalSessionStatus,
} from "@t3tools/contracts";
import { makeKeyedCoalescingWorker } from "@t3tools/shared/KeyedCoalescingWorker";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Equal from "effect/Equal";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as DateTime from "effect/DateTime";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
@@ -26,7 +26,7 @@ import {
terminalRestartsTotal,
terminalSessionsTotal,
} from "../../observability/Metrics.ts";
import { runProcess } from "../../processRunner.ts";
import * as ProcessRunner from "../../processRunner.ts";
import {
TerminalCwdError,
TerminalHistoryError,
@@ -51,6 +51,7 @@ const DEFAULT_MAX_RETAINED_INACTIVE_SESSIONS = 128;
const DEFAULT_OPEN_COLS = 120;
const DEFAULT_OPEN_ROWS = 30;
const TERMINAL_ENV_BLOCKLIST = new Set(["PORT", "ELECTRON_RENDERER_PORT", "ELECTRON_RUN_AS_NODE"]);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
class TerminalSubprocessCheckError extends Schema.TaggedErrorClass<TerminalSubprocessCheckError>()(
"TerminalSubprocessCheckError",
@@ -72,7 +73,9 @@ class TerminalProcessSignalError extends Schema.TaggedErrorClass<TerminalProcess
) {}
interface TerminalSubprocessChecker {
(terminalPid: number): Effect.Effect<boolean, TerminalSubprocessCheckError>;
(
terminalPid: number,
): Effect.Effect<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner>;
}
interface ShellCandidate {
@@ -211,17 +214,23 @@ function normalizeShellCommand(
return firstToken.replace(/^['"]|['"]$/g, "");
}
function basename(command: string, platform: NodeJS.Platform): string {
const normalized = platform === "win32" ? command.replaceAll("/", "\\") : command;
const separator = platform === "win32" ? "\\" : "/";
return normalized.slice(normalized.lastIndexOf(separator) + 1);
function basenameForPlatform(command: string, platform: NodeJS.Platform): string {
const normalized =
platform === "win32" ? command.replaceAll("/", "\\") : command.replaceAll("\\", "/");
const parts = normalized
.split(platform === "win32" ? /\\+/ : /\/+/)
.filter((part) => part.length > 0);
return parts.at(-1) ?? normalized;
}
function joinWindowsPath(...segments: ReadonlyArray<string>): string {
return segments
.filter((segment) => segment.length > 0)
.join("\\")
.replace(/\\+/g, "\\");
function joinWindowsPath(...parts: ReadonlyArray<string>): string {
return parts
.map((part, index) => {
if (index === 0) return part.replace(/[\\/]+$/g, "");
return part.replace(/^[\\/]+|[\\/]+$/g, "");
})
.filter((part) => part.length > 0)
.join("\\");
}
function shellCandidateFromCommand(
@@ -229,7 +238,7 @@ function shellCandidateFromCommand(
platform: NodeJS.Platform = process.platform,
): ShellCandidate | null {
if (!command || command.length === 0) return null;
const shellName = basename(command, platform).toLowerCase();
const shellName = basenameForPlatform(command, platform).toLowerCase();
if (platform === "win32" && (shellName === "pwsh.exe" || shellName === "powershell.exe")) {
return { shell: command, args: ["-NoLogo"] };
}
@@ -357,66 +366,82 @@ function isRetryableShellSpawnError(error: PtySpawnError): boolean {
function checkWindowsSubprocessActivity(
terminalPid: number,
): Effect.Effect<boolean, TerminalSubprocessCheckError> {
): Effect.Effect<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
const command = [
`$children = Get-CimInstance Win32_Process -Filter "ParentProcessId = ${terminalPid}" -ErrorAction SilentlyContinue`,
"if ($children) { exit 0 }",
"exit 1",
].join("; ");
return Effect.tryPromise({
try: () =>
runProcess("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", command], {
timeoutMs: 1_500,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to check Windows terminal subprocess activity.",
cause,
terminalPid,
command: "powershell",
}),
}).pipe(Effect.map((result) => result.code === 0));
return Effect.gen(function* () {
const processRunner = yield* ProcessRunner.ProcessRunner;
return yield* processRunner.run({
command: "powershell.exe",
args: ["-NoProfile", "-NonInteractive", "-Command", command],
timeout: "1500 millis",
maxOutputBytes: 32_768,
outputMode: "truncate",
shell: process.platform === "win32",
timeoutBehavior: "timedOutResult",
});
}).pipe(
Effect.map((result) => result.code === 0),
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
message: "Failed to check Windows terminal subprocess activity.",
cause,
terminalPid,
command: "powershell",
}),
),
);
}
const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessActivity")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
const runPgrep = Effect.tryPromise({
try: () =>
runProcess("pgrep", ["-P", String(terminalPid)], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 32_768,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with pgrep.",
cause,
terminalPid,
command: "pgrep",
}),
});
): Effect.fn.Return<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
const processRunner = yield* ProcessRunner.ProcessRunner;
const runPgrep = processRunner
.run({
command: "pgrep",
args: ["-P", String(terminalPid)],
timeout: "1 second",
maxOutputBytes: 32_768,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with pgrep.",
cause,
terminalPid,
command: "pgrep",
}),
),
);
const runPs = Effect.tryPromise({
try: () =>
runProcess("ps", ["-eo", "pid=,ppid="], {
timeoutMs: 1_000,
allowNonZeroExit: true,
maxBufferBytes: 262_144,
outputMode: "truncate",
}),
catch: (cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with ps.",
cause,
terminalPid,
command: "ps",
}),
});
const runPs = processRunner
.run({
command: "ps",
args: ["-eo", "pid=,ppid="],
timeout: "1 second",
maxOutputBytes: 262_144,
outputMode: "truncate",
timeoutBehavior: "timedOutResult",
})
.pipe(
Effect.mapError(
(cause) =>
new TerminalSubprocessCheckError({
message: "Failed to inspect terminal subprocesses with ps.",
cause,
terminalPid,
command: "ps",
}),
),
);
const pgrepResult = yield* Effect.exit(runPgrep);
if (pgrepResult._tag === "Success") {
@@ -447,7 +472,7 @@ const checkPosixSubprocessActivity = Effect.fn("terminal.checkPosixSubprocessAct
const defaultSubprocessChecker = Effect.fn("terminal.defaultSubprocessChecker")(function* (
terminalPid: number,
): Effect.fn.Return<boolean, TerminalSubprocessCheckError> {
): Effect.fn.Return<boolean, TerminalSubprocessCheckError, ProcessRunner.ProcessRunner> {
if (!Number.isInteger(terminalPid) || terminalPid <= 0) {
return false;
}
@@ -725,14 +750,19 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
const path = yield* Path.Path;
const context = yield* Effect.context<never>();
const runFork = Effect.runForkWith(context);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const logsDir = options.logsDir;
const historyLineLimit = options.historyLineLimit ?? DEFAULT_HISTORY_LINE_LIMIT;
const platform = options.platform ?? process.platform;
const baseEnv = options.env ?? process.env;
const shellResolver = options.shellResolver ?? (() => defaultShellResolver(platform, baseEnv));
const subprocessChecker = options.subprocessChecker ?? defaultSubprocessChecker;
const processRunner = yield* ProcessRunner.ProcessRunner;
const subprocessChecker =
options.subprocessChecker ??
((terminalPid) =>
defaultSubprocessChecker(terminalPid).pipe(
Effect.provideService(ProcessRunner.ProcessRunner, processRunner),
));
const subprocessPollIntervalMs =
options.subprocessPollIntervalMs ?? DEFAULT_SUBPROCESS_POLL_INTERVAL_MS;
const processKillGraceMs = options.processKillGraceMs ?? DEFAULT_PROCESS_KILL_GRACE_MS;
@@ -1419,22 +1449,23 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
runFork(drainProcessEvents(session, processPid));
});
const startedAt = yield* nowIso;
const runningAt = yield* nowIso;
yield* modifyManagerState((state) => {
session.process = ptyProcess;
session.pid = processPid;
session.status = "running";
session.updatedAt = startedAt;
session.updatedAt = runningAt;
session.unsubscribeData = unsubscribeData;
session.unsubscribeExit = unsubscribeExit;
return [undefined, state] as const;
});
const createdAt = yield* nowIso;
yield* publishEvent({
type: eventType,
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: startedAt,
createdAt,
snapshot: snapshot(session),
});
}),
@@ -1451,8 +1482,8 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
if (ptyProcess) {
yield* startKillEscalation(ptyProcess, session.threadId, session.terminalId);
}
const erroredAt = yield* nowIso;
const failedAt = yield* nowIso;
yield* modifyManagerState((state) => {
session.status = "error";
session.pid = null;
@@ -1463,18 +1494,19 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
session.updatedAt = failedAt;
session.updatedAt = erroredAt;
return [undefined, state] as const;
});
yield* evictInactiveSessionsIfNeeded();
const message = error.message;
const createdAt = yield* nowIso;
yield* publishEvent({
type: "error",
threadId: session.threadId,
terminalId: session.terminalId,
createdAt: failedAt,
createdAt,
message,
});
yield* Effect.logError("failed to start terminal", {
@@ -1547,6 +1579,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
}
const updatedAt = yield* nowIso;
const createdAt = yield* nowIso;
const event = yield* modifyManagerState((state) => {
const liveSession: Option.Option<TerminalSessionState> = Option.fromNullishOr(
state.sessions.get(toSessionKey(session.threadId, session.terminalId)),
@@ -1568,7 +1601,7 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
type: "activity" as const,
threadId: liveSession.value.threadId,
terminalId: liveSession.value.terminalId,
createdAt: updatedAt,
createdAt,
hasRunningSubprocess: hasRunningSubprocess.value,
}),
state,
@@ -1797,19 +1830,20 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
Effect.gen(function* () {
const terminalId = input.terminalId ?? DEFAULT_TERMINAL_ID;
const session = yield* requireSession(input.threadId, terminalId);
const updatedAt = yield* nowIso;
session.history = "";
session.pendingHistoryControlSequence = "";
session.pendingProcessEvents = [];
session.pendingProcessEventIndex = 0;
session.processEventDrainRunning = false;
const clearedAt = yield* nowIso;
session.updatedAt = clearedAt;
session.updatedAt = updatedAt;
yield* persistHistory(input.threadId, terminalId, session.history);
const createdAt = yield* nowIso;
yield* publishEvent({
type: "cleared",
threadId: input.threadId,
terminalId,
createdAt: clearedAt,
createdAt,
});
}),
);
@@ -1933,4 +1967,6 @@ export const makeTerminalManagerWithOptions = Effect.fn("makeTerminalManagerWith
},
);
export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager());
export const TerminalManagerLive = Layer.effect(TerminalManager, makeTerminalManager()).pipe(
Layer.provide(ProcessRunner.layer),
);
@@ -6,6 +6,7 @@ import { ChildProcessSpawner } from "effect/unstable/process";
import { type CursorSettings, type ModelSelection } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { extractJsonObject } from "@t3tools/shared/schemaJson";
import { TextGenerationError } from "@t3tools/contracts";
import { type ThreadTitleGenerationResult, type TextGenerationShape } from "./TextGeneration.ts";
@@ -16,7 +17,6 @@ import {
buildThreadTitlePrompt,
} from "./TextGenerationPrompts.ts";
import {
extractJsonObject,
sanitizeCommitSubject,
sanitizePrTitle,
sanitizeThreadTitle,
Loaded 100 of 196 files, more files were not shown because too many files have changed in this diff. Show more