Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge d6bbc5af31 Provide TestClock to Tailscale timeout test
Co-authored-by: Julius Marminge <[email protected]>
2026-05-13 16:10:17 +00:00
Cursor AgentandJulius Marminge d8ec10a5b1 Resolve mock process on timeout cleanup
Co-authored-by: Julius Marminge <[email protected]>
2026-05-13 16:09:35 +00:00
Cursor AgentandJulius Marminge f30413f93d Fix Tailscale timeout test fiber
Co-authored-by: Julius Marminge <[email protected]>
2026-05-13 16:09:01 +00:00
Cursor AgentandJulius Marminge 8bc37bee2e Use idiomatic Effect parsing and timeouts
Co-authored-by: Julius Marminge <[email protected]>
2026-05-13 16:08:14 +00: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
aa8b9f2286 Deploy hosted web app from release workflow (#2507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: cursor[bot] <206951365+cursor[bot]@users.noreply.github.com>
2026-05-08 12:47:08 -07:00
Julius MarmingeandJulius Marminge 073eb389d3 [codex] Fix Windows release signing setup (#2606)
Co-authored-by: Julius Marminge <[email protected]>
2026-05-08 12:35:52 -07:00
Julius Marmingeandcodex 825263b6f9 Scaffold oxlint plugin with initial rule (#2603)
Co-authored-by: codex <[email protected]>
2026-05-08 11:52:19 -07:00
Julius MarmingeandCursor Agent 25b02f4ba2 Enable stricter Effect LSP rules (#2596)
Co-authored-by: Cursor Agent <[email protected]>
2026-05-08 09:58:29 -07:00
504 changed files with 12280 additions and 6826 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:
+161 -3
View File
@@ -23,8 +23,8 @@ on:
type: string
permissions:
contents: write
id-token: write
contents: read
id-token: none
jobs:
check_changes:
@@ -244,6 +244,68 @@ jobs:
exit $code
}
- name: Prepare Azure Trusted Signing
if: matrix.platform == 'win'
shell: pwsh
env:
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_TRUSTED_SIGNING_ENDPOINT: ${{ secrets.AZURE_TRUSTED_SIGNING_ENDPOINT }}
AZURE_TRUSTED_SIGNING_ACCOUNT_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_ACCOUNT_NAME }}
AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME }}
AZURE_TRUSTED_SIGNING_PUBLISHER_NAME: ${{ secrets.AZURE_TRUSTED_SIGNING_PUBLISHER_NAME }}
run: |
$ErrorActionPreference = "Stop"
$requiredSecrets = @(
$env:AZURE_TENANT_ID,
$env:AZURE_CLIENT_ID,
$env:AZURE_CLIENT_SECRET,
$env:AZURE_TRUSTED_SIGNING_ENDPOINT,
$env:AZURE_TRUSTED_SIGNING_ACCOUNT_NAME,
$env:AZURE_TRUSTED_SIGNING_CERTIFICATE_PROFILE_NAME,
$env:AZURE_TRUSTED_SIGNING_PUBLISHER_NAME
)
if ($requiredSecrets | Where-Object { [string]::IsNullOrWhiteSpace($_) }) {
Write-Host "Azure Trusted Signing disabled; skipping TrustedSigning module preparation."
exit 0
}
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 `
-MinimumVersion 0.5.0 `
-Force `
-AllowClobber `
-Repository PSGallery `
-Scope CurrentUser `
-ErrorAction Stop
Import-Module TrustedSigning -MinimumVersion 0.5.0 -Force
Get-Command Invoke-TrustedSigning -ErrorAction Stop
$moduleRoots = @(
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "PowerShell", "Modules"),
[System.IO.Path]::Combine([Environment]::GetFolderPath("MyDocuments"), "WindowsPowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "PowerShell", "Modules"),
[System.IO.Path]::Combine($env:ProgramFiles, "WindowsPowerShell", "Modules")
)
$modulePathEntries = @($moduleRoots + ($env:PSModulePath -split ";")) |
Where-Object { $_ -and (Test-Path $_) } |
Select-Object -Unique
"PSModulePath=$($modulePathEntries -join ';')" >> $env:GITHUB_ENV
- name: Build desktop artifact
shell: bash
env:
@@ -358,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
@@ -511,6 +576,98 @@ jobs:
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
deploy_web:
name: Deploy hosted web app
needs: [preflight, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
T3CODE_WEB_ROUTER_URL: ${{ vars.T3CODE_WEB_ROUTER_URL }}
T3CODE_WEB_LATEST_DOMAIN: ${{ vars.T3CODE_WEB_LATEST_DOMAIN }}
T3CODE_WEB_NIGHTLY_DOMAIN: ${{ vars.T3CODE_WEB_NIGHTLY_DOMAIN }}
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ needs.preflight.outputs.ref }}
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
bun-version-file: package.json
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version-file: package.json
- name: Install release tooling dependencies
run: bun install --frozen-lockfile --filter=@t3tools/scripts --filter=@t3tools/web
- name: Align package versions to release version
run: node scripts/update-release-package-versions.ts "${{ needs.preflight.outputs.version }}"
- name: Refresh release lockfile
run: bun install --lockfile-only --ignore-scripts
- name: Deploy and alias channel
shell: bash
run: |
set -euo pipefail
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
exit 1
fi
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"
channel_name="latest"
else
channel_domain="$nightly_domain"
channel_name="nightly"
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 \
--prod \
--skip-domain \
--yes \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}" \
--build-env "APP_VERSION=${{ needs.preflight.outputs.version }}" \
--build-env "VITE_HOSTED_APP_URL=$router_url" \
--build-env "VITE_HOSTED_APP_CHANNEL=$channel_name"
)"
echo "Aliasing $deployment_url to $channel_domain."
bunx [email protected] alias set "$deployment_url" "$channel_domain" \
--token "$VERCEL_TOKEN" \
"${vercel_scope_args[@]}"
if [[ "$channel_name" == "latest" && -n "$router_domain" && "$router_domain" != "$channel_domain" ]]; then
echo "Aliasing $deployment_url to router domain $router_domain."
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' }}
@@ -595,8 +752,9 @@ jobs:
always() && !cancelled() &&
needs.preflight.result == 'success' &&
needs.release.result == 'success' &&
needs.deploy_web.result == 'success' &&
(needs.finalize.result == 'success' || needs.finalize.result == 'skipped')
needs: [preflight, release, finalize]
needs: [preflight, release, deploy_web, finalize]
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
steps:
+4 -1
View File
@@ -9,6 +9,7 @@
"**/routeTree.gen.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"jsPlugins": ["./oxlint-plugin-t3code/index.ts"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
@@ -17,6 +18,8 @@
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
"eslint/no-await-in-loop": "off",
"eslint/no-underscore-dangle": "off",
"t3code/no-inline-schema-compile": "warn"
}
}
+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.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.22",
"version": "0.0.23",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
+2 -1
View File
@@ -16,6 +16,7 @@ const COMMIT_HASH_DISPLAY_LENGTH = 12;
const AppPackageMetadata = Schema.Struct({
t3codeCommitHash: Schema.optional(Schema.String),
});
const decodeAppPackageMetadata = Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata));
export interface DesktopAppIdentityShape {
readonly resolveUserDataPath: Effect.Effect<string>;
@@ -47,7 +48,7 @@ const make = Effect.gen(function* () {
return yield* Option.match(raw, {
onNone: () => Effect.succeed(Option.none<string>()),
onSome: (value) =>
Schema.decodeEffect(Schema.fromJsonString(AppPackageMetadata))(value).pipe(
decodeAppPackageMetadata(value).pipe(
Effect.map((parsed) =>
Option.fromNullishOr(parsed.t3codeCommitHash).pipe(Option.flatMap(normalizeCommitHash)),
),
@@ -15,7 +15,7 @@ import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { TestClock } from "effect/testing";
import * as TestClock from "effect/testing/TestClock";
import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -25,6 +25,10 @@ import * as DesktopObservability from "../app/DesktopObservability.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
entryPath: "/server/bin.mjs",
@@ -94,7 +98,7 @@ const healthyHttpClientLayer = httpClientLayer((request) =>
);
function decodeBootstrap(raw: string) {
return Schema.decodeEffect(Schema.fromJsonString(DesktopBackendBootstrap))(raw);
return decodeDesktopBackendBootstrap(raw);
}
function makeManagerLayer(input: {
+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,
};
};
@@ -20,10 +20,14 @@ const ClientSettingsDocumentSchema = Schema.Struct({
const ClientSettingsJson = fromLenientJson(ClientSettingsSchema);
const LegacyClientSettingsDocumentJson = fromLenientJson(ClientSettingsDocumentSchema);
const decodeLegacyClientSettingsDocumentJson = Schema.decodeEffect(
LegacyClientSettingsDocumentJson,
);
const decodeClientSettingsJsonValue = Schema.decodeEffect(ClientSettingsJson);
const decodeClientSettingsJson = (raw: string): Effect.Effect<ClientSettings, Schema.SchemaError> =>
Schema.decodeEffect(LegacyClientSettingsDocumentJson)(raw).pipe(
decodeLegacyClientSettingsDocumentJson(raw).pipe(
Effect.map((document) => document.settings),
Effect.catch(() => Schema.decodeEffect(ClientSettingsJson)(raw)),
Effect.catch(() => decodeClientSettingsJsonValue(raw)),
);
const encodeClientSettingsJson = Schema.encodeEffect(ClientSettingsJson);
@@ -3,7 +3,7 @@ import type {
DesktopSshEnvironmentBootstrap,
DesktopSshEnvironmentTarget,
} from "@t3tools/contracts";
import { type NetError, NetService } from "@t3tools/shared/Net";
import * as NetService from "@t3tools/shared/Net";
import {
SshPasswordPrompt,
type SshPasswordPromptShape,
@@ -35,7 +35,7 @@ export type DesktopSshEnvironmentRuntimeServices =
| FileSystem.FileSystem
| Path.Path
| HttpClient.HttpClient
| NetService;
| NetService.NetService;
export type DesktopSshEnvironmentOperationError =
| SshCommandError
@@ -44,7 +44,7 @@ export type DesktopSshEnvironmentOperationError =
| SshPairingError
| SshReadinessError
| SshPasswordPromptError
| NetError;
| NetService.NetError;
export type DesktopSshEnvironmentDiscoverError = SshHostDiscoveryError;
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { TestClock } from "effect/testing";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { TestClock } from "effect/testing";
import * as TestClock from "effect/testing/TestClock";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
import * as DesktopConfig from "../app/DesktopConfig.ts";
+7 -4
View File
@@ -54,6 +54,9 @@ const UpdateInfo = Schema.Struct({
const DownloadProgressInfo = Schema.Struct({
percent: Schema.Number,
});
const decodeAppUpdateYmlConfig = Schema.decodeUnknownEffect(AppUpdateYmlConfig);
const decodeUpdateInfo = Schema.decodeUnknownEffect(UpdateInfo);
const decodeDownloadProgressInfo = Schema.decodeUnknownEffect(DownloadProgressInfo);
const currentIsoTimestamp = DateTime.now.pipe(Effect.map(DateTime.formatIso));
@@ -115,7 +118,7 @@ function parseAppUpdateYml(raw: string): Effect.Effect<Option.Option<AppUpdateYm
}
}
return Schema.decodeUnknownEffect(AppUpdateYmlConfig)(entries).pipe(
return decodeAppUpdateYmlConfig(entries).pipe(
Effect.map((config) => (config.provider ? Option.some(config) : Option.none())),
Effect.catch(() => Effect.succeed(Option.none<AppUpdateYmlConfig>())),
);
@@ -408,7 +411,7 @@ const make = Effect.gen(function* () {
const handleUpdateAvailable = Effect.fn("desktop.updates.handleUpdateAvailable")(function* (
raw: unknown,
) {
yield* Schema.decodeUnknownEffect(UpdateInfo)(raw).pipe(
yield* decodeUpdateInfo(raw).pipe(
Effect.flatMap(
Effect.fn("desktop.updates.applyUpdateAvailable")(function* (info) {
const state = yield* Ref.get(updateStateRef);
@@ -479,7 +482,7 @@ const make = Effect.gen(function* () {
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
raw: unknown,
) {
yield* Schema.decodeUnknownEffect(DownloadProgressInfo)(raw).pipe(
yield* decodeDownloadProgressInfo(raw).pipe(
Effect.flatMap(
Effect.fn("desktop.updates.applyDownloadProgress")(function* (progress) {
const state = yield* Ref.get(updateStateRef);
@@ -506,7 +509,7 @@ const make = Effect.gen(function* () {
const handleUpdateDownloaded = Effect.fn("desktop.updates.handleUpdateDownloaded")(function* (
raw: unknown,
) {
yield* Schema.decodeUnknownEffect(UpdateInfo)(raw).pipe(
yield* decodeUpdateInfo(raw).pipe(
Effect.flatMap(
Effect.fn("desktop.updates.applyUpdateDownloaded")(function* (info) {
const state = yield* Ref.get(updateStateRef);
+1 -13
View File
@@ -3,19 +3,7 @@
"compilerOptions": {
"composite": true,
"types": ["node", "electron"],
"lib": ["ESNext", "DOM", "esnext.disposable"],
"plugins": [
{
"name": "@effect/language-service",
"namespaceImportPackages": ["@effect/platform-node", "effect"],
"diagnosticSeverity": {
"importFromBarrel": "error",
"anyUnknownInErrorContext": "error",
"instanceOfSchema": "warning",
"deterministicKeys": "warning"
}
}
]
"lib": ["ESNext", "DOM", "esnext.disposable"]
},
"include": ["src", "tsdown.config.ts"]
}
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -8,20 +9,18 @@ import {
type OrchestrationEvent,
type OrchestrationThread,
} from "@t3tools/contracts";
import {
Effect,
Exit,
FileSystem,
Layer,
ManagedRuntime,
Option,
Path,
Ref,
Schedule,
Schema,
Scope,
Stream,
} from "effect";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
@@ -74,12 +73,13 @@ import {
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
import { VcsStatusBroadcaster } from "../src/vcs/VcsStatusBroadcaster.ts";
import { GitWorkflowService } from "../src/git/GitWorkflowService.ts";
import * as VcsProcess from "../src/vcs/VcsProcess.ts";
const decodeCodexSettings = Schema.decodeEffect(CodexSettings);
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
cwd,
@@ -267,7 +267,7 @@ export const makeOrchestrationIntegrationHarness = (
const realCodexRegistry = Layer.effect(
ProviderAdapterRegistry,
Effect.gen(function* () {
const codexSettings = Schema.decodeSync(CodexSettings)({});
const codexSettings = yield* decodeCodexSettings({});
const codexAdapter = yield* makeCodexAdapter(codexSettings);
return makeAdapterRegistryMock({
[ProviderDriverKind.make("codex")]: codexAdapter,
@@ -310,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" }),
@@ -1,5 +1,3 @@
import { randomUUID } from "node:crypto";
import {
ApprovalRequestId,
EventId,
@@ -12,7 +10,10 @@ import {
TurnId,
ProviderDriverKind,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
import * as Effect from "effect/Effect";
import * as Queue from "effect/Queue";
import * as Random from "effect/Random";
import * as Stream from "effect/Stream";
import {
ProviderAdapterSessionNotFoundError,
@@ -202,7 +203,7 @@ interface MakeTestProviderAdapterHarnessOptions {
}
function nowIso(): string {
return new Date().toISOString();
return "2026-01-01T00:00:00.000Z";
}
function sessionNotFound(
@@ -308,10 +309,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
for (const fixtureEvent of response.events) {
const rawEvent: Record<string, unknown> = {
...(fixtureEvent as Record<string, unknown>),
eventId: randomUUID(),
eventId: yield* Random.nextUUIDv4,
provider,
sessionId: RuntimeSessionId.make(String(input.threadId)),
createdAt: nowIso(),
};
rawEvent.threadId = state.snapshot.threadId;
if (Object.hasOwn(rawEvent, "turnId")) {
@@ -366,7 +366,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
if (deferredTurnCompletedEvents.length === 0) {
yield* emit({
type: "turn.completed",
eventId: EventId.make(randomUUID()),
eventId: EventId.make(yield* Random.nextUUIDv4),
provider,
createdAt: nowIso(),
threadId: state.snapshot.threadId,
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
import fs from "node:fs";
import path from "node:path";
@@ -17,7 +18,10 @@ import {
ProviderInstanceId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import type { TestTurnResponse } from "./TestProviderAdapter.integration.ts";
import {
@@ -47,7 +51,7 @@ const CODEX_PROVIDER = ProviderDriverKind.make("codex");
const CLAUDE_AGENT_PROVIDER = ProviderDriverKind.make("claudeAgent");
function nowIso() {
return new Date().toISOString();
return "2026-05-01T00:00:00.000Z";
}
class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWaitTimeoutError>()(
@@ -64,14 +68,14 @@ function waitForSync<A>(
timeoutMs = 10_000,
): Effect.Effect<A, never> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
const deadline = (yield* Clock.currentTimeMillis) + timeoutMs;
while (true) {
const value = read();
if (predicate(value)) {
return value;
}
if (Date.now() >= deadline) {
if ((yield* Clock.currentTimeMillis) >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* Effect.sleep(10);
@@ -156,6 +160,7 @@ const startTurn = (input: {
readonly messageId: string;
readonly text: string;
readonly modelSelection?: ModelSelection;
readonly createdAt?: string;
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
@@ -174,7 +179,7 @@ const startTurn = (input: {
: {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
createdAt: input.createdAt ?? nowIso(),
});
it.live("runs a single turn end-to-end and persists checkpoint state in sqlite + git", () =>
@@ -755,6 +760,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
commandId: "cmd-turn-start-revert-1",
messageId: "msg-user-revert-1",
text: "First edit",
createdAt: "2026-02-24T10:04:59.900Z",
});
yield* harness.waitForThread(
@@ -813,6 +819,7 @@ it.live("reverts to an earlier checkpoint and trims checkpoint projections + git
commandId: "cmd-turn-start-revert-2",
messageId: "msg-user-revert-2",
text: "Second edit",
createdAt: "2026-02-24T10:05:00.900Z",
});
yield* harness.waitForThread(
@@ -3,7 +3,12 @@ import { ProviderDriverKind, ProviderInstanceId, ThreadId } from "@t3tools/contr
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { makeAdapterRegistryMock } from "../src/provider/testUtils/providerAdapterRegistryMock.ts";
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.22",
"version": "0.0.23",
"license": "MIT",
"repository": {
"type": "git",
@@ -31,8 +31,7 @@
"@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:",
+1
View File
@@ -1,4 +1,5 @@
#!/usr/bin/env bun
// @effect-diagnostics nodeBuiltinImport:off
import { appendFileSync } from "node:fs";
import * as Effect from "effect/Effect";
+13 -3
View File
@@ -1,8 +1,13 @@
#!/usr/bin/env node
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Data, Effect, FileSystem, Logger, Option, Path } from "effect";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { Command, Flag } from "effect/unstable/cli";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
@@ -11,6 +16,7 @@ import {
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -30,6 +36,9 @@ interface PackageJson {
overrides: Record<string, string>;
}
const PackageJsonPrettyJson = fromJsonStringPretty(Schema.Unknown);
const encodePackageJson = Schema.encodeEffect(PackageJsonPrettyJson);
class CliError extends Data.TaggedError("CliError")<{
readonly message: string;
readonly cause?: unknown;
@@ -227,8 +236,9 @@ const publishCmd = Command.make(
};
const original = yield* fs.readFileString(packageJsonPath);
const packageJsonString = yield* encodePackageJson(pkg);
yield* fs.writeFileString(backupPath, original);
yield* fs.writeFileString(packageJsonPath, `${JSON.stringify(pkg, null, 2)}\n`);
yield* fs.writeFileString(packageJsonPath, `${packageJsonString}\n`);
yield* Effect.log("[cli] Prepared package.json for publish");
const iconBackups = yield* applyPublishIconOverrides(repoRoot, serverDir);
@@ -1,6 +1,8 @@
// @effect-diagnostics nodeBuiltinImport:off
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
import process from "node:process";
import readline from "node:readline";
import * as NodeTimers from "node:timers";
type JsonPrimitive = null | boolean | number | string;
type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
@@ -114,7 +116,8 @@ function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
function sleep(ms: number) {
return new Promise<void>((resolve) => {
setTimeout(resolve, ms);
// @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script, not an Effect runtime test.
NodeTimers.setTimeout(resolve, ms);
});
}
@@ -177,7 +180,8 @@ class JsonRpcChild {
const id = this.nextId++;
const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
const timeout = setTimeout(() => {
// @effect-diagnostics-next-line globalTimers:off - Standalone Node probe script request timeout.
const timeout = NodeTimers.setTimeout(() => {
this.pending.delete(id);
reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
}, timeoutMs);
@@ -185,11 +189,11 @@ class JsonRpcChild {
this.pending.set(id, {
method,
resolve: (value) => {
clearTimeout(timeout);
NodeTimers.clearTimeout(timeout);
resolve(value);
},
reject: (error) => {
clearTimeout(timeout);
NodeTimers.clearTimeout(timeout);
reject(error);
},
});
+3 -1
View File
@@ -1,4 +1,6 @@
import { Effect, FileSystem, Path } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Random from "effect/Random";
export const writeFileStringAtomically = (input: {
+6 -5
View File
@@ -1,9 +1,10 @@
import path from "node:path";
// @effect-diagnostics nodeBuiltinImport:off
import NodePath from "node:path";
export const ATTACHMENTS_ROUTE_PREFIX = "/attachments";
export function normalizeAttachmentRelativePath(rawRelativePath: string): string | null {
const normalized = path.normalize(rawRelativePath).replace(/^[/\\]+/, "");
const normalized = NodePath.normalize(rawRelativePath).replace(/^[/\\]+/, "");
if (normalized.length === 0 || normalized.startsWith("..") || normalized.includes("\0")) {
return null;
}
@@ -19,9 +20,9 @@ export function resolveAttachmentRelativePath(input: {
return null;
}
const attachmentsRoot = path.resolve(input.attachmentsDir);
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
const attachmentsRoot = NodePath.resolve(input.attachmentsDir);
const filePath = NodePath.resolve(NodePath.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${NodePath.sep}`)) {
return null;
}
return filePath;
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
import { randomUUID } from "node:crypto";
import { existsSync } from "node:fs";
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
@@ -1,5 +1,7 @@
import type { AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
import { DateTime, Effect, Layer } from "effect";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { BootstrapCredentialServiceLive } from "./BootstrapCredentialService.ts";
import { ServerSecretStoreLive } from "./ServerSecretStore.ts";
@@ -1,7 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
@@ -1,6 +1,12 @@
import type { AuthPairingLink } from "@t3tools/contracts";
import { DateTime, Duration, Effect, Layer, PubSub, Ref, Stream } from "effect";
import { Option } from "effect";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import { ServerConfig } from "../../config.ts";
import { AuthPairingLinkRepositoryLive } from "../../persistence/Layers/AuthPairingLinks.ts";
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
+4 -1
View File
@@ -6,7 +6,10 @@ import {
type AuthSessionState,
type AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import { DateTime, Effect, Layer, Option } from "effect";
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 HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import { AuthControlPlane } from "../Services/AuthControlPlane.ts";
@@ -1,6 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
@@ -1,5 +1,6 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { ServerConfig } from "../../config.ts";
import { ServerAuthPolicy, type ServerAuthPolicyShape } from "../Services/ServerAuthPolicy.ts";
@@ -1,6 +1,11 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Cause, Deferred, Effect, FileSystem, Layer, Ref } from "effect";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Ref from "effect/Ref";
import * as PlatformError from "effect/PlatformError";
import { ServerConfig } from "../../config.ts";
@@ -1,6 +1,10 @@
import * as Crypto from "node:crypto";
import { Effect, FileSystem, Layer, Path, Predicate } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Predicate from "effect/Predicate";
import * as PlatformError from "effect/PlatformError";
import { ServerConfig } from "../../config.ts";
@@ -1,7 +1,9 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Duration, Effect, Layer } from "effect";
import { TestClock } from "effect/testing";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as TestClock from "effect/testing/TestClock";
import type { ServerConfigShape } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
@@ -1,6 +1,14 @@
import { AuthSessionId, type AuthClientMetadata, type AuthClientSession } from "@t3tools/contracts";
import { Clock, DateTime, Duration, Effect, Layer, PubSub, Ref, Schema, Stream } from "effect";
import { Option } from "effect";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PubSub from "effect/PubSub";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as Option from "effect/Option";
import { ServerConfig } from "../../config.ts";
import { AuthSessionRepositoryLive } from "../../persistence/Layers/AuthSessions.ts";
@@ -192,6 +200,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
),
);
const encodeClaims = Schema.encodeEffect(Schema.fromJsonString(SessionClaims));
const issue: SessionCredentialServiceShape["issue"] = (input) =>
Effect.gen(function* () {
const sessionId = AuthSessionId.make(crypto.randomUUID());
@@ -209,7 +218,13 @@ export const makeSessionCredentialService = Effect.gen(function* () {
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
const encodedPayload = yield* encodeClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
const client = input?.client ?? createDefaultClientMetadata();
yield* authSessions.create({
@@ -297,12 +312,19 @@ export const makeSessionCredentialService = Effect.gen(function* () {
});
}
const expiresAt = DateTime.make(claims.exp);
if (Option.isNone(expiresAt)) {
return yield* new SessionCredentialError({
message: "Invalid `exp` claim",
});
}
return {
sessionId: claims.sid,
token,
method: claims.method,
client: toClientMetadata(row.value.client),
expiresAt: DateTime.makeUnsafe(claims.exp),
expiresAt: expiresAt.value,
subject: claims.sub,
role: claims.role,
} satisfies VerifiedSession;
@@ -317,6 +339,7 @@ export const makeSessionCredentialService = Effect.gen(function* () {
),
);
const encodeWsClaims = Schema.encodeEffect(Schema.fromJsonString(WebSocketClaims));
const issueWebSocketToken: SessionCredentialServiceShape["issueWebSocketToken"] = (
sessionId,
input,
@@ -333,7 +356,12 @@ export const makeSessionCredentialService = Effect.gen(function* () {
iat: issuedAt.epochMilliseconds,
exp: expiresAt.epochMilliseconds,
};
const encodedPayload = base64UrlEncode(JSON.stringify(claims));
const encodedPayload = yield* encodeWsClaims(claims).pipe(
Effect.map(base64UrlEncode),
Effect.mapError(
(cause) => new SessionCredentialError({ message: "Failed to encode claims", cause }),
),
);
const signature = signPayload(encodedPayload, signingSecret);
return {
token: `${encodedPayload}.${signature}`,
@@ -4,7 +4,11 @@ import type {
AuthPairingLink,
AuthSessionId,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Effect, Context } from "effect";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Context from "effect/Context";
import type { SessionRole } from "./SessionCredentialService.ts";
export const DEFAULT_SESSION_SUBJECT = "cli-issued-session";
@@ -1,6 +1,10 @@
import type { AuthPairingLink, ServerAuthBootstrapMethod } from "@t3tools/contracts";
import { Data, DateTime, Duration, Context } from "effect";
import type { Effect, Stream } from "effect";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Stream from "effect/Stream";
export type BootstrapCredentialRole = "owner" | "client";
+4 -2
View File
@@ -12,8 +12,10 @@ import type {
ServerAuthSessionMethod,
AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import { Data, DateTime, Context } from "effect";
import type { Effect } from "effect";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import type { SessionRole } from "./SessionCredentialService.ts";
@@ -1,6 +1,6 @@
import type { ServerAuthDescriptor } from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
export interface ServerAuthPolicyShape {
readonly getDescriptor: () => Effect.Effect<ServerAuthDescriptor>;
@@ -1,5 +1,6 @@
import { Data, Context } from "effect";
import type { Effect } from "effect";
import * as Data from "effect/Data";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
export class SecretStoreError extends Data.TaggedError("SecretStoreError")<{
readonly message: string;
@@ -4,8 +4,12 @@ import type {
AuthSessionId,
ServerAuthSessionMethod,
} from "@t3tools/contracts";
import { Data, DateTime, Duration, Context } from "effect";
import type { Effect, Stream } from "effect";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type * as Stream from "effect/Stream";
export type SessionRole = "owner" | "client";
+15 -4
View File
@@ -6,12 +6,15 @@ import {
AuthRevokePairingLinkInput,
type AuthWebSocketTokenResult,
} from "@t3tools/contracts";
import { DateTime, Effect, Schema } from "effect";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
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* () {
@@ -25,7 +28,7 @@ export const respondToAuthError = (error: AuthError) =>
{
error: error.message,
},
{ status: error.status ?? 500 },
{ status: error.status ?? 500, headers: browserApiCorsHeaders },
);
});
@@ -36,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,
});
}),
);
@@ -79,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,
@@ -112,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))),
);
@@ -126,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))),
);
+7 -2
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics-next-line nodeBuiltinImport:off - NodeHttpServer.layer takes `NodeHttp.createServer` as arg
import * as NodeHttp from "node:http";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
@@ -5,7 +6,7 @@ import { join } from "node:path";
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import * as NetService from "@t3tools/shared/Net";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -138,7 +139,7 @@ const withLiveProjectCliServer = <A, E, R>(baseDir: string, run: () => Effect.Ef
}
yield* persistServerRuntimeState({
path: config.serverRuntimeStatePath,
state: makePersistedServerRuntimeState({
state: yield* makePersistedServerRuntimeState({
config,
port: address.port,
}),
@@ -179,6 +180,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
const createdOutput = yield* captureStdout(
runCli(["auth", "pairing", "create", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const created = JSON.parse(createdOutput.output) as {
readonly id: string;
readonly credential: string;
@@ -186,6 +188,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
const listedOutput = yield* captureStdout(
runCli(["auth", "pairing", "list", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
readonly id: string;
readonly credential?: string;
@@ -207,6 +210,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
const issuedOutput = yield* captureStdout(
runCli(["auth", "session", "issue", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const issued = JSON.parse(issuedOutput.output) as {
readonly sessionId: string;
readonly token: string;
@@ -215,6 +219,7 @@ it.layer(NodeServices.layer)("bin cli parsing", (it) => {
const listedOutput = yield* captureStdout(
runCli(["auth", "session", "list", "--base-dir", baseDir, "--json"]),
);
// @effect-diagnostics-next-line preferSchemaOverJson:off
const listed = JSON.parse(listedOutput.output) as ReadonlyArray<{
readonly sessionId: string;
readonly token?: string;
+1 -1
View File
@@ -4,7 +4,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { Command } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import * as NetService from "@t3tools/shared/Net";
import packageJson from "../package.json" with { type: "json" };
import { authCommand } from "./cli/auth.ts";
import { sharedServerCommandFlags } from "./cli/config.ts";
+7 -8
View File
@@ -1,13 +1,15 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NFS from "node:fs";
import * as path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { FileSystem, Schema } from "effect";
import * as FileSystem from "effect/FileSystem";
import * as Schema from "effect/Schema";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import { TestClock } from "effect/testing";
import * as TestClock from "effect/testing/TestClock";
import { vi } from "vitest";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap.ts";
@@ -36,6 +38,7 @@ vi.mock("node:fs", async (importOriginal) => {
});
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
const encodeTestEnvelopeSchema = Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema));
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
it.effect("uses platform-specific fd paths", () =>
@@ -53,9 +56,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
`${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
);
const fd = yield* Effect.acquireRelease(
@@ -77,9 +78,7 @@ it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
`${yield* encodeTestEnvelopeSchema({ mode: "desktop" })}\n`,
);
// Open without acquireRelease: the direct-stream fallback uses autoClose: true,
+7 -1
View File
@@ -1,9 +1,15 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NFS from "node:fs";
import * as Net from "node:net";
import * as readline from "node:readline";
import type { Readable } from "node:stream";
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Predicate from "effect/Predicate";
import * as Result from "effect/Result";
import * as Schema from "effect/Schema";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
class BootstrapError extends Data.TaggedError("BootstrapError")<{
+1 -1
View File
@@ -1,4 +1,4 @@
import { Schema } from "effect";
import * as Schema from "effect/Schema";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import type { VcsError } from "@t3tools/contracts";
@@ -1,5 +1,7 @@
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import { describe, expect, it } from "vitest";
import {
@@ -39,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;
@@ -63,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(() => {
@@ -92,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()),
}),
@@ -117,7 +217,6 @@ describe("CheckpointDiffQueryLive", () => {
);
const expectedFromRef = checkpointRefForThreadTurn(threadId, 0);
expect(hasCheckpointRefCalls).toEqual([expectedFromRef, toCheckpointRef]);
expect(diffCheckpointsCalls).toEqual([
{
cwd: "/tmp/workspace",
@@ -172,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()),
}),
@@ -198,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");
@@ -220,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,10 +1,14 @@
import {
type CheckpointRef,
OrchestrationGetTurnDiffResult,
type OrchestrationGetFullThreadDiffInput,
type ThreadId,
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Schema } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
@@ -17,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;
@@ -25,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 = {
@@ -42,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,
@@ -97,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,
@@ -152,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,8 +1,13 @@
// @effect-diagnostics nodeBuiltinImport:off
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
@@ -1,301 +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 { Effect, Layer, FileSystem, Path } from "effect";
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 {
@@ -12,8 +12,8 @@ import type {
OrchestrationGetTurnDiffInput,
OrchestrationGetTurnDiffResult,
} from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type { CheckpointServiceError } from "../Errors.ts";
@@ -10,8 +10,8 @@
*
* @module CheckpointStore
*/
import { Context } from "effect";
import type { Effect } from "effect";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import type { CheckpointStoreError } from "../Errors.ts";
import { CheckpointRef } from "@t3tools/contracts";
+1 -1
View File
@@ -1,4 +1,4 @@
import { Encoding } from "effect";
import * as Encoding from "effect/Encoding";
import { CheckpointRef, ProjectId, type ThreadId } from "@t3tools/contracts";
export const CHECKPOINT_REFS_PREFIX = "refs/t3/checkpoints";
+5 -1
View File
@@ -1,5 +1,9 @@
import { AuthSessionId } from "@t3tools/contracts";
import { Console, Effect, Layer, Option, References } from "effect";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as References from "effect/References";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import { AuthControlPlaneRuntimeLive } from "../auth/Layers/AuthControlPlane.ts";
+16 -9
View File
@@ -1,13 +1,19 @@
import os from "node:os";
import NodeOS from "node:os";
import { assert, expect, it } from "@effect/vitest";
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path, Schema } from "effect";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import {
DesktopBackendBootstrap,
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import * as NetService from "@t3tools/shared/Net";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "../config.ts";
import { resolveServerConfig } from "./config.ts";
@@ -53,7 +59,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
it.effect("falls back to effect/config values when flags are omitted", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-env-base");
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
const resolved = yield* resolveServerConfig(
{
@@ -119,7 +125,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
it.effect("uses CLI flags when provided", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-flags-base");
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-flags-base");
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const resolved = yield* resolveServerConfig(
{
@@ -147,7 +153,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
T3CODE_HOME: join(NodeOS.tmpdir(), "ignored-base"),
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "false",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
@@ -185,7 +191,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
it.effect("preserves explicit false CLI boolean flags over env and bootstrap values", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-false-flags");
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-false-flags");
const fd = yield* openBootstrapFd(
makeDesktopBootstrap({
noBrowser: true,
@@ -378,7 +384,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
it.effect("applies flag then env precedence over bootstrap envelope values", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-env-wins");
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-env-wins");
const fd = yield* openBootstrapFd(
makeDesktopBootstrap({
port: 4888,
@@ -459,6 +465,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
yield* fs.writeFileString(
derivedPaths.settingsPath,
// @effect-diagnostics-next-line preferSchemaOverJson:off
`${JSON.stringify({
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
@@ -521,7 +528,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
it.effect("forces noBrowser and disables auto-bootstrap for headless startup presentation", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(os.tmpdir(), "t3-cli-config-headless-base");
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-headless-base");
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
const resolved = yield* resolveServerConfig(
+12 -14
View File
@@ -1,18 +1,16 @@
import { NetService } from "@t3tools/shared/Net";
import * as NetService from "@t3tools/shared/Net";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
import {
Config,
Duration,
Effect,
FileSystem,
LogLevel,
Option,
Path,
Schema,
SchemaIssue,
SchemaTransformation,
} from "effect";
import * as Config from "effect/Config";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as LogLevel from "effect/LogLevel";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as SchemaTransformation from "effect/SchemaTransformation";
import { Argument, Flag } from "effect/unstable/cli";
import { readBootstrapEnvelope } from "../bootstrap.ts";
@@ -215,7 +213,7 @@ export const resolveServerConfig = (
},
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const { findAvailablePort } = yield* NetService.NetService;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
const env = yield* EnvServerConfig;
+27 -21
View File
@@ -4,18 +4,18 @@ import {
ProjectId,
type ClientOrchestrationCommand,
} from "@t3tools/contracts";
import {
Console,
Duration,
Effect,
Exit,
FileSystem,
Layer,
Option,
Path,
References,
Schema,
} from "effect";
import * as Console from "effect/Console";
import * as Data from "effect/Data";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
FetchHttpClient,
@@ -54,6 +54,10 @@ type ProjectCliDispatchCommand = Extract<
{ type: "project.create" | "project.meta.update" | "project.delete" }
>;
class ProjectCommandError extends Data.TaggedError("ProjectCommandError")<{
readonly message: string;
}> {}
const ProjectCliRuntimeLive = Layer.mergeAll(
WorkspacePathsLive,
OrchestrationLayerLive.pipe(
@@ -124,7 +128,7 @@ const resolveProjectTitle = Effect.fn("resolveProjectTitle")(function* (
if (trimmed.length > 0) {
return trimmed;
}
return yield* Effect.fail(new Error("Project title cannot be empty."));
return yield* new ProjectCommandError({ message: "Project title cannot be empty." });
}
const path = yield* Path.Path;
@@ -138,7 +142,7 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
}) {
const trimmedIdentifier = input.identifier.trim();
if (trimmedIdentifier.length === 0) {
return yield* Effect.fail(new Error("Project identifier cannot be empty."));
return yield* new ProjectCommandError({ message: "Project identifier cannot be empty." });
}
const activeProjects = input.snapshot.projects.filter((project) => project.deletedAt === null);
@@ -165,7 +169,9 @@ const findActiveProjectTarget = Effect.fn("findActiveProjectTarget")(function* (
const resolved = exactWorkspaceMatch;
if (!resolved) {
return yield* Effect.fail(new Error(`No active project found for '${trimmedIdentifier}'.`));
return yield* new ProjectCommandError({
message: `No active project found for '${trimmedIdentifier}'.`,
});
}
return {
@@ -185,7 +191,7 @@ const fetchLiveOrchestrationSnapshot = (origin: string, bearerToken: string) =>
"2xx": decodeOrchestrationReadModelResponse,
orElse: (response) =>
readErrorMessageFromResponse(response).pipe(
Effect.flatMap((message) => Effect.fail(new Error(message))),
Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),
),
}),
);
@@ -206,7 +212,7 @@ const dispatchLiveOrchestrationCommand = (
"2xx": () => Effect.void,
orElse: (response) =>
readErrorMessageFromResponse(response).pipe(
Effect.flatMap((message) => Effect.fail(new Error(message))),
Effect.flatMap((message) => Effect.fail(new ProjectCommandError({ message }))),
),
}),
),
@@ -331,9 +337,9 @@ const projectAddCommand = Command.make("add", {
(project) => project.deletedAt === null && project.workspaceRoot === workspaceRoot,
);
if (existingProject) {
return yield* Effect.fail(
new Error(`An active project already exists for '${workspaceRoot}'.`),
);
return yield* new ProjectCommandError({
message: `An active project already exists for '${workspaceRoot}'.`,
});
}
const title = yield* resolveProjectTitle(workspaceRoot, Option.getOrUndefined(flags.title));
@@ -345,7 +351,7 @@ const projectAddCommand = Command.make("add", {
title,
workspaceRoot,
defaultModelSelection: getAutoBootstrapDefaultModelSelection(),
createdAt: new Date().toISOString(),
createdAt: DateTime.formatIso(yield* DateTime.now),
});
return `Added project ${projectId} (${title}) at ${workspaceRoot}.`;
}),
+1 -1
View File
@@ -1,4 +1,4 @@
import { Effect } from "effect";
import * as Effect from "effect/Effect";
import { Command, GlobalFlag } from "effect/unstable/cli";
import { ServerConfig, type StartupPresentation } from "../config.ts";
+8 -8
View File
@@ -1,5 +1,5 @@
import { expect, it } from "@effect/vitest";
import { DateTime } from "effect";
import * as DateTime from "effect/DateTime";
import {
formatIssuedPairingCredential,
@@ -15,8 +15,8 @@ it("formats issued pairing credentials with the secret and optional pair URL", (
credential: "secret-pairing-token",
role: "client",
subject: "one-time-token",
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
createdAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),
expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
},
{ baseUrl: "https://example.com", json: false },
);
@@ -34,8 +34,8 @@ it("formats pairing listings without exposing the secret token", () => {
subject: "one-time-token",
label: "Phone",
role: "client",
createdAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
createdAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),
expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
},
],
{ json: false },
@@ -57,7 +57,7 @@ it("formats issued sessions with the bearer token but omits tokens from listings
label: "deploy-bot",
deviceType: "bot",
},
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
},
{ json: false },
);
@@ -75,8 +75,8 @@ it("formats issued sessions with the bearer token but omits tokens from listings
},
connected: false,
current: false,
issuedAt: DateTime.fromDateUnsafe(new Date("2026-04-08T09:00:00.000Z")),
expiresAt: DateTime.fromDateUnsafe(new Date("2026-04-08T10:00:00.000Z")),
issuedAt: DateTime.makeUnsafe("2026-04-08T09:00:00.000Z"),
expiresAt: DateTime.makeUnsafe("2026-04-08T10:00:00.000Z"),
lastConnectedAt: null,
},
],
+1 -1
View File
@@ -1,5 +1,5 @@
import type { AuthClientMetadata, AuthClientSession, AuthPairingLink } from "@t3tools/contracts";
import { DateTime } from "effect";
import * as DateTime from "effect/DateTime";
import type { IssuedBearerSession, IssuedPairingLink } from "./auth/Services/AuthControlPlane.ts";
+7 -1
View File
@@ -6,7 +6,13 @@
*
* @module ServerConfig
*/
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, Context } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as LogLevel from "effect/LogLevel";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import * as Context from "effect/Context";
export const DEFAULT_PORT = 3773;
@@ -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,43 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows process JSON with the schema decoder", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
[
"[",
'{"ProcessId":10,"ParentProcessId":1,"Name":"node.exe","CommandLine":"node server.js","Status":null,"WorkingSetSize":2048,"PercentProcessorTime":1.25},',
'{"ProcessId":11,"ParentProcessId":10,"Name":"agent.exe","CommandLine":null,"Status":"Running","WorkingSetSize":4096,"PercentProcessorTime":0}',
"]",
].join(""),
);
assert.deepEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Live",
cpuPercent: 1.25,
rssBytes: 2048,
elapsed: "",
command: "node server.js",
},
{
pid: 11,
ppid: 10,
pgid: null,
status: "Running",
cpuPercent: 0,
rssBytes: 4096,
elapsed: "",
command: "agent.exe",
},
]);
assert.deepEqual(ProcessDiagnostics.parseWindowsProcessRows("{"), []);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -26,7 +26,7 @@ interface ProcessRow {
readonly command: string;
}
const PROCESS_QUERY_TIMEOUT_MS = 1_000;
const PROCESS_QUERY_TIMEOUT = Duration.seconds(1);
const POSIX_PROCESS_QUERY_COMMAND = "pid=,ppid=,pgid=,stat=,pcpu=,rss=,etime=,command=";
const PROCESS_QUERY_MAX_OUTPUT_BYTES = 2 * 1024 * 1024;
@@ -50,6 +50,21 @@ class ProcessDiagnosticsError extends Schema.TaggedErrorClass<ProcessDiagnostics
cause: Schema.optional(Schema.Defect),
},
) {}
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
const WindowsProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Name: Schema.optional(Schema.NullOr(Schema.String)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
});
type WindowsProcessRecord = typeof WindowsProcessRecord.Type;
const decodeWindowsProcessJson = Schema.decodeOption(Schema.fromJsonString(Schema.Unknown));
const decodeWindowsProcessRecord = Schema.decodeUnknownOption(WindowsProcessRecord);
function toProcessDiagnosticsError(message: string, cause?: unknown): ProcessDiagnosticsError {
return new ProcessDiagnosticsError({
@@ -73,6 +88,12 @@ function parseNumber(value: string): number | null {
return Number.isFinite(parsed) ? parsed : null;
}
const trimNonEmptyOption = (value: string | null | undefined): Option.Option<string> =>
Option.fromNullishOr(value).pipe(
Option.map((entry) => entry.trim()),
Option.filter((entry) => entry.length > 0),
);
export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow> {
const rows: ProcessRow[] = [];
const rowPattern =
@@ -138,51 +159,54 @@ 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;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return decodeWindowsProcessRecord(value).pipe(
Option.flatMap((record: WindowsProcessRecord) => {
const commandLine = trimNonEmptyOption(record.CommandLine).pipe(
Option.orElse(() => trimNonEmptyOption(record.Name)),
);
if (
!Number.isInteger(record.ProcessId) ||
record.ProcessId <= 0 ||
!Number.isInteger(record.ParentProcessId) ||
record.ParentProcessId < 0 ||
Option.isNone(commandLine)
) {
return Option.none();
}
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
return Option.some({
pid: record.ProcessId,
ppid: record.ParentProcessId,
pgid: null,
status: Option.getOrElse(trimNonEmptyOption(record.Status), () => "Live"),
cpuPercent:
typeof record.PercentProcessorTime === "number" &&
Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0,
rssBytes:
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0,
elapsed: "",
command: commandLine.value,
});
}),
);
}
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
const parsed = decodeWindowsProcessJson(output);
if (Option.isNone(parsed)) return [];
const records = Array.isArray(parsed.value) ? parsed.value : [parsed.value];
return records.flatMap((record) =>
Option.match(normalizeWindowsProcessRow(record), {
onNone: () => [],
onSome: (row) => [row],
}),
);
}
function buildDescendantEntries(
@@ -308,7 +332,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.`)),
@@ -316,7 +340,7 @@ const runProcess = Effect.fn("runProcess")(
}),
),
Effect.mapError((cause) =>
Schema.is(ProcessDiagnosticsError)(cause)
isProcessDiagnosticsError(cause)
? cause
: toProcessDiagnosticsError(input.errorMessage, cause),
),
@@ -89,24 +89,14 @@ function toNumberValue(value: unknown): number | null {
function unixNanoToDateTime(value: unknown): DateTime.Utc | null {
const text = toStringValue(value);
if (!text) return null;
try {
const millis = Number(BigInt(text) / 1_000_000n);
if (!Number.isFinite(millis)) return null;
return DateTime.makeUnsafe(millis);
return Option.getOrNull(DateTime.make(millis));
} catch {
return null;
}
}
function isAfter(left: DateTime.Utc, right: DateTime.Utc): boolean {
return DateTime.toEpochMillis(left) > DateTime.toEpochMillis(right);
}
function isBefore(left: DateTime.Utc, right: DateTime.Utc): boolean {
return DateTime.toEpochMillis(left) < DateTime.toEpochMillis(right);
}
function readExitTag(exit: unknown): string | null {
if (!isRecordObject(exit) || !("_tag" in exit)) return null;
return toStringValue(exit._tag);
@@ -254,10 +244,11 @@ export function aggregateTraceDiagnostics(
recordCount += 1;
firstSpanAt =
startedAt && (firstSpanAt === null || isBefore(startedAt, firstSpanAt))
startedAt && (firstSpanAt === null || DateTime.isLessThan(startedAt, firstSpanAt))
? startedAt
: firstSpanAt;
lastSpanAt = lastSpanAt === null || isAfter(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
lastSpanAt =
lastSpanAt === null || DateTime.isGreaterThan(endedAt, lastSpanAt) ? endedAt : lastSpanAt;
const exitTag = readExitTag(parsed.exit);
const isFailure = exitTag === "Failure";
@@ -289,7 +280,7 @@ export function aggregateTraceDiagnostics(
const failureKey = `${name}\0${cause}`;
const existing = failuresByKey.get(failureKey);
const isLatestFailure = !existing || isAfter(endedAt, existing.lastSeenAt);
const isLatestFailure = !existing || DateTime.isGreaterThan(endedAt, existing.lastSeenAt);
failuresByKey.set(failureKey, {
name,
cause,
@@ -1,7 +1,12 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as nodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { Effect, Exit, FileSystem, Layer, PlatformError } from "effect";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "../../config.ts";
import { ServerEnvironment } from "../Services/ServerEnvironment.ts";
@@ -1,7 +1,12 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import { Effect, FileSystem, Layer, Path, Random } from "effect";
import * as Effect from "effect/Effect";
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 { 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";
@@ -89,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,19 +1,36 @@
import { afterEach, describe, expect, it } from "@effect/vitest";
import { Effect, FileSystem } from "effect";
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", () => {
@@ -23,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");
}),
@@ -31,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",
}),
);
}),
);
@@ -60,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",
}),
);
}),
);
@@ -108,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");
}),
@@ -116,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");
}),
@@ -130,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");
}),
@@ -1,8 +1,10 @@
import * as OS from "node:os";
import { Effect, FileSystem } from "effect";
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;
@@ -51,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* (
@@ -1,6 +1,6 @@
import type { EnvironmentId, ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import { Context } from "effect";
import type { Effect } from "effect";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
export interface ServerEnvironmentShape {
readonly getEnvironmentId: Effect.Effect<EnvironmentId>;
+58 -4
View File
@@ -1,10 +1,15 @@
// @effect-diagnostics nodeBuiltinImport:off
import fs from "node:fs";
import path from "node:path";
import { spawnSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Scope from "effect/Scope";
import { ChildProcessSpawner } from "effect/unstable/process";
import { expect } from "vitest";
import type {
@@ -32,6 +37,7 @@ import { ServerConfig } from "../config.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
ProjectSetupScriptRunner,
ProjectSetupScriptRunnerError,
type ProjectSetupScriptRunnerInput,
type ProjectSetupScriptRunnerShape,
} from "../project/Services/ProjectSetupScriptRunner.ts";
@@ -713,6 +719,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 13,
@@ -754,6 +761,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 14,
@@ -792,6 +800,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 0,
@@ -843,6 +852,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 16,
@@ -955,6 +965,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
};
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
prListSequence: [JSON.stringify([existingPr]), JSON.stringify([existingPr])],
},
});
@@ -981,6 +992,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 1661,
@@ -1034,8 +1046,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 488,
@@ -1110,6 +1125,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
"effect-atom": JSON.stringify([
{
number: 1618,
@@ -1121,6 +1137,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
updatedAt: "2026-03-01T10:00:00Z",
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"upstream/effect-atom": JSON.stringify([
{
number: 1518,
@@ -1132,8 +1149,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
updatedAt: "2026-04-01T10:00:00Z",
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"pingdotgg:effect-atom": JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"my-org/upstream:effect-atom": JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"pingdotgg:upstream/effect-atom": JSON.stringify([
{
number: 1518,
@@ -1145,6 +1165,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
updatedAt: "2026-04-01T10:00:00Z",
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"my-org/upstream:upstream/effect-atom": JSON.stringify([
{
number: 1518,
@@ -1194,6 +1215,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 22,
@@ -1231,6 +1253,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 23,
@@ -1262,6 +1285,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 45,
@@ -1612,6 +1636,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
"[]",
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 77,
@@ -1747,6 +1772,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
"[]",
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 303,
@@ -1793,6 +1819,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
"[]",
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 404,
@@ -1833,6 +1860,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 42,
@@ -1886,7 +1914,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 142,
@@ -1963,6 +1993,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
"effect-atom": JSON.stringify([
{
number: 1618,
@@ -1972,6 +2003,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
headRefName: "effect-atom",
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"upstream/effect-atom": JSON.stringify([
{
number: 1518,
@@ -1981,8 +2013,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
headRefName: "upstream/effect-atom",
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"pingdotgg:effect-atom": JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"my-org/upstream:effect-atom": JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"pingdotgg:upstream/effect-atom": JSON.stringify([
{
number: 1518,
@@ -1992,6 +2027,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
headRefName: "upstream/effect-atom",
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"my-org/upstream:upstream/effect-atom": JSON.stringify([
{
number: 1518,
@@ -2041,7 +2077,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
"t3code/pr-142/statemachine": JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
statemachine: JSON.stringify([
{
number: 41,
@@ -2051,6 +2089,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
headRefName: "statemachine",
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"octocat:statemachine": JSON.stringify([
{
number: 142,
@@ -2068,6 +2107,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
},
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"fork-seed:statemachine": JSON.stringify([]),
},
},
@@ -2112,6 +2152,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListByHeadSelector: {
// @effect-diagnostics-next-line preferSchemaOverJson:off
"octocat:statemachine": JSON.stringify([
{
number: 142,
@@ -2129,8 +2170,11 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
},
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"fork-seed:statemachine": JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
"t3code/pr-142/statemachine": JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
statemachine: JSON.stringify([]),
},
},
@@ -2170,6 +2214,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequence: [
"[]",
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 88,
@@ -2215,6 +2260,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager, ghCalls } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 1661,
@@ -2232,6 +2278,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
},
},
]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 188,
@@ -2294,7 +2341,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
ghScenario: {
prListSequenceByHeadSelector: {
"octocat:statemachine": [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 188,
@@ -2313,7 +2362,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
},
]),
],
// @effect-diagnostics-next-line preferSchemaOverJson:off
"fork-seed:statemachine": [JSON.stringify([])],
// @effect-diagnostics-next-line preferSchemaOverJson:off
statemachine: [JSON.stringify([])],
},
},
@@ -2870,7 +2921,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["add", "existing.txt"]);
yield* runGit(repoDir, ["commit", "-m", "Existing worktree branch"]);
yield* runGit(repoDir, ["checkout", "main"]);
const worktreePath = path.join(repoDir, "..", `pr-existing-${Date.now()}`);
const worktreePath = path.join(repoDir, "..", `pr-existing-${path.basename(repoDir)}`);
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-existing-worktree"]);
const setupCalls: ProjectSetupScriptRunnerInput[] = [];
@@ -3044,7 +3095,7 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
yield* runGit(repoDir, ["commit", "-m", "Reused fork PR branch"]);
yield* runGit(repoDir, ["push", "-u", "fork-seed", "feature/pr-reused-fork"]);
yield* runGit(repoDir, ["checkout", "main"]);
const worktreePath = path.join(repoDir, "..", `pr-reused-fork-${Date.now()}`);
const worktreePath = path.join(repoDir, "..", `pr-reused-fork-${path.basename(repoDir)}`);
yield* runGit(repoDir, ["worktree", "add", worktreePath, "feature/pr-reused-fork"]);
yield* runGit(worktreePath, ["branch", "--unset-upstream"], true);
@@ -3112,7 +3163,8 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
},
},
setupScriptRunner: {
runForThread: () => Effect.fail(new Error("terminal start failed")),
runForThread: () =>
Effect.fail(new ProjectSetupScriptRunnerError({ message: "terminal start failed" })),
},
});
@@ -3289,7 +3341,9 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
const { manager } = yield* makeManager({
ghScenario: {
prListSequence: [
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([]),
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{
number: 201,
+13 -15
View File
@@ -1,20 +1,18 @@
import { randomUUID } from "node:crypto";
import {
Array as Arr,
Cache,
Context,
DateTime,
Duration,
Effect,
Exit,
FileSystem,
Layer,
Option,
Order,
Path,
Ref,
} from "effect";
import * as Arr from "effect/Array";
import * as Cache from "effect/Cache";
import * as Context from "effect/Context";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Order from "effect/Order";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import {
GitActionProgressEvent,
GitActionProgressPhase,
@@ -1,5 +1,6 @@
import { assert, describe, it, vi } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as GitManager from "./GitManager.ts";
import * as GitWorkflowService from "./GitWorkflowService.ts";
+3 -1
View File
@@ -1,4 +1,6 @@
import { Context, Effect, Layer } from "effect";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import {
GitManagerError,
+1
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
import { existsSync } from "node:fs";
import { join } from "node:path";
+16 -4
View File
@@ -1,6 +1,10 @@
import Mime from "@effect/platform-node/Mime";
import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";
import { Data, Effect, FileSystem, Option, Path } from "effect";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import { cast } from "effect/Function";
import {
HttpBody,
@@ -24,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>`;
@@ -31,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,
});
@@ -65,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 -5
View File
@@ -2,7 +2,13 @@ import { KeybindingCommand, KeybindingRule, KeybindingsConfig } from "@t3tools/c
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Cause, Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
import { ServerConfig } from "./config.ts";
import {
@@ -17,6 +23,12 @@ import {
import { KeybindingsConfigError } from "@t3tools/contracts";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const encodeKeybindingsConfigJson = Schema.encodeEffect(KeybindingsConfigJson);
const decodeKeybindingsConfigJson = Schema.decodeUnknownEffect(KeybindingsConfigJson);
const encodeResolvedKeybindingFromConfig = Schema.encodeEffect(ResolvedKeybindingFromConfig);
const decodeResolvedKeybindingFromConfigExit = Schema.decodeUnknownExit(
ResolvedKeybindingFromConfig,
);
const makeKeybindingsLayer = () => {
return KeybindingsLive.pipe(
Layer.provideMerge(
@@ -39,7 +51,7 @@ const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRu
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
const encoded = yield* encodeKeybindingsConfigJson(rules);
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
yield* fileSystem.writeFileString(configPath, encoded);
});
@@ -48,7 +60,7 @@ const readKeybindingsConfig = (configPath: string) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const rawConfig = yield* fileSystem.readFileString(configPath);
return yield* Schema.decodeUnknownEffect(KeybindingsConfigJson)(rawConfig);
return yield* decodeKeybindingsConfigJson(rawConfig);
});
it.layer(NodeServices.layer)("keybindings", (it) => {
@@ -105,7 +117,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
it.effect("encodes resolved plus-key shortcuts", () =>
Effect.gen(function* () {
const encoded = yield* Schema.encodeEffect(ResolvedKeybindingFromConfig)({
const encoded = yield* encodeResolvedKeybindingFromConfig({
command: "terminal.toggle",
shortcut: {
key: "+",
@@ -151,7 +163,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
it.effect("formats invalid resolved keybinding rules with the custom message", () =>
Effect.sync(() => {
const result = Schema.decodeUnknownExit(ResolvedKeybindingFromConfig)({
const result = decodeResolvedKeybindingFromConfigExit({
key: "mod+shift+d+o",
command: "terminal.new",
});
@@ -229,6 +241,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
const { keybindingsConfigPath } = yield* ServerConfig;
yield* fs.writeFileString(
keybindingsConfigPath,
// @effect-diagnostics-next-line preferSchemaOverJson:off
JSON.stringify([
{ key: "mod+j", command: "terminal.toggle" },
{ key: "mod+shift+d+o", command: "terminal.new" },
+32 -40
View File
@@ -19,33 +19,30 @@ import {
type ServerUpsertKeybindingInput,
type ServerConfigIssue,
} from "@t3tools/contracts";
import {
Array,
Cache,
Cause,
Deferred,
Duration,
Effect,
Exit,
FileSystem,
Path,
Layer,
Option,
Predicate,
PubSub,
Schema,
SchemaGetter,
SchemaIssue,
SchemaTransformation,
Ref,
Context,
Scope,
Stream,
} from "effect";
import * as Array from "effect/Array";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
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 Predicate from "effect/Predicate";
import * as PubSub from "effect/PubSub";
import * as Schema from "effect/Schema";
import * as SchemaIssue from "effect/SchemaIssue";
import * as SchemaTransformation from "effect/SchemaTransformation";
import * as Ref from "effect/Ref";
import * as Context from "effect/Context";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config.ts";
import { writeFileStringAtomically } from "./atomicWrite.ts";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
import {
DEFAULT_KEYBINDINGS,
DEFAULT_RESOLVED_KEYBINDINGS,
@@ -172,16 +169,11 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
}
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
const KeybindingsConfigPrettyJson = KeybindingsConfigJson.pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
);
const KeybindingsConfigPrettyJson = fromJsonStringPretty(KeybindingsConfig);
const decodeKeybindingRuleExit = Schema.decodeUnknownExit(KeybindingRule);
const decodeResolvedKeybindingFromConfigExit = Schema.decodeExit(ResolvedKeybindingFromConfig);
const decodeRawKeybindingsEntriesExit = Schema.decodeUnknownExit(RawKeybindingsEntries);
const encodeKeybindingsConfigPrettyJson = Schema.encodeEffect(KeybindingsConfigPrettyJson);
export interface KeybindingsConfigState {
readonly keybindings: ResolvedKeybindingsConfig;
@@ -356,7 +348,7 @@ const makeKeybindings = Effect.gen(function* () {
return yield* Effect.forEach(rawConfig, (entry) =>
Effect.gen(function* () {
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
const decodedRule = decodeKeybindingRuleExit(entry);
if (decodedRule._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
@@ -365,7 +357,7 @@ const makeKeybindings = Effect.gen(function* () {
});
return null;
}
const resolved = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
const resolved = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
if (resolved._tag === "Failure") {
yield* Effect.logWarning("ignoring invalid keybinding entry", {
path: keybindingsConfigPath,
@@ -391,7 +383,7 @@ const makeKeybindings = Effect.gen(function* () {
}
const rawConfig = yield* readRawConfig;
const decodedEntries = Schema.decodeUnknownExit(RawKeybindingsEntries)(rawConfig);
const decodedEntries = decodeRawKeybindingsEntriesExit(rawConfig);
if (decodedEntries._tag === "Failure") {
const detail = `expected JSON array (${Cause.pretty(decodedEntries.cause)})`;
return {
@@ -403,7 +395,7 @@ const makeKeybindings = Effect.gen(function* () {
const keybindings: KeybindingRule[] = [];
const issues: ServerConfigIssue[] = [];
for (const [index, entry] of decodedEntries.value.entries()) {
const decodedRule = Schema.decodeUnknownExit(KeybindingRule)(entry);
const decodedRule = decodeKeybindingRuleExit(entry);
if (decodedRule._tag === "Failure") {
const detail = Cause.pretty(decodedRule.cause);
issues.push(invalidEntryIssue(index, detail));
@@ -416,7 +408,7 @@ const makeKeybindings = Effect.gen(function* () {
continue;
}
const resolvedRule = Schema.decodeExit(ResolvedKeybindingFromConfig)(decodedRule.value);
const resolvedRule = decodeResolvedKeybindingFromConfigExit(decodedRule.value);
if (resolvedRule._tag === "Failure") {
const detail = Cause.pretty(resolvedRule.cause);
issues.push(invalidEntryIssue(index, detail));
@@ -435,7 +427,7 @@ const makeKeybindings = Effect.gen(function* () {
});
const writeConfigAtomically = (rules: readonly KeybindingRule[]) => {
return Schema.encodeEffect(KeybindingsConfigPrettyJson)(rules).pipe(
return encodeKeybindingsConfigPrettyJson(rules).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.flatMap((encoded) =>
writeFileStringAtomically({
+2 -1
View File
@@ -1,4 +1,5 @@
import { Cause, Exit } from "effect";
import * as Cause from "effect/Cause";
import * as Exit from "effect/Exit";
export type MetricAttributeValue = string;
export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
@@ -1,5 +1,8 @@
import { makeLocalFileTracer, makeTraceSink } from "@t3tools/shared/observability";
import { Effect, Layer, References, Tracer } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as References from "effect/References";
import * as Tracer from "effect/Tracer";
import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { ServerConfig } from "../../config.ts";
@@ -1,7 +1,10 @@
import { assert, describe, it } from "@effect/vitest";
import { ProviderDriverKind } from "@t3tools/contracts";
import { Duration, Effect, Fiber, Metric } from "effect";
import { TestClock } from "effect/testing";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Metric from "effect/Metric";
import * as TestClock from "effect/testing/TestClock";
import { withMetrics } from "./Metrics.ts";
+5 -1
View File
@@ -1,4 +1,8 @@
import { Clock, Duration, Effect, Exit, Metric } from "effect";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Metric from "effect/Metric";
import { dual } from "effect/Function";
import {
@@ -1,7 +1,13 @@
import { assert, describe, it } from "@effect/vitest";
import { WS_METHODS } from "@t3tools/contracts";
import { Duration, Effect, Exit, Fiber, Metric, Stream, Tracer } from "effect";
import { TestClock } from "effect/testing";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Fiber from "effect/Fiber";
import * as Metric from "effect/Metric";
import * as Stream from "effect/Stream";
import * as Tracer from "effect/Tracer";
import * as TestClock from "effect/testing/TestClock";
import {
observeRpcEffect,
@@ -1,5 +1,11 @@
import { WS_METHODS } from "@t3tools/contracts";
import { Clock, Duration, Effect, Exit, Metric, References, Stream } from "effect";
import * as Clock from "effect/Clock";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Metric from "effect/Metric";
import * as References from "effect/References";
import * as Stream from "effect/Stream";
import { outcomeFromExit } from "./Attributes.ts";
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
@@ -1,6 +1,6 @@
import type { TraceRecord } from "@t3tools/shared/observability";
import { Context } from "effect";
import type { Effect } from "effect";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
export interface BrowserTraceCollectorShape {
readonly record: (records: ReadonlyArray<TraceRecord>) => Effect.Effect<void>;
-238
View File
@@ -1,238 +0,0 @@
/**
* 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 { Context, Effect, Layer } from "effect";
// ==============================
// 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);
+2 -1
View File
@@ -1,4 +1,5 @@
import { SchemaIssue, Schema } from "effect";
import * as SchemaIssue from "effect/SchemaIssue";
import * as Schema from "effect/Schema";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
@@ -19,7 +20,14 @@ import {
TurnId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import * as Clock from "effect/Clock";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as PubSub from "effect/PubSub";
import * as Scope from "effect/Scope";
import * as Stream from "effect/Stream";
import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
@@ -73,7 +81,7 @@ function createProviderServiceHarness(
sessionCwd = cwd,
providerName: ProviderSession["provider"] = ProviderDriverKind.make("codex"),
) {
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
const rollbackConversation = vi.fn(
(_input: { readonly threadId: ThreadId; readonly numTurns: number }) => Effect.void,
@@ -148,7 +156,7 @@ async function waitForThread(
}) => boolean,
timeoutMs = 15_000,
) {
const deadline = Date.now() + timeoutMs;
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async (): Promise<{
latestTurn: { turnId: string } | null;
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
@@ -159,10 +167,10 @@ async function waitForThread(
if (thread && predicate(thread)) {
return thread;
}
if (Date.now() >= deadline) {
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
throw new Error("Timed out waiting for thread state.");
}
await new Promise((resolve) => setTimeout(resolve, 10));
await Effect.runPromise(Effect.sleep("10 millis"));
return poll();
};
return poll();
@@ -173,7 +181,7 @@ async function waitForEvent(
predicate: (event: { type: string }) => boolean,
timeoutMs = 15_000,
) {
const deadline = Date.now() + timeoutMs;
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async () => {
const events = await Effect.runPromise(
Stream.runCollect(engine.readEvents(0)).pipe(Effect.map((chunk) => Array.from(chunk))),
@@ -181,10 +189,10 @@ async function waitForEvent(
if (events.some(predicate)) {
return events;
}
if (Date.now() >= deadline) {
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
throw new Error("Timed out waiting for orchestration event.");
}
await new Promise((resolve) => setTimeout(resolve, 10));
await Effect.runPromise(Effect.sleep("10 millis"));
return poll();
};
return poll();
@@ -223,15 +231,15 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
}
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
const deadline = Date.now() + timeoutMs;
const deadline = (await Effect.runPromise(Clock.currentTimeMillis)) + timeoutMs;
const poll = async (): Promise<void> => {
if (gitRefExists(cwd, ref)) {
return;
}
if (Date.now() >= deadline) {
if ((await Effect.runPromise(Clock.currentTimeMillis)) >= deadline) {
throw new Error(`Timed out waiting for git ref '${ref}'.`);
}
await new Promise((resolve) => setTimeout(resolve, 10));
await Effect.runPromise(Effect.sleep("10 millis"));
return poll();
};
return poll();
@@ -342,7 +350,7 @@ describe("CheckpointReactor", () => {
await Effect.runPromise(reactor.start().pipe(Scope.provide(scope)));
const drain = () => Effect.runPromise(reactor.drain);
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
engine.dispatch({
type: "project.create",
@@ -410,7 +418,7 @@ describe("CheckpointReactor", () => {
it("captures pre-turn baseline on turn.started and post-turn checkpoint on turn.completed", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -435,7 +443,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-started-1"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-1"),
});
@@ -450,7 +458,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-completed-1"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-1"),
payload: { state: "completed" },
@@ -495,7 +503,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-refresh-local-status"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-refresh-local-status"),
payload: { state: "completed" },
@@ -508,7 +516,7 @@ describe("CheckpointReactor", () => {
it("ignores auxiliary thread turn completion while primary turn is active", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -533,7 +541,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-started-main"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-main"),
});
@@ -549,7 +557,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-completed-aux"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-aux"),
payload: { state: "completed" },
@@ -565,7 +573,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-completed-main"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-main"),
payload: { state: "completed" },
@@ -583,7 +591,7 @@ describe("CheckpointReactor", () => {
seedFilesystemCheckpoints: false,
providerName: ProviderDriverKind.make("claudeAgent"),
});
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -607,7 +615,7 @@ describe("CheckpointReactor", () => {
type: "turn.started",
eventId: EventId.make("evt-turn-started-claude-1"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
});
@@ -621,7 +629,7 @@ describe("CheckpointReactor", () => {
type: "turn.completed",
eventId: EventId.make("evt-turn-completed-claude-1"),
provider: ProviderDriverKind.make("claudeAgent"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-claude-1"),
payload: { state: "completed" },
@@ -641,7 +649,7 @@ describe("CheckpointReactor", () => {
it("appends capture failure activity when turn diff summary cannot be derived", async () => {
const harness = await createHarness({ seedFilesystemCheckpoints: false });
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -666,7 +674,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-completed-missing-baseline"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-missing-baseline"),
payload: { state: "completed" },
@@ -706,7 +714,7 @@ describe("CheckpointReactor", () => {
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
}),
);
@@ -729,7 +737,7 @@ describe("CheckpointReactor", () => {
seedFilesystemCheckpoints: false,
threadWorktreePath: null,
});
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -755,7 +763,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-completed-missing-provider-cwd"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-missing-cwd"),
payload: { state: "completed" },
@@ -776,7 +784,7 @@ describe("CheckpointReactor", () => {
it("ignores non-v2 checkpoint.captured runtime events", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -801,7 +809,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-checkpoint-captured-3"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-3"),
turnCount: 3,
@@ -826,7 +834,7 @@ describe("CheckpointReactor", () => {
seedFilesystemCheckpoints: false,
providerSessionCwd: nonRepositorySessionCwd,
});
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -851,7 +859,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-runtime-capture-failure"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-runtime-failure"),
payload: { state: "completed" },
@@ -862,7 +870,7 @@ describe("CheckpointReactor", () => {
eventId: EventId.make("evt-turn-started-after-runtime-failure"),
provider: ProviderDriverKind.make("codex"),
createdAt: new Date().toISOString(),
createdAt: "2026-01-01T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
turnId: asTurnId("turn-after-runtime-failure"),
});
@@ -878,7 +886,7 @@ describe("CheckpointReactor", () => {
it("executes provider revert and emits thread.reverted for checkpoint revert requests", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -959,7 +967,7 @@ describe("CheckpointReactor", () => {
it("executes provider revert and emits thread.reverted for claude sessions", async () => {
const harness = await createHarness({ providerName: ProviderDriverKind.make("claudeAgent") });
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -1028,7 +1036,7 @@ describe("CheckpointReactor", () => {
it("processes consecutive revert requests with deterministic rollback sequencing", async () => {
const harness = await createHarness();
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -1111,7 +1119,7 @@ describe("CheckpointReactor", () => {
it("appends an error activity when revert is requested without an active session", async () => {
const harness = await createHarness({ hasSession: false });
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
harness.engine.dispatch({
@@ -8,7 +8,12 @@ import {
type OrchestrationEvent,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { Cause, Effect, Layer, Option, Stream } from "effect";
import * as Cause from "effect/Cause";
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 Stream from "effect/Stream";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { parseTurnDiffFilesFromUnifiedDiff } from "../../checkpointing/Diffs.ts";
@@ -28,6 +33,8 @@ import { isGitRepository } from "../../git/Utils.ts";
import { VcsStatusBroadcaster } from "../../vcs/VcsStatusBroadcaster.ts";
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
type ReactorInput =
| {
readonly source: "runtime";
@@ -584,7 +591,7 @@ const make = Effect.gen(function* () {
const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
) {
const now = new Date().toISOString();
const now = DateTime.formatIso(yield* DateTime.now);
const thread = yield* resolveThreadDetail(event.payload.threadId);
if (!thread) {
@@ -717,12 +724,14 @@ const make = Effect.gen(function* () {
if (event.type === "thread.checkpoint-revert-requested") {
yield* handleRevertRequested(event).pipe(
Effect.catch((error) =>
appendRevertFailureActivity({
threadId: event.payload.threadId,
turnCount: event.payload.turnCount,
detail: error.message,
createdAt: new Date().toISOString(),
}),
Effect.flatMap(nowIso, (createdAt) =>
appendRevertFailureActivity({
threadId: event.payload.threadId,
turnCount: event.payload.turnCount,
detail: error.message,
createdAt,
}),
),
),
);
return;
@@ -736,12 +745,14 @@ const make = Effect.gen(function* () {
if (event.type === "thread.turn-diff-completed") {
yield* captureCheckpointFromPlaceholder(event).pipe(
Effect.catch((error) =>
appendCaptureFailureActivity({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
detail: error.message,
createdAt: new Date().toISOString(),
}).pipe(Effect.catch(() => Effect.void)),
Effect.flatMap(nowIso, (createdAt) =>
appendCaptureFailureActivity({
threadId: event.payload.threadId,
turnId: event.payload.turnId,
detail: error.message,
createdAt,
}).pipe(Effect.catch(() => Effect.void)),
),
),
);
}
@@ -760,12 +771,14 @@ const make = Effect.gen(function* () {
yield* refreshLocalGitStatusFromTurnCompletion(event);
yield* captureCheckpointFromTurnCompletion(event).pipe(
Effect.catch((error) =>
appendCaptureFailureActivity({
threadId: event.threadId,
turnId,
detail: error.message,
createdAt: new Date().toISOString(),
}).pipe(Effect.catch(() => Effect.void)),
Effect.flatMap(nowIso, (createdAt) =>
appendCaptureFailureActivity({
threadId: event.threadId,
turnId,
detail: error.message,
createdAt,
}).pipe(Effect.catch(() => Effect.void)),
),
),
);
return;
@@ -1,81 +0,0 @@
import { assert, it } from "@effect/vitest";
import { CommandId, MessageId, ThreadId } from "@t3tools/contracts";
import { DateTime, Effect, Layer, Option, Ref, Stream } from "effect";
import { TestClock } from "effect/testing";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import {
OrchestrationCommandReceiptRepository,
type OrchestrationCommandReceipt,
} from "../../persistence/Services/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
import { createEmptyReadModel } from "../projector.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
it.effect("uses TestClock-backed DateTime for rejected command receipts", () =>
Effect.gen(function* () {
const capturedReceipt = yield* Ref.make<Option.Option<OrchestrationCommandReceipt>>(
Option.none(),
);
const fixedNow = DateTime.makeUnsafe("2026-05-08T16:30:00.000Z");
const fixedNowIso = DateTime.formatIso(fixedNow);
const receiptRepositoryLayer = Layer.mock(OrchestrationCommandReceiptRepository)({
getByCommandId: () => Effect.succeed(Option.none()),
upsert: (receipt) => Ref.set(capturedReceipt, Option.some(receipt)),
});
const testLayer = OrchestrationEngineLive.pipe(
Layer.provide(
Layer.mock(ProjectionSnapshotQuery)({
getCommandReadModel: () => Effect.succeed(createEmptyReadModel(fixedNowIso)),
}),
),
Layer.provide(
Layer.mock(OrchestrationProjectionPipeline)({
bootstrap: Effect.void,
}),
),
Layer.provide(
Layer.mock(OrchestrationEventStore)({
readFromSequence: () => Stream.empty,
}),
),
Layer.provide(receiptRepositoryLayer),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(TestClock.layer()),
);
yield* Effect.gen(function* () {
yield* TestClock.setTime(DateTime.toEpochMillis(fixedNow));
const engine = yield* OrchestrationEngineService;
const result = yield* Effect.result(
engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.make("cmd-clock-rejected"),
threadId: ThreadId.make("thread-missing-clock"),
message: {
messageId: MessageId.make("msg-clock-rejected"),
role: "user",
text: "hello",
attachments: [],
},
interactionMode: "default",
runtimeMode: "approval-required",
createdAt: fixedNowIso,
}),
);
assert.equal(result._tag, "Failure");
const receipt = yield* Ref.get(capturedReceipt);
assert.isTrue(Option.isSome(receipt));
if (Option.isNone(receipt)) {
return;
}
assert.equal(receipt.value.acceptedAt, fixedNowIso);
}).pipe(Effect.provide(testLayer));
}),
);
@@ -8,9 +8,15 @@ import {
TurnId,
type OrchestrationEvent,
ProviderInstanceId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
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";
import * as Metric from "effect/Metric";
import * as Option from "effect/Option";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -32,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);
@@ -69,7 +74,7 @@ async function createOrchestrationSystem() {
}
function now() {
return new Date().toISOString();
return "2026-01-01T00:00:00.000Z";
}
const hasMetricSnapshot = (
@@ -178,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 }),
@@ -185,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()),
}),
@@ -773,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));
@@ -915,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));
@@ -5,21 +5,20 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { OrchestrationCommand } from "@t3tools/contracts";
import {
Cause,
DateTime,
Deferred,
Duration,
Effect,
Exit,
Layer,
Metric,
Option,
PubSub,
Queue,
Schema,
Stream,
} from "effect";
import * as Cause from "effect/Cause";
import * as Clock from "effect/Clock";
import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as Metric from "effect/Metric";
import * as Option from "effect/Option";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
@@ -45,6 +44,10 @@ import {
OrchestrationEngineService,
type OrchestrationEngineShape,
} from "../Services/OrchestrationEngine.ts";
const isOrchestrationCommandPreviouslyRejectedError = Schema.is(
OrchestrationCommandPreviouslyRejectedError,
);
const isOrchestrationCommandInvariantError = Schema.is(OrchestrationCommandInvariantError);
interface CommandEnvelope {
command: OrchestrationCommand;
@@ -52,9 +55,6 @@ interface CommandEnvelope {
startedAtMs: number;
}
const currentIso = DateTime.now.pipe(Effect.map(DateTime.formatIso));
const currentEpochMillis = DateTime.now.pipe(Effect.map(DateTime.toEpochMillis));
function commandToAggregateRef(command: OrchestrationCommand): {
readonly aggregateKind: "project" | "thread";
readonly aggregateId: ProjectId | ThreadId;
@@ -82,7 +82,8 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
let commandReadModel = createEmptyReadModel(yield* currentIso);
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
let commandReadModel = createEmptyReadModel(yield* nowIso);
const commandQueue = yield* Queue.unbounded<CommandEnvelope>();
const eventPubSub = yield* PubSub.unbounded<OrchestrationEvent>();
@@ -101,6 +102,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
const dispatchStartSequence = commandReadModel.snapshotSequence;
let processingStartedAtMs = 0;
const aggregateRef = commandToAggregateRef(envelope.command);
const baseMetricAttributes = {
commandType: envelope.command.type,
@@ -121,164 +123,165 @@ const makeOrchestrationEngine = Effect.gen(function* () {
}
});
return Effect.gen(function* () {
const processingStartedAtMs = yield* currentEpochMillis;
const exit = yield* Effect.exit(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"orchestration.command_id": envelope.command.commandId,
"orchestration.command_type": envelope.command.type,
"orchestration.aggregate_kind": aggregateRef.aggregateKind,
"orchestration.aggregate_id": aggregateRef.aggregateId,
});
return Effect.exit(
Effect.gen(function* () {
processingStartedAtMs = yield* Clock.currentTimeMillis;
yield* Effect.annotateCurrentSpan({
"orchestration.command_id": envelope.command.commandId,
"orchestration.command_type": envelope.command.type,
"orchestration.aggregate_kind": aggregateRef.aggregateKind,
"orchestration.aggregate_id": aggregateRef.aggregateId,
});
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
commandId: envelope.command.commandId,
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
return {
sequence: existingReceipt.value.resultSequence,
};
}
return yield* new OrchestrationCommandPreviouslyRejectedError({
commandId: envelope.command.commandId,
detail: existingReceipt.value.error ?? "Previously rejected.",
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
}
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel: commandReadModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextCommandReadModel = commandReadModel;
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
});
}
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
});
return {
sequence: existingReceipt.value.resultSequence,
};
}
return yield* new OrchestrationCommandPreviouslyRejectedError({
commandId: envelope.command.commandId,
detail: existingReceipt.value.error ?? "Previously rejected.",
});
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextCommandReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
),
),
);
commandReadModel = committedCommand.nextCommandReadModel;
for (const [index, event] of committedCommand.committedEvents.entries()) {
yield* PubSub.publish(eventPubSub, event);
if (index === 0) {
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandAckDuration,
metricAttributes({
...baseMetricAttributes,
ackEventType: event.type,
}),
),
Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - envelope.startedAtMs)),
);
}
}
return { sequence: committedCommand.lastSequence };
}).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
).pipe(
Effect.flatMap((exit) =>
Effect.gen(function* () {
const outcome = Exit.isSuccess(exit)
? "success"
: Cause.hasInterruptsOnly(exit.cause)
? "interrupt"
: "failure";
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandDuration,
metricAttributes(baseMetricAttributes),
),
Duration.millis(Math.max(0, (yield* Clock.currentTimeMillis) - processingStartedAtMs)),
);
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandsTotal,
metricAttributes({
...baseMetricAttributes,
outcome,
}),
),
1,
);
if (Exit.isSuccess(exit)) {
yield* Deferred.succeed(envelope.result, exit.value);
return;
}
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel: commandReadModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextCommandReadModel = commandReadModel;
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextCommandReadModel = yield* projectEvent(nextCommandReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
});
}
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
});
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextCommandReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(
sqlError,
),
const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
if (!isOrchestrationCommandPreviouslyRejectedError(error)) {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: commandReadModel.snapshotSequence,
}),
),
),
);
commandReadModel = committedCommand.nextCommandReadModel;
for (const [index, event] of committedCommand.committedEvents.entries()) {
yield* PubSub.publish(eventPubSub, event);
if (index === 0) {
const acknowledgedAtMs = yield* currentEpochMillis;
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandAckDuration,
metricAttributes({
...baseMetricAttributes,
ackEventType: event.type,
}),
),
Duration.millis(Math.max(0, acknowledgedAtMs - envelope.startedAtMs)),
);
if (isOrchestrationCommandInvariantError(error)) {
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: yield* nowIso,
resultSequence: commandReadModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
}
}
return { sequence: committedCommand.lastSequence };
}).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
);
const outcome = Exit.isSuccess(exit)
? "success"
: Cause.hasInterruptsOnly(exit.cause)
? "interrupt"
: "failure";
const processedAtMs = yield* currentEpochMillis;
yield* Metric.update(
Metric.withAttributes(orchestrationCommandDuration, metricAttributes(baseMetricAttributes)),
Duration.millis(Math.max(0, processedAtMs - processingStartedAtMs)),
);
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandsTotal,
metricAttributes({
...baseMetricAttributes,
outcome,
}),
),
1,
);
if (Exit.isSuccess(exit)) {
yield* Deferred.succeed(envelope.result, exit.value);
return;
}
const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: commandReadModel.snapshotSequence,
}),
),
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
const rejectedAt = yield* currentIso;
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: rejectedAt,
resultSequence: commandReadModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
}
}
yield* Deferred.fail(envelope.result, error);
});
yield* Deferred.fail(envelope.result, error);
}),
),
);
};
yield* projectionPipeline.bootstrap;
@@ -296,8 +299,11 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
const startedAtMs = yield* currentEpochMillis;
yield* Queue.offer(commandQueue, { command, result, startedAtMs });
yield* Queue.offer(commandQueue, {
command,
result,
startedAtMs: yield* Clock.currentTimeMillis,
});
return yield* Deferred.await(result);
});
@@ -1,4 +1,8 @@
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Layer from "effect/Layer";
import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Scope from "effect/Scope";
import { afterEach, describe, expect, it } from "vitest";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
@@ -1,4 +1,5 @@
import { Effect, Layer } from "effect";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import {
OrchestrationReactor,
@@ -11,7 +11,10 @@ import {
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -55,7 +58,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
yield* eventStore.append({
type: "project.created",
@@ -180,7 +183,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))(
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
yield* eventStore.append({
type: "thread.message-sent",
@@ -224,6 +227,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-base-")))(
WHERE message_id = 'message-attachments'
`;
assert.equal(rows.length, 1);
// @effect-diagnostics-next-line preferSchemaOverJson:off
assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
{
type: "image",
@@ -246,7 +250,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
yield* eventStore.append({
type: "thread.message-sent",
@@ -297,6 +301,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
WHERE message_id = 'message-attachments-safe'
`;
assert.equal(rows.length, 1);
// @effect-diagnostics-next-line preferSchemaOverJson:off
assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
{
type: "image",
@@ -326,8 +331,8 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const later = new Date(Date.now() + 1_000).toISOString();
const now = "2026-01-01T00:00:00.000Z";
const later = "2026-01-01T00:00:01.000Z";
yield* eventStore.append({
type: "project.created",
@@ -441,6 +446,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
WHERE message_id = 'message-clear-attachments'
`;
assert.equal(rows.length, 1);
// @effect-diagnostics-next-line preferSchemaOverJson:off
assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), []);
}),
);
@@ -454,8 +460,8 @@ it.layer(
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const later = new Date(Date.now() + 1_000).toISOString();
const now = "2026-01-01T00:00:00.000Z";
const later = "2026-01-01T00:00:01.000Z";
yield* eventStore.append({
type: "project.created",
@@ -576,6 +582,7 @@ it.layer(
WHERE message_id = 'message-overwrite'
`;
assert.equal(rows.length, 1);
// @effect-diagnostics-next-line preferSchemaOverJson:off
assert.deepEqual(JSON.parse(rows[0]?.attachmentsJson ?? "null"), [
{
type: "image",
@@ -598,7 +605,7 @@ it.layer(
const eventStore = yield* OrchestrationEventStore;
const path = yield* Path.Path;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
@@ -722,7 +729,7 @@ it.layer(
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const { attachmentsDir } = yield* ServerConfig;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("Thread Revert.Files");
const keepAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000001";
const removeAttachmentId = "thread-revert-files-00000000-0000-4000-8000-000000000002";
@@ -931,7 +938,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const { attachmentsDir } = yield* ServerConfig;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
const threadId = ThreadId.make("Thread Delete.Files");
const attachmentId = "thread-delete-files-00000000-0000-4000-8000-000000000001";
const otherThreadAttachmentId =
@@ -1063,7 +1070,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
const path = yield* Path.Path;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
const { attachmentsDir: attachmentsRootDir, stateDir } = yield* ServerConfig;
const attachmentsSentinelPath = path.join(attachmentsRootDir, "sentinel.txt");
const stateDirSentinelPath = path.join(stateDir, "state-sentinel.txt");
@@ -1103,7 +1110,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
yield* eventStore.append({
type: "project.created",
@@ -1230,7 +1237,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const now = new Date().toISOString();
const now = "2026-01-01T00:00:00.000Z";
yield* eventStore.append({
type: "project.created",
@@ -2187,7 +2194,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
Effect.gen(function* () {
const engine = yield* OrchestrationEngineService;
const sql = yield* SqlClient.SqlClient;
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
yield* engine.dispatch({
type: "project.create",
@@ -2225,7 +2232,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
Effect.gen(function* () {
const engine = yield* OrchestrationEngineService;
const sql = yield* SqlClient.SqlClient;
const createdAt = new Date().toISOString();
const createdAt = "2026-01-01T00:00:00.000Z";
yield* engine.dispatch({
type: "project.create",
@@ -4,7 +4,12 @@ import {
type OrchestrationEvent,
ThreadId,
} from "@t3tools/contracts";
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Stream from "effect/Stream";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { toPersistenceSqlError, type ProjectionRepositoryError } from "../../persistence/Errors.ts";
Loaded 100 of 504 files, more files were not shown because too many files have changed in this diff. Show more