Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex 3bec3d2c8d Optimize streaming message projection path
Co-authored-by: codex <[email protected]>
2026-04-02 02:21:12 -07:00
Julius Marmingeandcodex b24b5fb8ce Trim checkpoint reactor stream fanout
Co-authored-by: codex <[email protected]>
2026-04-02 02:21:09 -07:00
Julius Marmingeandcodex 0be82d3443 Add server perf latency baselines
Co-authored-by: codex <[email protected]>
2026-04-02 02:21:06 -07:00
Julius Marminge 7a1b982926 Broaden perf seed coverage across multiple projects
- Seed large_threads across 5 projects with bounded heavy turns
- Add shared perf server env setup and update harness assertions
- Co-authored-by: codex <[email protected]>
2026-04-02 01:07:51 -07:00
Julius Marminge 062c809aa0 Clean up perf run dirs and cover collector reset
- Persist and remove the seeded run parent directory after perf runs
- Add regression coverage for seed cleanup, percentile clamping, and RAF reset
2026-04-02 00:37:23 -07:00
Julius Marminge b8fba18575 Document local performance benchmark harness
- Add README entry for perf benchmarks
- Document scenarios, commands, artifacts, and env vars
2026-04-02 00:14:42 -07:00
Julius Marminge f1f234d2a0 Exclude perf tests from Vitest default runs
- Keep `bun run test` focused on non-perf suites
2026-04-02 00:04:00 -07:00
Julius Marminge 18f19a6fe8 Add perf regression coverage for dense stream workloads
- Expand perf fixtures with multi-thread live stream events and namespaced IDs
- Harden stream getters and update web perf tests for the heavier workload
2026-04-01 18:56:42 -07:00
Julius Marminge efa6d97da0 Record updated performance regression artifacts
- Refresh virtualization and websocket perf snapshots
- Keep perf baselines in sync with latest run
2026-04-01 14:00:31 -07:00
Julius Marminge 5804697e92 Add perf regression test harnesses
- Seed reusable perf fixtures for server scenarios
- Add perf provider adapter and web perf tests
- Capture artifacts for virtualization and websocket runs
2026-04-01 13:59:21 -07:00
Julius Marmingeandcodex 9132c37c86 [codex] migrate Effect.fn in apps/server/src/persistence/NodeSqliteClient.ts (#1633)
Co-authored-by: codex <[email protected]>
2026-04-01 16:34:52 +00:00
Julius Marmingeandcodex b9c7ea0581 [codex] migrate Effect.fn in apps/server/src/orchestration/Layers/ProviderCommandReactor.ts (#1629)
Co-authored-by: codex <[email protected]>
2026-04-01 16:26:52 +00:00
Julius Marmingeandcodex 556a195c9d [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderService.ts (#1639)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:38 +00:00
Julius Marmingeandcodex 80b282ece7 [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderRegistry.ts (#1638)
Co-authored-by: codex <[email protected]>
2026-04-01 16:19:36 +00:00
Julius Marmingeandcodex d15075b32d [codex] migrate Effect.fn in apps/server/src/provider/Layers/EventNdjsonLogger.ts (#1636)
Co-authored-by: codex <[email protected]>
2026-04-01 16:14:55 +00:00
Julius Marmingeandcodex 9f6686a13d [codex] migrate Effect.fn in apps/server/src/persistence/Layers/Sqlite.ts (#1631)
Co-authored-by: codex <[email protected]>
2026-04-01 16:14:26 +00:00
Julius Marmingeandcodex c6ff7c0d5b [codex] migrate Effect.fn in apps/server/src/provider/makeManagedServerProvider.ts (#1640)
Co-authored-by: codex <[email protected]>
2026-04-01 16:03:08 +00:00
Julius Marmingeandcodex a9e5a84c03 [codex] migrate Effect.fn in apps/server/src/provider/Layers/ProviderAdapterRegistry.ts (#1637)
Co-authored-by: codex <[email protected]>
2026-04-01 08:58:04 -07:00
Julius Marmingeandcodex 67ca528fea [codex] migrate Effect.fn in apps/server/src/provider/Layers/ClaudeProvider.ts (#1634)
Co-authored-by: codex <[email protected]>
2026-04-01 15:57:31 +00:00
Julius Marmingeandcodex 6d9b21c5d0 [codex] migrate Effect.fn in apps/server/src/provider/Layers/CodexProvider.ts (#1635)
Co-authored-by: codex <[email protected]>
2026-04-01 08:56:04 -07:00
Julius Marmingeandcodex ddffdfc095 [codex] migrate Effect.fn in apps/server/src/telemetry/Layers/AnalyticsService.ts (#1642)
Co-authored-by: codex <[email protected]>
2026-04-01 08:53:55 -07:00
Julius Marmingeandcodex a58290ed79 [codex] migrate Effect.fn in apps/server/src/git/Layers/CodexTextGeneration.ts (#1624)
Co-authored-by: codex <[email protected]>
2026-04-01 15:53:25 +00:00
Julius Marmingeandcodex 3488ca3570 [codex] migrate Effect.fn in apps/server/src/persistence/Migrations.ts (#1632)
Co-authored-by: codex <[email protected]>
2026-04-01 08:44:49 -07:00
Julius Marmingeandcodex c542ce3369 [codex] migrate Effect.fn in apps/server/src/git/Layers/ClaudeTextGeneration.ts (#1625)
Co-authored-by: codex <[email protected]>
2026-04-01 15:44:38 +00:00
Julius Marmingeandcodex 15f0be848d [codex] migrate Effect.fn in apps/server/src/checkpointing/Layers/CheckpointStore.ts (#1623)
Co-authored-by: codex <[email protected]>
2026-04-01 08:39:23 -07:00
Julius Marmingeandcodex 1c3fa67374 [codex] migrate Effect.fn in apps/server/src/checkpointing/Layers/CheckpointDiffQuery.ts (#1622)
Co-authored-by: codex <[email protected]>
2026-04-01 08:35:54 -07:00
Lars Nieuwenhuis 0ac59d569d Feat: Added Trae IDE support for opening current working directory (#1656) 2026-04-01 15:19:12 +00:00
d8aa2f85df chore: effect rpc and layer based startup (#929)
Co-authored-by: codex <[email protected]>
Co-authored-by: Cursor Agent <[email protected]>
2026-03-31 23:58:35 -07:00
Utkarsh Patil 64d6938cf4 fix(web): consume plans on new-thread implementation (#1203) 2026-03-31 23:48:39 -07:00
0a88719a3a Improve Linux desktop identity packaged builds (#1201)
Co-authored-by: Copilot Autofix powered by AI <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-03-31 20:07:51 -07:00
shivam 0bc94bc24e fixing the input ui at certain endpoints causing the button to overflow. (#1574) 2026-03-31 18:40:14 -07:00
EDM115andJulius Marminge 19eb9e7227 fix(server): parse git branches correctly when column.ui is enabled (#1529)
Co-authored-by: Julius Marminge <[email protected]>
2026-03-31 18:02:09 -07:00
Julius Marminge aa5521dcfb Map fatal Codex stderr to runtime errors (#1615) 2026-03-31 15:10:16 -07:00
303 changed files with 16503 additions and 9149 deletions

No files matched your search

+2 -2
View File
@@ -1,13 +1,13 @@
# Scripts
- `bun run dev` — Starts contracts, server, and web in workspace dev mode.
- `bun run dev` — Starts contracts, server, and web in `turbo watch` mode.
- `bun run dev:server` — Starts just the WebSocket server (uses Bun TypeScript execution).
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --base-dir ~/.t3-2`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds workspace packages and apps through Vite+ task running.
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
- `bun run test` — Runs workspace tests.
- `bun run dist:desktop:artifact -- --platform <mac|linux|win> --target <target> --arch <arch>` — Builds a desktop artifact for a specific platform/target/arch.
+5 -3
View File
@@ -24,11 +24,13 @@ jobs:
with:
node-version-file: package.json
- name: Cache Bun
- name: Cache Bun and Turbo
uses: actions/cache@v5
with:
path: ~/.bun/install/cache
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}
path: |
~/.bun/install/cache
.turbo
key: ${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-${{ hashFiles('turbo.json') }}
restore-keys: |
${{ runner.os }}-bun-${{ hashFiles('bun.lock') }}-
+1
View File
@@ -21,3 +21,4 @@ apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
artifacts/
+15
View File
@@ -0,0 +1,15 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts",
"apps/web/public/mockServiceWorker.js"
],
"sortPackageJson": {}
}
+22
View File
@@ -0,0 +1,22 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"ignorePatterns": [
"dist",
"dist-electron",
"node_modules",
"bun.lock",
"*.tsbuildinfo",
"**/routeTree.gen.ts"
],
"plugins": ["eslint", "oxc", "react", "unicorn", "typescript"],
"categories": {
"correctness": "warn",
"suspicious": "warn",
"perf": "warn"
},
"rules": {
"react-in-jsx-scope": "off",
"eslint/no-shadow": "off",
"eslint/no-await-in-loop": "off"
}
}
+89
View File
@@ -0,0 +1,89 @@
# Replace React Query With AtomRpc + Atom State
## Summary
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
- Keep Zustand for orchestration read model and UI state.
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
## Target Architecture
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
- Add `rpc/invalidation.ts` with explicit scoped invalidation keys: `git:${cwd}`, `project:${cwd}`, `checkpoint:${threadId}`, `server-config`.
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
## Phase 1: Infrastructure First
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
2. Build the AtomRpc client on top of that layer.
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
5. Land this as a no-behavior-change PR.
## Phase 2: Replace `wsNativeApi`-Owned Push State
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
## Phase 3: Replace React Query Domain By Domain
1. Replace [gitReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/gitReactQuery.ts) first.
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
6. Defer the desktop updater until the last phase.
## Phase 4: Move Root Invalidation Off `queryClient`
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
2. Keep Zustand orchestration/event application unchanged.
3. Map current effects exactly:
- git or checkpoint-affecting orchestration events touch `checkpoint:${threadId}`
- file creation/deletion/restoration touches `project:${cwd}`
- config-affecting server events touch `server-config`
## Phase 5: Remove Imperative `NativeApi` Usage
1. Create narrow modules instead of a replacement mega-facade:
- `rpc/orchestrationActions.ts`
- `rpc/terminalActions.ts`
- `rpc/gitActions.ts`
- `rpc/projectActions.ts`
- `platform/desktopBridge.ts`
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
## Phase 6: Remove React Query Completely
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
4. Delete the old query-option tests.
## Public Interfaces And Types
- Preserve the current server-state hook names during the transition.
- Add permanent domain hooks: `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, `useProjectSearchEntries`, `useCheckpointDiff`, `useDesktopUpdateState`.
- Do not expose raw AtomRpc clients to components.
- Do not add Suspense as part of this migration.
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
## Test Plan
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
- Acceptance scenarios:
- welcome still bootstraps snapshot and navigation
- keybindings toast still responds to config stream updates
- git status/branches refresh after checkout/pull/worktree actions
- PR resolve dialog keeps cached result while typing
- `@` path search refreshes after file mutations and orchestration events
- diff panel refreshes when checkpoints arrive
- desktop updater still reflects push events and button actions
## Assumptions And Defaults
- Zustand stays in scope; only `react-query` is being removed.
- `desktopBridge` remains the only non-RPC boundary.
- The migration lands as 5-6 small PRs, each green independently.
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
+4
View File
@@ -45,6 +45,10 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
## Performance benchmarks
See [docs/perf-benchmarks.md](./docs/perf-benchmarks.md) for the local perf harness, seeded scenarios, artifact format, and the commands for automated and manual benchmark runs.
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+5 -4
View File
@@ -5,12 +5,12 @@
"main": "dist-electron/main.js",
"scripts": {
"dev": "bun run --parallel dev:bundle dev:electron",
"dev:bundle": "vp pack --watch",
"dev:bundle": "tsdown --watch",
"dev:electron": "bun run scripts/dev-electron.mjs",
"build": "vp pack",
"build": "tsdown",
"start": "bun run scripts/start-electron.mjs",
"typecheck": "tsc --noEmit",
"test": "vp test run --passWithNoTests",
"test": "vitest run --passWithNoTests",
"smoke-test": "node scripts/smoke-test.mjs"
},
"dependencies": {
@@ -22,8 +22,9 @@
"@t3tools/contracts": "workspace:*",
"@t3tools/shared": "workspace:*",
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vite-plus": "catalog:"
"vitest": "catalog:"
},
"productName": "T3 Code (Alpha)"
}
+2 -2
View File
@@ -10,11 +10,11 @@ const devServerUrl = `http://localhost:${port}`;
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/index.mjs",
"../server/dist/bin.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
+1 -1
View File
@@ -1,5 +1,5 @@
import type { BrowserWindow } from "electron";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import { beforeEach, describe, expect, it, vi } from "vitest";
const { showMessageBoxMock } = vi.hoisted(() => ({
showMessageBoxMock: vi.fn(),
+15 -2
View File
@@ -66,6 +66,8 @@ const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
const APP_DISPLAY_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const APP_USER_MODEL_ID = "com.t3tools.t3code";
const LINUX_DESKTOP_ENTRY_NAME = isDevelopment ? "t3code-dev.desktop" : "t3code.desktop";
const LINUX_WM_CLASS = isDevelopment ? "t3code-dev" : "t3code";
const USER_DATA_DIR_NAME = isDevelopment ? "t3code-dev" : "t3code";
const LEGACY_USER_DATA_DIR_NAME = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const COMMIT_HASH_PATTERN = /^[0-9a-f]{7,40}$/i;
@@ -80,6 +82,9 @@ const DESKTOP_UPDATE_CHANNEL = "latest";
const DESKTOP_UPDATE_ALLOW_PRERELEASE = false;
type DesktopUpdateErrorContext = DesktopUpdateState["errorContext"];
type LinuxDesktopNamedApp = Electron.App & {
setDesktopName?: (desktopName: string) => void;
};
let mainWindow: BrowserWindow | null = null;
let backendProcess: ChildProcess.ChildProcess | null = null;
@@ -99,7 +104,7 @@ let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
runningUnderArm64Translation: app.runningUnderARM64Translation,
runningUnderArm64Translation: app.runningUnderARM64Translation === true,
});
const initialUpdateState = (): DesktopUpdateState =>
createInitialDesktopUpdateState(app.getVersion(), desktopRuntimeInfo);
@@ -263,6 +268,10 @@ function captureBackendOutput(child: ChildProcess.ChildProcess): void {
initializePackagedLogging();
if (process.platform === "linux") {
app.commandLine.appendSwitch("class", LINUX_WM_CLASS);
}
function getDestructiveMenuIcon(): Electron.NativeImage | undefined {
if (process.platform !== "darwin") return undefined;
if (destructiveMenuIconCache !== undefined) {
@@ -390,7 +399,7 @@ function resolveAboutCommitHash(): string | null {
}
function resolveBackendEntry(): string {
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs");
}
function resolveBackendCwd(): string {
@@ -715,6 +724,10 @@ function configureAppIdentity(): void {
app.setAppUserModelId(APP_USER_MODEL_ID);
}
if (process.platform === "linux") {
(app as LinuxDesktopNamedApp).setDesktopName?.(LINUX_DESKTOP_ENTRY_NAME);
}
if (process.platform === "darwin" && app.dock) {
const iconPath = resolveIconPath("png");
if (iconPath) {
+1 -1
View File
@@ -3,7 +3,7 @@ import os from "node:os";
import path from "node:path";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it } from "vitest";
const tempRoots: string[] = [];
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { isArm64HostRunningIntelBuild, resolveDesktopRuntimeInfo } from "./runtimeArch";
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
import { syncShellEnvironment } from "./syncShellEnvironment";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
createInitialDesktopUpdateState,
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import type { DesktopUpdateState } from "@t3tools/contracts";
import {
+1 -2
View File
@@ -5,6 +5,5 @@
"types": ["node", "electron"],
"lib": ["ES2023", "DOM", "esnext.disposable"]
},
"include": ["src", "vite.config.ts", "../../packages/contracts/src", "../../packages/shared/src"],
"exclude": ["../../packages/contracts/src/**/*.test.ts", "../../packages/shared/src/**/*.test.ts"]
"include": ["src", "tsdown.config.ts"]
}
+21
View File
@@ -0,0 +1,21 @@
import { defineConfig } from "tsdown";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig([
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
entry: ["src/preload.ts"],
},
]);
+24
View File
@@ -0,0 +1,24 @@
{
"$schema": "https://turbo.build/schema.json",
"extends": ["//"],
"tasks": {
"build": {
"dependsOn": ["^build"],
"outputs": ["dist-electron/**"],
},
"dev": {
"dependsOn": ["t3#build"],
"persistent": true,
},
"start": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"persistent": true,
},
"smoke-test": {
"dependsOn": ["build", "@t3tools/web#build", "t3#build"],
"cache": false,
"outputs": [],
},
},
}
-42
View File
@@ -1,42 +0,0 @@
import * as path from "node:path";
import { defineConfig } from "vite-plus";
const shared = {
format: "cjs" as const,
outDir: "dist-electron",
sourcemap: true,
outExtensions: () => ({ js: ".js" }),
};
export default defineConfig({
resolve: {
tsconfigPaths: true,
alias: [
{
find: /^@t3tools\/contracts$/,
replacement: path.resolve(import.meta.dirname, "../../packages/contracts/src/index.ts"),
},
{
find: /^@t3tools\/contracts\/settings$/,
replacement: path.resolve(import.meta.dirname, "../../packages/contracts/src/settings.ts"),
},
{
find: /^@t3tools\/shared\/(.*)$/,
replacement: path.resolve(import.meta.dirname, "../../packages/shared/src/$1.ts"),
},
],
},
pack: [
{
...shared,
entry: ["src/main.ts"],
clean: true,
noExternal: (id) => id.startsWith("@t3tools/"),
},
{
...shared,
entry: ["src/preload.ts"],
},
],
});
@@ -69,6 +69,7 @@ import {
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { WorkspaceEntriesLive } from "../src/workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../src/workspace/Layers/WorkspacePaths.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -114,19 +115,19 @@ function waitFor<A, E>(
predicate: (value: A) => boolean,
description: string,
timeoutMs?: number,
): Effect.Effect<A>;
): Effect.Effect<A, never>;
function waitFor<A, B extends A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => value is B,
description: string,
timeoutMs?: number,
): Effect.Effect<B>;
): Effect.Effect<B, never>;
function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
): Effect.Effect<A> {
timeoutMs = 40_000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
const maxRetries = Math.max(0, Math.floor(timeoutMs / retryIntervalMs));
@@ -175,11 +176,11 @@ export interface OrchestrationIntegrationHarness {
threadId: string,
predicate: (thread: OrchestrationThread) => boolean,
timeoutMs?: number,
) => Effect.Effect<OrchestrationThread>;
) => Effect.Effect<OrchestrationThread, never>;
readonly waitForDomainEvent: (
predicate: (event: OrchestrationEvent) => boolean,
timeoutMs?: number,
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>>;
) => Effect.Effect<ReadonlyArray<OrchestrationEvent>, never>;
readonly waitForPendingApproval: (
requestId: string,
predicate: (row: {
@@ -188,22 +189,25 @@ export interface OrchestrationIntegrationHarness {
readonly resolvedAt: string | null;
}) => boolean,
timeoutMs?: number,
) => Effect.Effect<{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
}>;
) => Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
readonly waitForReceipt: {
(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt>;
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt>;
): Effect.Effect<Receipt, never>;
};
readonly dispose: Effect.Effect<void>;
readonly dispose: Effect.Effect<void, never>;
}
interface MakeOrchestrationIntegrationHarnessOptions {
@@ -317,10 +321,12 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(
WorkspaceEntriesLive.pipe(
Layer.provide(WorkspacePathsLive),
Layer.provideMerge(gitCoreLayer),
Layer.provide(NodeServices.layer),
),
),
Layer.provideMerge(WorkspacePathsLive),
);
const orchestrationReactorLayer = OrchestrationReactorLive.pipe(
Layer.provideMerge(runtimeIngestionLayer),
@@ -388,7 +394,7 @@ export const makeOrchestrationIntegrationHarness = (
(thread): thread is OrchestrationThread => thread !== null && predicate(thread),
`projected thread '${threadId}'`,
timeoutMs,
) as Effect.Effect<OrchestrationThread>;
) as Effect.Effect<OrchestrationThread, never>;
const waitForDomainEvent: OrchestrationIntegrationHarness["waitForDomainEvent"] = (
predicate,
@@ -432,20 +438,23 @@ export const makeOrchestrationIntegrationHarness = (
} => row !== null && predicate(row),
`pending approval '${requestId}'`,
timeoutMs,
) as Effect.Effect<{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
}>;
) as Effect.Effect<
{
readonly status: "pending" | "resolved";
readonly decision: "accept" | "acceptForSession" | "decline" | "cancel" | null;
readonly resolvedAt: string | null;
},
never
>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
): Effect.Effect<OrchestrationRuntimeReceipt>;
): Effect.Effect<OrchestrationRuntimeReceipt, never>;
function waitForReceipt<Receipt extends OrchestrationRuntimeReceipt>(
predicate: (receipt: OrchestrationRuntimeReceipt) => receipt is Receipt,
timeoutMs?: number,
): Effect.Effect<Receipt>;
): Effect.Effect<Receipt, never>;
function waitForReceipt(
predicate: (receipt: OrchestrationRuntimeReceipt) => boolean,
timeoutMs?: number,
@@ -30,7 +30,7 @@ export interface TestTurnResponse {
readonly mutateWorkspace?: (input: {
readonly cwd: string;
readonly turnCount: number;
}) => Effect.Effect<void>;
}) => Effect.Effect<void, never>;
}
export type FixtureProviderRuntimeEvent = {
@@ -183,7 +183,9 @@ export interface TestProviderAdapterHarness {
threadId: ThreadId,
response: TestTurnResponse,
) => Effect.Effect<void, ProviderAdapterSessionNotFoundError>;
readonly queueTurnResponseForNextSession: (response: TestTurnResponse) => Effect.Effect<void>;
readonly queueTurnResponseForNextSession: (
response: TestTurnResponse,
) => Effect.Effect<void, never>;
readonly getStartCount: () => number;
readonly getRollbackCalls: (threadId: ThreadId) => ReadonlyArray<number>;
readonly getInterruptCalls: (threadId: ThreadId) => ReadonlyArray<TurnId | undefined>;
@@ -335,7 +337,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
}
if (response.mutateWorkspace && state.session.cwd) {
yield* response.mutateWorkspace({ cwd: state.session.cwd, turnCount });
yield* response.mutateWorkspace({ cwd: state.session.cwd!, turnCount });
}
const userItem = {
@@ -486,7 +488,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
readThread,
rollbackThread,
stopAll,
streamEvents: Stream.fromQueue(runtimeEvents),
get streamEvents() {
return Stream.fromQueue(runtimeEvents);
},
};
const queueTurnResponse = (
@@ -503,7 +507,9 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
),
);
const queueTurnResponseForNextSession = (response: TestTurnResponse): Effect.Effect<void> =>
const queueTurnResponseForNextSession = (
response: TestTurnResponse,
): Effect.Effect<void, never> =>
Effect.sync(() => {
queuedResponsesForNextSession.push(response);
});
@@ -57,8 +57,8 @@ function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 3000,
): Effect.Effect<A> {
timeoutMs = 10_000,
): Effect.Effect<A, never> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
@@ -226,7 +226,9 @@ it.live("runs a single turn end-to-end and persists checkpoint state in sqlite +
THREAD_ID,
(entry) =>
entry.session?.status === "ready" &&
entry.messages.some((message) => message.role === "assistant" && !message.streaming) &&
entry.messages.some(
(message) => message.role === "assistant" && message.streaming === false,
) &&
entry.checkpoints.length === 1,
);
assert.equal(thread.checkpoints[0]?.status, "ready");
@@ -307,7 +309,9 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
(entry) =>
entry.session?.status === "ready" &&
entry.session.providerName === "codex" &&
entry.messages.some((message) => message.role === "assistant" && !message.streaming),
entry.messages.some(
(message) => message.role === "assistant" && message.streaming === false,
),
180_000,
);
assert.equal(firstThread.session?.threadId, "thread-1");
@@ -0,0 +1,53 @@
import { readFile, rm } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { PERF_CATALOG_IDS, getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
import { seedPerfState } from "./seedPerfState.ts";
describe("seedPerfState", () => {
const runParentDirsToCleanup: string[] = [];
afterEach(async () => {
await Promise.all(
runParentDirsToCleanup
.splice(0)
.map((runParentDir) => rm(runParentDir, { recursive: true, force: true })),
);
});
it("seeds large thread fixtures through the real event store and projection pipeline", async () => {
const seeded = await seedPerfState("large_threads");
runParentDirsToCleanup.push(seeded.runParentDir);
const scenario = getPerfSeedScenario("large_threads");
expect(seeded.snapshot.projects).toHaveLength(5);
expect(seeded.snapshot.threads).toHaveLength(30);
expect(seeded.baseDir).toBe(join(seeded.runParentDir, "base"));
expect(new Set(seeded.snapshot.threads.map((thread) => thread.projectId)).size).toBe(5);
const heavyThread = seeded.snapshot.threads.find(
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
);
const heavyThreadScenario = scenario.threads.find(
(thread) => thread.id === PERF_CATALOG_IDS.largeThreads.heavyAThreadId,
);
expect(heavyThread?.messages).toHaveLength(2_000);
expect(heavyThreadScenario?.turnCount ?? Number.POSITIVE_INFINITY).toBeLessThan(100);
expect((heavyThread?.activities.length ?? 0) > 0).toBe(true);
expect((heavyThread?.proposedPlans.length ?? 0) > 0).toBe(true);
expect((heavyThread?.checkpoints.length ?? 0) >= 20).toBe(true);
expect((heavyThread?.checkpoints[0]?.files.length ?? 0) >= 12).toBe(true);
});
it("enables assistant streaming in the burst base seed for websocket perf runs", async () => {
const seeded = await seedPerfState("burst_base");
runParentDirsToCleanup.push(seeded.runParentDir);
const rawSettings = await readFile(join(seeded.baseDir, "userdata/settings.json"), "utf8");
expect(JSON.parse(rawSettings)).toMatchObject({
enableAssistantStreaming: true,
});
});
});
@@ -0,0 +1,589 @@
import { execFileSync } from "node:child_process";
import { cp, mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import {
CheckpointRef,
CommandId,
EventId,
type OrchestrationEvent,
type OrchestrationReadModel,
type ProjectId,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime } from "effect";
import {
buildPerfAssistantMessageCountPlan,
getPerfSeedScenario,
perfEventId,
perfMessageIdForThread,
perfTurnIdForThread,
type PerfProjectScenario,
type PerfSeedScenario,
type PerfSeedScenarioId,
type PerfSeedThreadScenario,
} from "@t3tools/shared/perf/scenarioCatalog";
import { ServerConfig } from "../../src/config.ts";
import { OrchestrationProjectionPipelineLive } from "../../src/orchestration/Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "../../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
import { OrchestrationProjectionPipeline } from "../../src/orchestration/Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../../src/orchestration/Services/ProjectionSnapshotQuery.ts";
import { OrchestrationEventStoreLive } from "../../src/persistence/Layers/OrchestrationEventStore.ts";
import { layerConfig as SqlitePersistenceLayerLive } from "../../src/persistence/Layers/Sqlite.ts";
import { OrchestrationEventStore } from "../../src/persistence/Services/OrchestrationEventStore.ts";
import { ServerSettingsService, ServerSettingsLive } from "../../src/serverSettings.ts";
export interface PerfSeededState {
readonly scenarioId: PerfSeedScenarioId;
readonly runParentDir: string;
readonly baseDir: string;
readonly workspaceRoot: string;
readonly snapshot: OrchestrationReadModel;
}
const templateDirPromises = new Map<PerfSeedScenarioId, Promise<string>>();
function runGit(cwd: string, args: ReadonlyArray<string>) {
execFileSync("git", args, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
});
}
async function initializeGitWorkspace(workspaceRoot: string): Promise<void> {
await mkdir(workspaceRoot, { recursive: true });
runGit(workspaceRoot, ["init", "--initial-branch=main"]);
runGit(workspaceRoot, ["config", "user.email", "[email protected]"]);
runGit(workspaceRoot, ["config", "user.name", "Perf Fixture"]);
await writeFile(
join(workspaceRoot, "README.md"),
"# Performance Workspace\n\nSeeded fixture state for local perf regression tests.\n",
"utf8",
);
runGit(workspaceRoot, ["add", "."]);
runGit(workspaceRoot, ["commit", "-m", "Initial perf workspace"]);
}
function plusMs(baseTimeMs: number, offsetMs: number): string {
return new Date(baseTimeMs + offsetMs).toISOString();
}
function makeCommandId(prefix: string, threadId: string, turnIndex: number): CommandId {
return CommandId.makeUnsafe(`${prefix}:${threadId}:${turnIndex.toString().padStart(4, "0")}`);
}
function buildProjectEvent(
project: PerfProjectScenario,
workspaceRoot: string,
createdAt: string,
): Omit<OrchestrationEvent, "sequence"> {
return {
type: "project.created",
eventId: EventId.makeUnsafe(`perf-project-created:${String(project.id)}`),
aggregateKind: "project",
aggregateId: project.id,
occurredAt: createdAt,
commandId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
causationEventId: null,
correlationId: CommandId.makeUnsafe(`perf-project-create:${String(project.id)}`),
metadata: {},
payload: {
projectId: project.id,
title: project.title,
workspaceRoot,
defaultModelSelection: project.defaultModelSelection,
scripts: [],
createdAt,
updatedAt: createdAt,
},
};
}
function buildThreadCreatedEvent(
thread: PerfSeedThreadScenario,
project: PerfProjectScenario,
createdAt: string,
): Omit<OrchestrationEvent, "sequence"> {
return {
type: "thread.created",
eventId: EventId.makeUnsafe(`perf-thread-created:${String(thread.id)}`),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: createdAt,
commandId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
causationEventId: null,
correlationId: CommandId.makeUnsafe(`perf-thread-create:${String(thread.id)}`),
metadata: {},
payload: {
threadId: thread.id,
projectId: thread.projectId,
title: thread.title,
modelSelection: project.defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt,
updatedAt: createdAt,
},
};
}
function buildUserMessageText(thread: PerfSeedThreadScenario, turnIndex: number): string {
const base = `${thread.title} request ${turnIndex}: review the current workspace state and explain the next change.`;
if (turnIndex % 11 === 0) {
return `${base}\n\nFocus on virtualization, batching, and cross-thread navigation latency.`;
}
if (turnIndex % 7 === 0) {
return `${base}\n\nSummarize CPU-sensitive paths and any websocket burst handling concerns.`;
}
return base;
}
function buildAssistantMessageText(
thread: PerfSeedThreadScenario,
turnIndex: number,
assistantMessageIndex: number,
assistantMessageCount: number,
): string {
const phaseLabel =
assistantMessageIndex === 1
? "Opening"
: assistantMessageIndex === assistantMessageCount
? "Settled"
: assistantMessageIndex % 5 === 0
? "Checkpoint"
: "Loop";
const focusTopics = [
"checked the visible timeline window and sidebar ordering",
"trimmed redundant projection work before the next render pass",
"reviewed websocket fan-out and message grouping pressure",
"verified checkpoint rows stay bounded while hidden threads move",
"kept the active route stable while background threads kept streaming",
];
const topic = focusTopics[(turnIndex + assistantMessageIndex) % focusTopics.length]!;
const threadBias =
thread.category === "heavy"
? "The thread is still dense enough to stress virtualization."
: thread.category === "burst"
? "This pass is still carrying live burst pressure."
: "Background churn is staying active without stealing focus.";
return `${thread.title} ${phaseLabel.toLowerCase()} ${assistantMessageIndex}/${assistantMessageCount} for turn ${turnIndex}: ${topic}. ${threadBias}`;
}
function buildProposedPlanMarkdown(thread: PerfSeedThreadScenario, turnIndex: number): string {
return [
`## ${thread.title} plan ${turnIndex}`,
"",
"1. Measure the current thread switch path against a stable local budget.",
"2. Reduce avoidable render churn in the visible timeline window.",
"3. Validate websocket burst handling with real runtime events before tightening thresholds.",
].join("\n");
}
function buildCheckpointFiles(
thread: PerfSeedThreadScenario,
threadOrdinal: number,
turnIndex: number,
): ReadonlyArray<{
readonly path: string;
readonly kind: string;
readonly additions: number;
readonly deletions: number;
}> {
const nestedPathTemplates = [
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "TimelineVirtualizer.tsx"],
["apps", "web", "src", "components", `thread-${threadOrdinal + 1}`, "ThreadSummaryPane.tsx"],
["apps", "web", "src", "hooks", `thread-${threadOrdinal + 1}`, "useThreadViewport.ts"],
["apps", "web", "src", "stores", `thread-${threadOrdinal + 1}`, "timelineStore.ts"],
[
"apps",
"server",
"src",
"orchestration",
`thread-${threadOrdinal + 1}`,
"projectionPipeline.ts",
],
["apps", "server", "src", "provider", `thread-${threadOrdinal + 1}`, "runtimeBuffer.ts"],
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "fixtureBuilders.ts"],
["packages", "shared", "src", "perf", `thread-${threadOrdinal + 1}`, "scenarioCatalog.ts"],
["packages", "contracts", "src", "orchestration", `thread-${threadOrdinal + 1}`, "schemas.ts"],
["docs", "perf", `thread-${threadOrdinal + 1}`, "notes", "regression-findings.md"],
["scripts", "perf", `thread-${threadOrdinal + 1}`, "capture-profile.ts"],
["test", "perf", "fixtures", `thread-${threadOrdinal + 1}`, "workspace-state.json"],
] as const;
const fileCount = thread.category === "heavy" ? 12 + (turnIndex % 7) : 7 + (turnIndex % 4);
return Array.from({ length: fileCount }, (_, fileIndex) => {
const template = nestedPathTemplates[fileIndex % nestedPathTemplates.length]!;
const variant = Math.floor(fileIndex / nestedPathTemplates.length);
const baseSegments = [...template];
const fileName = baseSegments.pop()!;
const variantFileName =
variant === 0
? fileName
: fileName.replace(/(\.[^.]*)$/, `-${(variant + 1).toString().padStart(2, "0")}$1`);
const path = [...baseSegments, variantFileName].join("/");
const kind =
fileIndex % 9 === 0
? "deleted"
: fileIndex % 5 === 0
? "added"
: fileIndex % 4 === 0
? "renamed"
: "modified";
return {
path,
kind,
additions: kind === "deleted" ? 0 : 4 + ((turnIndex + fileIndex) % 11),
deletions: kind === "added" ? 0 : 1 + ((threadOrdinal + fileIndex + turnIndex) % 6),
};
});
}
function buildThreadTurnEvents(
thread: PerfSeedThreadScenario,
threadOrdinal: number,
projectStartMs: number,
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
const threadStartMs = projectStartMs + threadOrdinal * 60_000;
const assistantMessageCountPlan = buildPerfAssistantMessageCountPlan(thread);
for (let turnIndex = 1; turnIndex <= thread.turnCount; turnIndex += 1) {
const turnId = perfTurnIdForThread(thread, turnIndex);
const userMessageId = perfMessageIdForThread(thread, "user", turnIndex, 1);
const assistantMessageCount = assistantMessageCountPlan[turnIndex - 1] ?? 1;
const turnBaseMs = threadStartMs + turnIndex * 1_000;
const userOccurredAt = plusMs(turnBaseMs, 0);
const activityAssistantIndex =
thread.activityStride !== null && turnIndex % thread.activityStride === 0
? Math.max(2, Math.floor(assistantMessageCount * 0.35))
: null;
const planAssistantIndex =
thread.planStride !== null && turnIndex % thread.planStride === 0
? Math.max(2, Math.floor(assistantMessageCount * 0.7))
: null;
let lastAssistantMessageId = perfMessageIdForThread(
thread,
"assistant",
turnIndex,
assistantMessageCount,
);
let turnEventOffset = 0;
const nextEventId = (prefix: string) =>
perfEventId(prefix, thread.id, turnIndex * 100 + turnEventOffset++);
events.push({
type: "thread.message-sent",
eventId: nextEventId("perf-user-message"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: userOccurredAt,
commandId: makeCommandId("perf-user-message", String(thread.id), turnIndex),
causationEventId: null,
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
metadata: {},
payload: {
threadId: thread.id,
messageId: userMessageId,
role: "user",
text: buildUserMessageText(thread, turnIndex),
attachments: [],
turnId,
streaming: false,
createdAt: userOccurredAt,
updatedAt: userOccurredAt,
},
});
for (
let assistantMessageIndex = 1;
assistantMessageIndex <= assistantMessageCount;
assistantMessageIndex += 1
) {
const assistantOccurredAt = plusMs(turnBaseMs, 120 + assistantMessageIndex * 40);
const assistantMessageId = perfMessageIdForThread(
thread,
"assistant",
turnIndex,
assistantMessageIndex,
);
lastAssistantMessageId = assistantMessageId;
events.push({
type: "thread.message-sent",
eventId: nextEventId("perf-assistant-message"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: assistantOccurredAt,
commandId: makeCommandId("perf-assistant-message", String(thread.id), turnIndex),
causationEventId: null,
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
metadata: {},
payload: {
threadId: thread.id,
messageId: assistantMessageId,
role: "assistant",
text: buildAssistantMessageText(
thread,
turnIndex,
assistantMessageIndex,
assistantMessageCount,
),
attachments: [],
turnId,
streaming: false,
createdAt: assistantOccurredAt,
updatedAt: assistantOccurredAt,
},
});
if (activityAssistantIndex === assistantMessageIndex) {
const activityOccurredAt = plusMs(turnBaseMs, 132 + assistantMessageIndex * 40);
events.push({
type: "thread.activity-appended",
eventId: nextEventId("perf-activity"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: activityOccurredAt,
commandId: makeCommandId("perf-activity", String(thread.id), turnIndex),
causationEventId: null,
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
metadata: {},
payload: {
threadId: thread.id,
activity: {
id: perfEventId("perf-activity-row", thread.id, turnIndex),
tone: "tool",
kind: "tool.completed",
summary: `Synthetic command batch ${turnIndex}.${assistantMessageIndex}`,
payload: {
command: "perf-simulated",
batch: turnIndex,
loop: assistantMessageIndex,
threadCategory: thread.category,
},
turnId,
createdAt: activityOccurredAt,
},
},
});
}
if (planAssistantIndex === assistantMessageIndex) {
const planOccurredAt = plusMs(turnBaseMs, 140 + assistantMessageIndex * 40);
events.push({
type: "thread.proposed-plan-upserted",
eventId: nextEventId("perf-plan"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: planOccurredAt,
commandId: makeCommandId("perf-plan", String(thread.id), turnIndex),
causationEventId: null,
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
metadata: {},
payload: {
threadId: thread.id,
proposedPlan: {
id: `perf-plan:${String(thread.id)}:${turnIndex.toString().padStart(4, "0")}`,
turnId,
planMarkdown: buildProposedPlanMarkdown(thread, turnIndex),
implementedAt: null,
implementationThreadId: null,
createdAt: planOccurredAt,
updatedAt: planOccurredAt,
},
},
});
}
}
if (thread.diffStride !== null && turnIndex % thread.diffStride === 0) {
const diffOccurredAt = plusMs(turnBaseMs, 180 + assistantMessageCount * 40);
events.push({
type: "thread.turn-diff-completed",
eventId: nextEventId("perf-diff"),
aggregateKind: "thread",
aggregateId: thread.id,
occurredAt: diffOccurredAt,
commandId: makeCommandId("perf-diff", String(thread.id), turnIndex),
causationEventId: null,
correlationId: makeCommandId("perf-turn", String(thread.id), turnIndex),
metadata: {},
payload: {
threadId: thread.id,
turnId,
checkpointTurnCount: turnIndex,
checkpointRef: CheckpointRef.makeUnsafe(
`refs/perf/${String(thread.id)}/${turnIndex.toString().padStart(4, "0")}`,
),
status: "ready",
files: buildCheckpointFiles(thread, threadOrdinal, turnIndex),
assistantMessageId: lastAssistantMessageId,
completedAt: diffOccurredAt,
},
});
}
}
return events;
}
function buildScenarioEvents(
scenario: PerfSeedScenario,
workspaceRootsByProjectId: ReadonlyMap<ProjectId, string>,
): ReadonlyArray<Omit<OrchestrationEvent, "sequence">> {
const projectStartMs = Date.parse("2026-03-01T12:00:00.000Z");
const threadsByProjectId = new Map<ProjectId, PerfSeedThreadScenario[]>();
for (const thread of scenario.threads) {
const existing = threadsByProjectId.get(thread.projectId) ?? [];
existing.push(thread);
threadsByProjectId.set(thread.projectId, existing);
}
let globalThreadOrdinal = 0;
const events: Array<Omit<OrchestrationEvent, "sequence">> = [];
for (const [projectOrdinal, project] of scenario.projects.entries()) {
const projectWorkspaceRoot = workspaceRootsByProjectId.get(project.id);
if (!projectWorkspaceRoot) {
throw new Error(`Missing workspace root for perf project '${String(project.id)}'.`);
}
const projectBaseMs = projectStartMs + projectOrdinal * 6 * 60_000;
const projectCreatedAt = plusMs(projectBaseMs, 0);
const projectThreads = threadsByProjectId.get(project.id) ?? [];
events.push(buildProjectEvent(project, projectWorkspaceRoot, projectCreatedAt));
for (const [threadOrdinalWithinProject, thread] of projectThreads.entries()) {
const threadCreatedAt = plusMs(projectBaseMs, threadOrdinalWithinProject * 45_000 + 50);
const threadEvents = buildThreadTurnEvents(thread, globalThreadOrdinal, projectBaseMs);
globalThreadOrdinal += 1;
events.push(buildThreadCreatedEvent(thread, project, threadCreatedAt), ...threadEvents);
}
}
return events;
}
async function createTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
const scenario = getPerfSeedScenario(scenarioId);
const baseDir = await mkdtemp(join(tmpdir(), `t3-perf-template-${scenarioId}-`));
const primaryProject = scenario.projects[0];
if (!primaryProject) {
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
}
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
const workspaceRootsByProjectId = new Map<ProjectId, string>(
scenario.projects.map((project) => [project.id, join(baseDir, project.workspaceDirectoryName)]),
);
await Promise.all(
scenario.projects.map((project) =>
initializeGitWorkspace(join(baseDir, project.workspaceDirectoryName)),
),
);
const seedLayer = Layer.empty.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(OrchestrationProjectionPipelineLive),
Layer.provideMerge(OrchestrationEventStoreLive),
Layer.provideMerge(ServerSettingsLive),
Layer.provideMerge(SqlitePersistenceLayerLive),
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(seedLayer);
const snapshot = await runtime.runPromise(
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const eventStore = yield* OrchestrationEventStore;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const snapshotQuery = yield* ProjectionSnapshotQuery;
yield* serverSettings.updateSettings({
enableAssistantStreaming: scenario.id === "burst_base",
});
for (const event of buildScenarioEvents(scenario, workspaceRootsByProjectId)) {
const storedEvent = yield* eventStore.append(event);
yield* projectionPipeline.projectEvent(storedEvent);
}
return yield* snapshotQuery.getSnapshot();
}),
);
const manifestPath = join(baseDir, "perf-seed-manifest.json");
await writeFile(
manifestPath,
`${JSON.stringify(
{
scenarioId,
workspaceRoot,
snapshotSequence: snapshot.snapshotSequence,
projectCount: snapshot.projects.length,
threadCount: snapshot.threads.length,
},
null,
2,
)}\n`,
"utf8",
);
await runtime.dispose();
return baseDir;
}
async function getTemplateDir(scenarioId: PerfSeedScenarioId): Promise<string> {
const existing = templateDirPromises.get(scenarioId);
if (existing) {
return existing;
}
const created = createTemplateDir(scenarioId);
templateDirPromises.set(scenarioId, created);
return created;
}
export async function seedPerfState(scenarioId: PerfSeedScenarioId): Promise<PerfSeededState> {
const scenario = getPerfSeedScenario(scenarioId);
const templateDir = await getTemplateDir(scenarioId);
const runParentDir = await mkdtemp(join(tmpdir(), `t3-perf-run-${scenarioId}-`));
const baseDir = join(runParentDir, "base");
await cp(templateDir, baseDir, { recursive: true, force: true });
const primaryProject = scenario.projects[0];
if (!primaryProject) {
throw new Error(`Perf scenario '${scenarioId}' has no projects.`);
}
const workspaceRoot = join(baseDir, primaryProject.workspaceDirectoryName);
const snapshotLayer = Layer.empty.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(ServerSettingsLive),
Layer.provideMerge(SqlitePersistenceLayerLive),
Layer.provideMerge(ServerConfig.layerTest(workspaceRoot, baseDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(snapshotLayer);
const snapshot = await runtime.runPromise(
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
return yield* snapshotQuery.getSnapshot();
}),
);
await runtime.dispose();
return {
scenarioId,
runParentDir,
baseDir,
workspaceRoot,
snapshot,
};
}
@@ -0,0 +1,920 @@
import { execFileSync } from "node:child_process";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { performance } from "node:perf_hooks";
import {
type ClientOrchestrationCommand,
CommandId,
MessageId,
type ModelSelection,
ORCHESTRATION_WS_METHODS,
type OrchestrationEvent,
type ProjectId,
type TerminalEvent,
ThreadId,
type ThreadId as ThreadIdType,
WS_METHODS,
} from "@t3tools/contracts";
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
import { afterEach, describe, expect, it } from "vitest";
import {
type ServerCommandLatencyMeasurement,
startServerPerfHarness,
summarizeCommandLatencyMeasurements,
summarizeRpcLatencySeries,
type ServerPerfHarness,
type ServerRpcLatencySeries,
} from "./serverPerfHarness.ts";
import type { PerfLatencySample } from "@t3tools/shared/perf/artifact";
const CONTROL_PLANE_SAMPLE_COUNT = 4;
const GIT_RPC_SAMPLE_COUNT = 6;
const STREAM_THREAD_COUNT = 5;
const SPAM_THREAD_COUNT = 8;
const TERMINAL_SESSION_COUNT = 3;
const TERMINAL_OUTPUT_LINE_COUNT = 260;
const TERMINAL_OUTPUT_SLEEP_SECONDS = 0.04;
const GIT_BRANCH_COUNT = 240;
const GIT_UNTRACKED_FILE_COUNT = 160;
const DEFAULT_WAIT_TIMEOUT_MS = 45_000;
interface SubscriptionCleanup {
readonly dispose: () => void;
}
interface EventWaiter<TValue, TResult> {
readonly description: string;
readonly select: (values: ReadonlyArray<TValue>) => TResult | null;
readonly resolve: (value: TResult) => void;
readonly reject: (error: Error) => void;
readonly timer: ReturnType<typeof setTimeout>;
}
class BufferedEventFeed<TValue> implements SubscriptionCleanup {
private readonly values: TValue[] = [];
private readonly waiters = new Set<EventWaiter<TValue, unknown>>();
push(value: TValue) {
this.values.push(value);
for (const waiter of this.waiters) {
const match = waiter.select(this.values);
if (match === null) {
continue;
}
clearTimeout(waiter.timer);
this.waiters.delete(waiter);
waiter.resolve(match);
}
}
waitFor<TResult>(
description: string,
select: (values: ReadonlyArray<TValue>) => TResult | null,
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
): Promise<TResult> {
const immediateMatch = select(this.values);
if (immediateMatch !== null) {
return Promise.resolve(immediateMatch);
}
return new Promise<TResult>((resolve, reject) => {
const waiter: EventWaiter<TValue, TResult> = {
description,
select,
resolve,
reject,
timer: setTimeout(() => {
this.waiters.delete(waiter as EventWaiter<TValue, unknown>);
reject(new Error(`Timed out waiting for ${description} after ${timeoutMs}ms.`));
}, timeoutMs),
};
this.waiters.add(waiter as EventWaiter<TValue, unknown>);
});
}
waitForEvent(
description: string,
predicate: (value: TValue) => boolean,
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
): Promise<TValue> {
return this.waitFor(description, (values) => values.find(predicate) ?? null, timeoutMs);
}
waitForCount(
description: string,
predicate: (value: TValue) => boolean,
count: number,
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
): Promise<ReadonlyArray<TValue>> {
return this.waitFor(
description,
(values) => {
const matches = values.filter(predicate);
return matches.length >= count ? matches.slice(0, count) : null;
},
timeoutMs,
);
}
waitForDistinct<TKey extends string | number>(
description: string,
predicate: (value: TValue) => boolean,
selectKey: (value: TValue) => TKey,
count: number,
timeoutMs = DEFAULT_WAIT_TIMEOUT_MS,
): Promise<ReadonlyArray<TValue>> {
return this.waitFor(
description,
(values) => {
const distinctMatches = new Map<TKey, TValue>();
for (const value of values) {
if (!predicate(value)) {
continue;
}
const key = selectKey(value);
if (!distinctMatches.has(key)) {
distinctMatches.set(key, value);
}
}
const matches = [...distinctMatches.values()];
return matches.length >= count ? matches : null;
},
timeoutMs,
);
}
dispose() {
for (const waiter of this.waiters) {
clearTimeout(waiter.timer);
waiter.reject(new Error(`Buffered feed disposed while waiting for ${waiter.description}.`));
}
this.waiters.clear();
}
}
function sleep(delayMs: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, delayMs));
}
function nowIso(): string {
return new Date().toISOString();
}
function runGit(cwd: string, args: ReadonlyArray<string>) {
execFileSync("git", args, {
cwd,
stdio: ["ignore", "pipe", "pipe"],
encoding: "utf8",
});
}
function makeControlThreadId(label: string): ThreadIdType {
return ThreadId.makeUnsafe(`perf-control-${label}-${crypto.randomUUID()}`);
}
function makeCommandId(label: string) {
return CommandId.makeUnsafe(`perf-command:${label}:${crypto.randomUUID()}`);
}
function makeMessageId(label: string) {
return MessageId.makeUnsafe(`perf-message:${label}:${crypto.randomUUID()}`);
}
async function dispatchCommand(harness: ServerPerfHarness, command: ClientOrchestrationCommand) {
return await harness.rpc.request((client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand](command),
);
}
async function measureCommandLatency(input: {
readonly harness: ServerPerfHarness;
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
readonly command: ClientOrchestrationCommand;
readonly expectedEventType: OrchestrationEvent["type"];
readonly loadProfile: string;
readonly timeoutMs?: number;
readonly metadata?: Record<string, unknown>;
}): Promise<ServerCommandLatencyMeasurement> {
const startedAt = nowIso();
const startedAtMs = performance.now();
const result = await dispatchCommand(input.harness, input.command);
const ackAtMs = performance.now();
const event = await input.orchestrationEvents.waitForEvent(
`${input.expectedEventType} for ${input.command.type}`,
(candidate) =>
candidate.type === input.expectedEventType &&
String(candidate.commandId) === String(input.command.commandId),
input.timeoutMs,
);
const eventAtMs = performance.now();
return {
commandType: input.command.type,
loadProfile: input.loadProfile,
startedAt,
dispatchToAckMs: ackAtMs - startedAtMs,
dispatchToEventMs: eventAtMs - startedAtMs,
ackToEventMs: eventAtMs - ackAtMs,
resultSequence: result.sequence,
eventSequence: event.sequence,
...(input.metadata ? { metadata: input.metadata } : {}),
};
}
async function createSupportThread(input: {
readonly harness: ServerPerfHarness;
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
readonly label: string;
}): Promise<ThreadIdType> {
const threadId = makeControlThreadId(`load-${input.label}`);
const command = {
type: "thread.create",
commandId: makeCommandId(`load-thread-create-${input.label}`),
threadId,
projectId: input.projectId,
title: `Perf Load ${input.label}`,
modelSelection: input.modelSelection,
interactionMode: "default",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: nowIso(),
} as const satisfies ClientOrchestrationCommand;
await dispatchCommand(input.harness, command);
await input.orchestrationEvents.waitForEvent(
`thread.created for load support thread ${input.label}`,
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
);
return threadId;
}
async function captureCreateArchiveSamples(input: {
readonly harness: ServerPerfHarness;
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
readonly loadProfile: string;
readonly sampleCount: number;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
}): Promise<ReadonlyArray<ServerCommandLatencyMeasurement>> {
const samples: ServerCommandLatencyMeasurement[] = [];
for (let sampleIndex = 0; sampleIndex < input.sampleCount; sampleIndex += 1) {
const threadId = makeControlThreadId(`${input.loadProfile}-${sampleIndex + 1}`);
const createCommand = {
type: "thread.create",
commandId: makeCommandId(`thread-create-${input.loadProfile}-${sampleIndex + 1}`),
threadId,
projectId: input.projectId,
title: `Perf ${input.loadProfile} ${sampleIndex + 1}`,
modelSelection: input.modelSelection,
interactionMode: "default",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: nowIso(),
} as const satisfies ClientOrchestrationCommand;
samples.push(
await measureCommandLatency({
harness: input.harness,
orchestrationEvents: input.orchestrationEvents,
command: createCommand,
expectedEventType: "thread.created",
loadProfile: input.loadProfile,
metadata: {
sampleIndex: sampleIndex + 1,
threadId,
},
}),
);
const archiveCommand = {
type: "thread.archive",
commandId: makeCommandId(`thread-archive-${input.loadProfile}-${sampleIndex + 1}`),
threadId,
} as const satisfies ClientOrchestrationCommand;
samples.push(
await measureCommandLatency({
harness: input.harness,
orchestrationEvents: input.orchestrationEvents,
command: archiveCommand,
expectedEventType: "thread.archived",
loadProfile: input.loadProfile,
metadata: {
sampleIndex: sampleIndex + 1,
threadId,
},
}),
);
}
return samples;
}
async function ensureStreamingThreads(input: {
readonly harness: ServerPerfHarness;
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
readonly count: number;
}): Promise<ReadonlyArray<ThreadIdType>> {
const threadIds: ThreadIdType[] = [
PERF_CATALOG_IDS.burstBase.burstThreadId,
PERF_CATALOG_IDS.burstBase.navigationThreadId,
PERF_CATALOG_IDS.burstBase.fillerThreadId,
];
while (threadIds.length < input.count) {
threadIds.push(
await createSupportThread({
harness: input.harness,
orchestrationEvents: input.orchestrationEvents,
projectId: input.projectId,
modelSelection: input.modelSelection,
label: `stream-${threadIds.length + 1}`,
}),
);
}
return threadIds;
}
async function startAssistantStreamingLoad(input: {
readonly harness: ServerPerfHarness;
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
readonly threadIds: ReadonlyArray<ThreadIdType>;
readonly label: string;
}): Promise<void> {
await Promise.all(
input.threadIds.map((threadId, index) =>
dispatchCommand(input.harness, {
type: "thread.turn.start",
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
threadId,
message: {
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
role: "user",
text: `Perf load ${input.label} ${index + 1}`,
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: nowIso(),
} as const satisfies ClientOrchestrationCommand),
),
);
const threadIds = new Set(input.threadIds.map(String));
await input.orchestrationEvents.waitForDistinct(
`assistant streaming output for ${input.label}`,
(event) =>
event.type === "thread.message-sent" &&
event.payload.role === "assistant" &&
event.payload.streaming &&
threadIds.has(String(event.payload.threadId)),
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
input.threadIds.length,
);
}
async function startCreateTurnSpamLoad(input: {
readonly harness: ServerPerfHarness;
readonly orchestrationEvents: BufferedEventFeed<OrchestrationEvent>;
readonly projectId: ProjectId;
readonly modelSelection: ModelSelection;
readonly count: number;
readonly label: string;
}): Promise<{
readonly threadIds: ReadonlyArray<ThreadIdType>;
readonly done: Promise<ReadonlyArray<ThreadIdType>>;
}> {
const threadIds = Array.from({ length: input.count }, (_, index) =>
makeControlThreadId(`${input.label}-${index + 1}`),
);
const threadIdStrings = new Set(threadIds.map(String));
const done = Promise.all(
threadIds.map(async (threadId, index) => {
const createCommand = {
type: "thread.create",
commandId: makeCommandId(`${input.label}-create-${index + 1}`),
threadId,
projectId: input.projectId,
title: `Perf Spam ${index + 1}`,
modelSelection: input.modelSelection,
interactionMode: "default",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: nowIso(),
} as const satisfies ClientOrchestrationCommand;
await dispatchCommand(input.harness, createCommand);
await input.orchestrationEvents.waitForEvent(
`thread.created for ${input.label}-${index + 1}`,
(event) => event.type === "thread.created" && event.payload.threadId === threadId,
);
await dispatchCommand(input.harness, {
type: "thread.turn.start",
commandId: makeCommandId(`${input.label}-turn-start-${index + 1}`),
threadId,
message: {
messageId: makeMessageId(`${input.label}-turn-${index + 1}`),
role: "user",
text: `Perf spam ${input.label} ${index + 1}`,
attachments: [],
},
runtimeMode: "full-access",
interactionMode: "default",
createdAt: nowIso(),
} as const satisfies ClientOrchestrationCommand);
return threadId;
}),
);
await input.orchestrationEvents.waitForCount(
`thread.create spam ${input.label}`,
(event) =>
event.type === "thread.created" && threadIdStrings.has(String(event.payload.threadId)),
Math.min(4, input.count),
);
await input.orchestrationEvents.waitForDistinct(
`assistant spam output ${input.label}`,
(event) =>
event.type === "thread.message-sent" &&
event.payload.role === "assistant" &&
event.payload.streaming &&
threadIdStrings.has(String(event.payload.threadId)),
(event) => (event.type === "thread.message-sent" ? String(event.payload.threadId) : ""),
Math.min(4, input.count),
);
return {
threadIds,
done,
};
}
async function startTerminalLoad(input: {
readonly harness: ServerPerfHarness;
readonly terminalEvents: BufferedEventFeed<TerminalEvent>;
readonly workspaceRoot: string;
readonly threadIds: ReadonlyArray<ThreadIdType>;
}): Promise<ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>> {
const sessions = await Promise.all(
input.threadIds.slice(0, TERMINAL_SESSION_COUNT).map(async (threadId, index) => {
const terminalId = `perf-${index + 1}`;
await input.harness.rpc.request((client) =>
client[WS_METHODS.terminalOpen]({
threadId,
terminalId,
cwd: input.workspaceRoot,
cols: 120,
rows: 32,
}),
);
const command = [
"i=1",
`while [ $i -le ${TERMINAL_OUTPUT_LINE_COUNT} ]`,
"do",
` printf 'perf-terminal-${index + 1}-%03d\\n' "$i"`,
" i=$((i + 1))",
` sleep ${TERMINAL_OUTPUT_SLEEP_SECONDS.toFixed(2)}`,
"done",
"",
].join("\n");
await input.harness.rpc.request((client) =>
client[WS_METHODS.terminalWrite]({
threadId,
terminalId,
data: command,
}),
);
return {
threadId,
terminalId,
};
}),
);
const terminalIds = new Set(sessions.map((session) => session.terminalId));
await input.terminalEvents.waitForDistinct(
"terminal output load",
(event) => event.type === "output" && terminalIds.has(event.terminalId),
(event) => event.terminalId,
sessions.length,
30_000,
);
return sessions;
}
async function closeTerminalLoad(
harness: ServerPerfHarness,
sessions: ReadonlyArray<{ readonly threadId: ThreadIdType; readonly terminalId: string }>,
): Promise<void> {
await Promise.all(
sessions.map((session) =>
harness.rpc.request((client) =>
client[WS_METHODS.terminalClose]({
threadId: session.threadId,
terminalId: session.terminalId,
deleteHistory: true,
}),
),
),
);
}
async function seedGitPressure(workspaceRoot: string): Promise<void> {
const untrackedDir = join(workspaceRoot, "perf-git-pressure");
await mkdir(untrackedDir, { recursive: true });
await Promise.all(
Array.from({ length: GIT_UNTRACKED_FILE_COUNT }, (_, index) =>
writeFile(
join(untrackedDir, `untracked-${(index + 1).toString().padStart(3, "0")}.ts`),
`export const perfFile${index + 1} = ${index + 1};\n`,
"utf8",
),
),
);
for (let index = 0; index < GIT_BRANCH_COUNT; index += 1) {
runGit(workspaceRoot, ["branch", `perf/latency-${(index + 1).toString().padStart(4, "0")}`]);
}
}
async function measureRpcLatencySeries<TResult>(input: {
readonly harness: ServerPerfHarness;
readonly name: string;
readonly loadProfile: string;
readonly iterations: number;
readonly execute: () => Promise<TResult>;
}): Promise<ServerRpcLatencySeries> {
const samples: PerfLatencySample[] = [];
for (let iteration = 0; iteration < input.iterations; iteration += 1) {
const startedAt = nowIso();
const startedAtMs = performance.now();
await input.execute();
const endedAtMs = performance.now();
samples.push({
name: `${input.name}-${iteration + 1}`,
durationMs: endedAtMs - startedAtMs,
startedAt,
endedAt: nowIso(),
metadata: {
iteration: iteration + 1,
loadProfile: input.loadProfile,
},
});
}
return {
name: input.name,
loadProfile: input.loadProfile,
summary: summarizeRpcLatencySeries(samples),
samples,
};
}
function groupCommandSeries(
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
loadProfile: string,
) {
const createSamples = samples.filter((sample) => sample.commandType === "thread.create");
const archiveSamples = samples.filter((sample) => sample.commandType === "thread.archive");
return [
{
name: "thread.create",
loadProfile,
summary: summarizeCommandLatencyMeasurements(createSamples),
samples: createSamples,
},
{
name: "thread.archive",
loadProfile,
summary: summarizeCommandLatencyMeasurements(archiveSamples),
samples: archiveSamples,
},
] as const;
}
describe("server perf latency", () => {
const disposables: Array<SubscriptionCleanup> = [];
afterEach(() => {
for (const disposable of disposables.splice(0)) {
disposable.dispose();
}
});
it("records idle and assistant-stream command latency at the websocket boundary", async () => {
let harness: ServerPerfHarness | null = null;
try {
harness = await startServerPerfHarness({
suite: "server-latency-critical-commands",
seedScenarioId: "burst_base",
providerScenarioId: "parallel_assistant_stream",
});
const runStartedAt = nowIso();
const burstProject = harness.seededState.snapshot.projects.find(
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
);
expect(burstProject).toBeTruthy();
const modelSelection = burstProject!.defaultModelSelection;
expect(modelSelection).toBeTruthy();
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
disposables.push(orchestrationEvents);
disposables.push({
dispose: harness.rpc.subscribe(
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
(event) => orchestrationEvents.push(event),
),
});
await sleep(250);
const idleSamples = await captureCreateArchiveSamples({
harness,
orchestrationEvents,
loadProfile: "idle",
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
projectId: burstProject!.id,
modelSelection: modelSelection!,
});
const streamingThreadIds = await ensureStreamingThreads({
harness,
orchestrationEvents,
projectId: burstProject!.id,
modelSelection: modelSelection!,
count: STREAM_THREAD_COUNT,
});
await startAssistantStreamingLoad({
harness,
orchestrationEvents,
threadIds: streamingThreadIds,
label: "stream-control-plane",
});
const streamingSamples = await captureCreateArchiveSamples({
harness,
orchestrationEvents,
loadProfile: "assistant-stream-5x",
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
projectId: burstProject!.id,
modelSelection: modelSelection!,
});
const spamLoad = await startCreateTurnSpamLoad({
harness,
orchestrationEvents,
projectId: burstProject!.id,
modelSelection: modelSelection!,
count: SPAM_THREAD_COUNT,
label: "create-turn-spam-8x",
});
const spamSamples = await captureCreateArchiveSamples({
harness,
orchestrationEvents,
loadProfile: "create-turn-spam-8x",
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
projectId: burstProject!.id,
modelSelection: modelSelection!,
});
await spamLoad.done;
const commandLatency = [
...groupCommandSeries(idleSamples, "idle"),
...groupCommandSeries(streamingSamples, "assistant-stream-5x"),
...groupCommandSeries(spamSamples, "create-turn-spam-8x"),
];
const result = await harness.finishRun({
artifactBasename: "control-plane-stream-baseline",
artifact: {
suite: "server-latency-critical-commands",
scenarioId: "burst_base_control_plane_stream_baseline",
startedAt: runStartedAt,
completedAt: nowIso(),
commandLatency,
rpcLatency: [],
metadata: {
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
streamingThreadCount: STREAM_THREAD_COUNT,
spamThreadCount: SPAM_THREAD_COUNT,
},
},
});
harness = null;
expect(result.artifact.commandLatency).toHaveLength(6);
for (const series of result.artifact.commandLatency) {
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
expect(series.summary.dispatchToEventMs.p50Ms).not.toBeNull();
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
}
} finally {
await harness?.dispose();
}
}, 180_000);
it("records command and git rpc latency under terminal and mixed server load", async () => {
let harness: ServerPerfHarness | null = null;
let terminalSessions: ReadonlyArray<{
readonly threadId: ThreadIdType;
readonly terminalId: string;
}> = [];
try {
harness = await startServerPerfHarness({
suite: "server-latency-critical-commands",
seedScenarioId: "burst_base",
providerScenarioId: "parallel_assistant_stream",
});
const runStartedAt = nowIso();
const burstProject = harness.seededState.snapshot.projects.find(
(project) => project.id === PERF_CATALOG_IDS.burstBase.burstProjectId,
);
expect(burstProject).toBeTruthy();
const modelSelection = burstProject!.defaultModelSelection;
expect(modelSelection).toBeTruthy();
const orchestrationEvents = new BufferedEventFeed<OrchestrationEvent>();
const terminalEvents = new BufferedEventFeed<TerminalEvent>();
disposables.push(orchestrationEvents, terminalEvents);
disposables.push({
dispose: harness.rpc.subscribe(
(client) => client[WS_METHODS.subscribeOrchestrationDomainEvents]({}),
(event) => orchestrationEvents.push(event),
),
});
disposables.push({
dispose: harness.rpc.subscribe(
(client) => client[WS_METHODS.subscribeTerminalEvents]({}),
(event) => terminalEvents.push(event),
),
});
await sleep(250);
await seedGitPressure(harness.seededState.workspaceRoot);
const gitLatencyIdle = await Promise.all([
measureRpcLatencySeries({
harness,
name: "git.status",
loadProfile: "idle-repo-pressure",
iterations: GIT_RPC_SAMPLE_COUNT,
execute: () =>
harness!.rpc.request((client) =>
client[WS_METHODS.gitStatus]({
cwd: harness!.seededState.workspaceRoot,
}),
),
}),
measureRpcLatencySeries({
harness,
name: "git.listBranches",
loadProfile: "idle-repo-pressure",
iterations: GIT_RPC_SAMPLE_COUNT,
execute: () =>
harness!.rpc.request((client) =>
client[WS_METHODS.gitListBranches]({
cwd: harness!.seededState.workspaceRoot,
}),
),
}),
]);
const streamingThreadIds = await ensureStreamingThreads({
harness,
orchestrationEvents,
projectId: burstProject!.id,
modelSelection: modelSelection!,
count: STREAM_THREAD_COUNT,
});
terminalSessions = await startTerminalLoad({
harness,
terminalEvents,
workspaceRoot: harness.seededState.workspaceRoot,
threadIds: streamingThreadIds,
});
const terminalSamples = await captureCreateArchiveSamples({
harness,
orchestrationEvents,
loadProfile: "terminal-output-3x",
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
projectId: burstProject!.id,
modelSelection: modelSelection!,
});
await sleep(6_500);
await startAssistantStreamingLoad({
harness,
orchestrationEvents,
threadIds: streamingThreadIds,
label: "mixed-load",
});
await terminalEvents.waitForCount(
"continued terminal output during mixed load",
(event) =>
event.type === "output" &&
terminalSessions.some((session) => session.terminalId === event.terminalId),
TERMINAL_SESSION_COUNT,
30_000,
);
const mixedSamples = await captureCreateArchiveSamples({
harness,
orchestrationEvents,
loadProfile: "mixed-stream-terminal-git",
sampleCount: CONTROL_PLANE_SAMPLE_COUNT,
projectId: burstProject!.id,
modelSelection: modelSelection!,
});
const gitLatencyMixed = await Promise.all([
measureRpcLatencySeries({
harness,
name: "git.status",
loadProfile: "mixed-stream-terminal-git",
iterations: GIT_RPC_SAMPLE_COUNT,
execute: () =>
harness!.rpc.request((client) =>
client[WS_METHODS.gitStatus]({
cwd: harness!.seededState.workspaceRoot,
}),
),
}),
measureRpcLatencySeries({
harness,
name: "git.listBranches",
loadProfile: "mixed-stream-terminal-git",
iterations: GIT_RPC_SAMPLE_COUNT,
execute: () =>
harness!.rpc.request((client) =>
client[WS_METHODS.gitListBranches]({
cwd: harness!.seededState.workspaceRoot,
}),
),
}),
]);
await closeTerminalLoad(harness, terminalSessions);
terminalSessions = [];
const result = await harness.finishRun({
artifactBasename: "terminal-mixed-git-baseline",
artifact: {
suite: "server-latency-critical-commands",
scenarioId: "burst_base_terminal_mixed_git_baseline",
startedAt: runStartedAt,
completedAt: nowIso(),
commandLatency: [
...groupCommandSeries(terminalSamples, "terminal-output-3x"),
...groupCommandSeries(mixedSamples, "mixed-stream-terminal-git"),
],
rpcLatency: [...gitLatencyIdle, ...gitLatencyMixed],
metadata: {
sampleCountPerProfile: CONTROL_PLANE_SAMPLE_COUNT,
gitRpcSampleCount: GIT_RPC_SAMPLE_COUNT,
branchCount: GIT_BRANCH_COUNT,
untrackedFileCount: GIT_UNTRACKED_FILE_COUNT,
terminalSessionCount: TERMINAL_SESSION_COUNT,
},
},
});
harness = null;
expect(result.artifact.commandLatency).toHaveLength(4);
expect(result.artifact.rpcLatency).toHaveLength(4);
for (const series of result.artifact.commandLatency) {
expect(series.samples).toHaveLength(CONTROL_PLANE_SAMPLE_COUNT);
expect(series.summary.dispatchToEventMs.maxMs).toBeLessThan(30_000);
}
for (const series of result.artifact.rpcLatency) {
expect(series.samples).toHaveLength(GIT_RPC_SAMPLE_COUNT);
expect(series.summary.maxMs).toBeLessThan(30_000);
}
} finally {
if (harness && terminalSessions.length > 0) {
await closeTerminalLoad(harness, terminalSessions).catch(() => undefined);
}
await harness?.dispose();
}
}, 180_000);
});
@@ -0,0 +1,393 @@
import { spawn, type ChildProcess } from "node:child_process";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { join, resolve } from "node:path";
import { performance } from "node:perf_hooks";
import { fileURLToPath } from "node:url";
import * as NodeSocket from "@effect/platform-node/NodeSocket";
import {
type OrchestrationEvent,
type TerminalEvent,
WS_METHODS,
WsRpcGroup,
} from "@t3tools/contracts";
import {
Effect,
Exit,
Layer,
ManagedRuntime,
Scope,
Stream,
type Scope as ScopeService,
} from "effect";
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
import {
summarizeLatencySamples,
summarizeLatencyValues,
type PerfLatencySample,
type PerfLatencySummary,
writeJsonArtifact,
} from "@t3tools/shared/perf/artifact";
import type {
PerfProviderScenarioId,
PerfSeedScenarioId,
} from "@t3tools/shared/perf/scenarioCatalog";
import { seedPerfState, type PerfSeededState } from "./seedPerfState.ts";
const repoRoot = fileURLToPath(new URL("../../../../", import.meta.url));
const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
const AUTO_BOOTSTRAP_PROJECT_ENV = "T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD";
const makeWsRpcClient = RpcClient.make(WsRpcGroup);
type WsRpcClient =
typeof makeWsRpcClient extends Effect.Effect<infer Client, any, any> ? Client : never;
export interface ServerCommandLatencyMeasurement {
readonly commandType: string;
readonly loadProfile: string;
readonly startedAt: string;
readonly dispatchToAckMs: number;
readonly dispatchToEventMs: number;
readonly ackToEventMs: number;
readonly resultSequence: number;
readonly eventSequence: number;
readonly metadata?: Record<string, unknown>;
}
export interface ServerCommandLatencySummary {
readonly count: number;
readonly dispatchToAckMs: PerfLatencySummary;
readonly dispatchToEventMs: PerfLatencySummary;
readonly ackToEventMs: PerfLatencySummary;
}
export interface ServerCommandLatencySeries {
readonly name: string;
readonly loadProfile: string;
readonly summary: ServerCommandLatencySummary;
readonly samples: ReadonlyArray<ServerCommandLatencyMeasurement>;
}
export interface ServerRpcLatencySeries {
readonly name: string;
readonly loadProfile: string;
readonly summary: PerfLatencySummary;
readonly samples: ReadonlyArray<PerfLatencySample>;
}
export interface ServerPerfRunArtifact {
readonly suite: string;
readonly scenarioId: string;
readonly startedAt: string;
readonly completedAt: string;
readonly commandLatency: ReadonlyArray<ServerCommandLatencySeries>;
readonly rpcLatency: ReadonlyArray<ServerRpcLatencySeries>;
readonly metadata?: Record<string, unknown>;
}
interface StartServerPerfHarnessOptions {
readonly suite: string;
readonly seedScenarioId: PerfSeedScenarioId;
readonly providerScenarioId?: PerfProviderScenarioId;
}
interface FinishServerPerfRunOptions {
readonly artifactBasename?: string;
readonly artifact: ServerPerfRunArtifact;
}
export interface ServerPerfHarness {
readonly seededState: PerfSeededState;
readonly wsUrl: string;
readonly artifactDir: string;
readonly rpc: PerfWsRpcClient;
readonly finishRun: (options: FinishServerPerfRunOptions) => Promise<{
readonly artifactPath: string;
readonly artifact: ServerPerfRunArtifact;
}>;
readonly dispose: () => Promise<void>;
}
const wsRpcProtocolLayer = (wsUrl: string) =>
RpcClient.layerProtocolSocket().pipe(
Layer.provide(NodeSocket.layerWebSocket(wsUrl)),
Layer.provide(RpcSerialization.layerJson),
);
async function pickFreePort(): Promise<number> {
return await new Promise<number>((resolvePort, reject) => {
const server = createServer();
server.on("error", reject);
server.listen(0, "127.0.0.1", () => {
const address = server.address();
if (!address || typeof address === "string") {
reject(new Error("Unable to resolve a free localhost port."));
return;
}
const { port } = address;
server.close((closeError) => {
if (closeError) {
reject(closeError);
return;
}
resolvePort(port);
});
});
});
}
async function stopChildProcess(process: ChildProcess): Promise<void> {
if (process.exitCode !== null) {
return;
}
process.kill("SIGTERM");
const exited = await new Promise<boolean>((resolveExited) => {
const timer = setTimeout(() => resolveExited(false), 5_000);
process.once("exit", () => {
clearTimeout(timer);
resolveExited(true);
});
});
if (!exited && process.exitCode === null) {
process.kill("SIGKILL");
await new Promise<void>((resolveExited) => {
process.once("exit", () => resolveExited());
});
}
}
async function ensureArtifactDir(suite: string, scenarioId: string): Promise<string> {
const baseArtifactDir = resolve(
process.env[PERF_ARTIFACT_DIR_ENV] ?? join(repoRoot, "artifacts/perf/server"),
);
const runId = `${suite}-${scenarioId}-${Date.now().toString()}`;
const artifactDir = join(baseArtifactDir, runId);
await mkdir(artifactDir, { recursive: true });
return artifactDir;
}
async function writeServerLogs(
artifactDir: string,
stdout: string,
stderr: string,
basename: string,
): Promise<void> {
await mkdir(artifactDir, { recursive: true });
await Promise.all([
writeFile(join(artifactDir, `${basename}.server.stdout.log`), stdout, "utf8"),
writeFile(join(artifactDir, `${basename}.server.stderr.log`), stderr, "utf8"),
]);
}
function buildPerfServerEnv(
baseEnv: NodeJS.ProcessEnv,
providerScenarioId?: PerfProviderScenarioId,
): NodeJS.ProcessEnv {
const env: NodeJS.ProcessEnv = {
...baseEnv,
[AUTO_BOOTSTRAP_PROJECT_ENV]: "false",
};
if (!providerScenarioId) {
delete env[PERF_PROVIDER_ENV];
delete env[PERF_SCENARIO_ENV];
return env;
}
return {
...env,
[PERF_PROVIDER_ENV]: "1",
[PERF_SCENARIO_ENV]: providerScenarioId,
};
}
export class PerfWsRpcClient {
private readonly runtime: ManagedRuntime.ManagedRuntime<RpcClient.Protocol, never>;
private readonly clientScope: Scope.Closeable;
private readonly clientPromise: Promise<WsRpcClient>;
private disposed = false;
constructor(private readonly wsUrl: string) {
this.runtime = ManagedRuntime.make(wsRpcProtocolLayer(wsUrl));
this.clientScope = this.runtime.runSync(Scope.make());
this.clientPromise = this.runtime.runPromise(Scope.provide(this.clientScope)(makeWsRpcClient));
}
async request<TSuccess, TError>(
execute: (client: WsRpcClient) => Effect.Effect<TSuccess, TError, never>,
): Promise<TSuccess> {
if (this.disposed) {
throw new Error(`WebSocket RPC client disposed for ${this.wsUrl}`);
}
const client = await this.clientPromise;
return await this.runtime.runPromise(Effect.suspend(() => execute(client)));
}
subscribe<TValue>(
connect: (client: WsRpcClient) => Stream.Stream<TValue, Error, never>,
listener: (value: TValue) => void,
): () => void {
if (this.disposed) {
return () => undefined;
}
let active = true;
const cancel = this.runtime.runCallback(
Effect.promise(() => this.clientPromise).pipe(
Effect.flatMap((client) =>
Stream.runForEach(connect(client), (value) =>
Effect.sync(() => {
if (!active) {
return;
}
listener(value);
}),
),
),
),
);
return () => {
active = false;
cancel();
};
}
async dispose(): Promise<void> {
if (this.disposed) {
return;
}
this.disposed = true;
await this.runtime.runPromise(Scope.close(this.clientScope, Exit.void));
await this.runtime.dispose();
}
}
async function waitForRpcReady(wsUrl: string, process: ChildProcess): Promise<void> {
const startedAtMs = performance.now();
const timeoutMs = 45_000;
while (performance.now() - startedAtMs < timeoutMs) {
if (process.exitCode !== null) {
throw new Error(`Perf server exited early with code ${process.exitCode}.`);
}
const client = new PerfWsRpcClient(wsUrl);
try {
await client.request((rpcClient) => rpcClient[WS_METHODS.serverGetSettings]({}));
await client.dispose();
return;
} catch {
await client.dispose().catch(() => undefined);
await new Promise((resolveDelay) => setTimeout(resolveDelay, 200));
}
}
throw new Error(`Timed out waiting for websocket readiness at ${wsUrl}.`);
}
export function summarizeCommandLatencyMeasurements(
samples: ReadonlyArray<ServerCommandLatencyMeasurement>,
): ServerCommandLatencySummary {
return {
count: samples.length,
dispatchToAckMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToAckMs)),
dispatchToEventMs: summarizeLatencyValues(samples.map((sample) => sample.dispatchToEventMs)),
ackToEventMs: summarizeLatencyValues(samples.map((sample) => sample.ackToEventMs)),
};
}
export function summarizeRpcLatencySeries(
samples: ReadonlyArray<PerfLatencySample>,
): PerfLatencySummary {
return summarizeLatencySamples(samples);
}
export async function startServerPerfHarness(
options: StartServerPerfHarnessOptions,
): Promise<ServerPerfHarness> {
const seededState = await seedPerfState(options.seedScenarioId);
const artifactDir = await ensureArtifactDir(options.suite, options.seedScenarioId);
const port = await pickFreePort();
const wsUrl = `ws://127.0.0.1:${port}/ws`;
const env = buildPerfServerEnv(process.env, options.providerScenarioId);
let stdoutBuffer = "";
let stderrBuffer = "";
let finished = false;
const serverProcess = spawn(
"bun",
[
"run",
"apps/server/src/bin.ts",
"--mode",
"web",
"--host",
"127.0.0.1",
"--port",
`${port}`,
"--base-dir",
seededState.baseDir,
"--no-browser",
],
{
cwd: repoRoot,
env,
stdio: ["ignore", "pipe", "pipe"],
},
);
serverProcess.stdout?.on("data", (chunk) => {
stdoutBuffer += chunk.toString();
});
serverProcess.stderr?.on("data", (chunk) => {
stderrBuffer += chunk.toString();
});
const cleanup = async () => {
if (finished) {
return;
}
finished = true;
await stopChildProcess(serverProcess);
await rm(seededState.runParentDir, { recursive: true, force: true });
};
try {
await waitForRpcReady(wsUrl, serverProcess);
const rpc = new PerfWsRpcClient(wsUrl);
return {
seededState,
wsUrl,
artifactDir,
rpc,
finishRun: async ({ artifactBasename, artifact }) => {
const basename = artifactBasename ?? `${artifact.suite}-${artifact.scenarioId}`;
await rpc.dispose();
await cleanup();
await writeServerLogs(artifactDir, stdoutBuffer, stderrBuffer, basename);
const artifactPath = join(artifactDir, `${basename}.json`);
await writeJsonArtifact(artifactPath, artifact);
return {
artifactPath,
artifact,
};
},
dispose: async () => {
await rpc.dispose().catch(() => undefined);
await cleanup();
},
};
} catch (error) {
await cleanup();
throw error;
}
}
export type { OrchestrationEvent, ScopeService, TerminalEvent, WsRpcClient };
@@ -40,7 +40,7 @@ const makeWorkspaceDirectory = Effect.gen(function* () {
interface IntegrationFixture {
readonly cwd: string;
readonly harness: TestProviderAdapterHarness;
readonly layer: Layer.Layer<ProviderService, unknown>;
readonly layer: Layer.Layer<ProviderService, unknown, never>;
}
const makeIntegrationFixture = Effect.gen(function* () {
+9 -8
View File
@@ -8,29 +8,30 @@
"directory": "apps/server"
},
"bin": {
"t3": "./dist/index.mjs"
"t3": "./dist/bin.mjs"
},
"files": [
"dist"
],
"type": "module",
"scripts": {
"dev": "bun run src/index.ts",
"dev": "bun run src/bin.ts",
"build": "node scripts/cli.ts build",
"start": "node dist/index.mjs",
"start": "node dist/bin.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vp test run"
"test": "vitest run",
"test:perf": "vitest run integration/perf"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.77",
"@effect/platform-bun": "catalog:",
"@effect/platform-node": "catalog:",
"@effect/sql-sqlite-bun": "catalog:",
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
"open": "^10.1.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -40,9 +41,9 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vite-plus": "catalog:"
"vitest": "catalog:"
},
"engines": {
"node": "^22.16 || ^23.11 || >=24.10"
+5 -9
View File
@@ -10,10 +10,7 @@ import {
DEVELOPMENT_ICON_OVERRIDES,
PUBLISH_ICON_OVERRIDES,
} from "../../../scripts/lib/brand-assets.ts";
import {
getWorkspaceCatalog,
resolveCatalogDependencies,
} from "../../../scripts/lib/resolve-catalog.ts";
import { resolveCatalogDependencies } from "../../../scripts/lib/resolve-catalog.ts";
import rootPackageJson from "../../../package.json" with { type: "json" };
import serverPackageJson from "../package.json" with { type: "json" };
@@ -25,7 +22,6 @@ class CliError extends Data.TaggedError("CliError")<{
const RepoRoot = Effect.service(Path.Path).pipe(
Effect.flatMap((path) => path.fromFileUrl(new URL("../../..", import.meta.url))),
);
const workspaceCatalog = getWorkspaceCatalog(rootPackageJson);
const runCommand = Effect.fn("runCommand")(function* (command: ChildProcess.Command) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -133,7 +129,7 @@ const buildCmd = Command.make(
const repoRoot = yield* RepoRoot;
const serverDir = path.join(repoRoot, "apps/server");
yield* Effect.log("[cli] Running vp pack...");
yield* Effect.log("[cli] Running tsdown...");
yield* runCommand(
ChildProcess.make({
cwd: serverDir,
@@ -141,7 +137,7 @@ const buildCmd = Command.make(
stderr: "inherit",
// Windows needs shell mode to resolve .cmd shims (e.g. bun.cmd).
shell: process.platform === "win32",
})`vp pack`,
})`bun tsdown`,
);
const webDist = path.join(repoRoot, "apps/web/dist");
@@ -155,7 +151,7 @@ const buildCmd = Command.make(
yield* Effect.logWarning("[cli] Web dist not found — skipping client bundle.");
}
}),
).pipe(Command.withDescription("Build the server package (vp pack + bundle web client)."));
).pipe(Command.withDescription("Build the server package (tsdown + bundle web client)."));
// ---------------------------------------------------------------------------
// publish subcommand
@@ -209,7 +205,7 @@ const publishCmd = Command.make(
pkg.dependencies = resolveCatalogDependencies(
pkg.dependencies,
workspaceCatalog,
rootPackageJson.workspaces.catalog,
"apps/server dependencies",
);
+52
View File
@@ -0,0 +1,52 @@
import { join } from "node:path";
import { seedPerfState } from "../integration/perf/seedPerfState.ts";
import { getPerfSeedScenario } from "@t3tools/shared/perf/scenarioCatalog";
const PERF_SEED_JSON_START = "__T3_PERF_SEED_JSON_START__";
const PERF_SEED_JSON_END = "__T3_PERF_SEED_JSON_END__";
const scenarioId = process.argv[2];
if (scenarioId !== "large_threads" && scenarioId !== "burst_base") {
console.error(`Expected a perf seed scenario id, received '${scenarioId ?? "<missing>"}'.`);
process.exit(1);
}
const seeded = await seedPerfState(scenarioId);
const scenario = getPerfSeedScenario(scenarioId);
const scenarioProjectById = new Map(scenario.projects.map((project) => [project.id, project]));
const scenarioThreadById = new Map(scenario.threads.map((thread) => [thread.id, thread]));
const projectById = new Map(seeded.snapshot.projects.map((project) => [project.id, project]));
const payload = JSON.stringify(
{
scenarioId: seeded.scenarioId,
runParentDir: seeded.runParentDir,
baseDir: seeded.baseDir,
workspaceRoot: seeded.workspaceRoot,
projectTitle: seeded.snapshot.projects[0]?.title ?? null,
projectSummaries: seeded.snapshot.projects.map((project) => ({
id: project.id,
title: project.title,
workspaceRoot:
scenarioProjectById.get(project.id)?.workspaceDirectoryName !== undefined
? join(seeded.baseDir, scenarioProjectById.get(project.id)?.workspaceDirectoryName ?? "")
: project.workspaceRoot,
threadCount: seeded.snapshot.threads.filter((thread) => thread.projectId === project.id)
.length,
})),
threadSummaries: seeded.snapshot.threads.map((thread) => ({
id: thread.id,
projectId: thread.projectId,
projectTitle: projectById.get(thread.projectId)?.title ?? null,
title: thread.title,
turnCount: scenarioThreadById.get(thread.id)?.turnCount ?? null,
messageCount: thread.messages.length,
activityCount: thread.activities.length,
proposedPlanCount: thread.proposedPlans.length,
checkpointCount: thread.checkpoints.length,
})),
},
null,
2,
);
process.stdout.write(`${PERF_SEED_JSON_START}\n${payload}\n${PERF_SEED_JSON_END}\n`);
+1 -1
View File
@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
createAttachmentId,
+17
View File
@@ -0,0 +1,17 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
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 { cli } from "./cli";
import { version } from "../package.json" with { type: "json" };
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
Command.run(cli, { version }).pipe(
Effect.scoped,
Effect.provide(CliRuntimeLayer),
NodeRuntime.runMain,
);
+1 -1
View File
@@ -8,7 +8,7 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import { TestClock } from "effect/testing";
import { vi } from "vite-plus/test";
import { vi } from "vitest";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { assertNone, assertSome } from "@effect/vitest/utils";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { parseTurnDiffFilesFromUnifiedDiff } from "./Diffs.ts";
+1 -1
View File
@@ -1,6 +1,6 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "../git/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
@@ -7,7 +7,7 @@ import {
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
Effect.gen(function* () {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
@@ -149,7 +149,8 @@ const make = Effect.gen(function* () {
}
return turnDiff;
});
},
);
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
@@ -3,14 +3,14 @@ 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 { describe, expect } from "vite-plus/test";
import { describe, expect } from "vitest";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointStoreLive } from "./CheckpointStore.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { ServerConfig } from "../../config.ts";
import { ThreadId } from "@t3tools/contracts";
@@ -14,7 +14,7 @@ import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
@@ -86,139 +86,140 @@ const makeCheckpointStore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.captureCheckpoint";
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
(tempDir) =>
Effect.gen(function* () {
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]",
};
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* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["read-tree", "HEAD"],
env: commitEnv,
});
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["add", "-A", "--", "."],
env: commitEnv,
});
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const writeTreeResult = yield* git.execute({
operation,
cwd: input.cwd,
args: ["write-tree"],
env: commitEnv,
});
const treeOid = writeTreeResult.stdout.trim();
if (treeOid.length === 0) {
return yield* new GitCommandError({
operation,
command: "git write-tree",
cwd: input.cwd,
detail: "git write-tree returned an empty tree oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.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 GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
const message = `t3 checkpoint ref=${input.checkpointRef}`;
const commitTreeResult = yield* git.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 GitCommandError({
operation,
command: "git commit-tree",
cwd: input.cwd,
detail: "git commit-tree returned an empty commit oid.",
});
}
yield* git.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,
}),
),
}),
);
});
yield* git.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 hasCheckpointRef: CheckpointStoreShape["hasCheckpointRef"] = (input) =>
resolveCheckpointCommit(input.cwd, input.checkpointRef).pipe(
Effect.map((commit) => commit !== null),
);
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.restoreCheckpoint";
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.restoreCheckpoint";
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
let commitOid = yield* resolveCheckpointCommit(input.cwd, input.checkpointRef);
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid && input.fallbackToHead === true) {
commitOid = yield* resolveHeadCommit(input.cwd);
}
if (!commitOid) {
return false;
}
if (!commitOid) {
return false;
}
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
yield* git.execute({
operation,
cwd: input.cwd,
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
Effect.gen(function* () {
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
@@ -247,24 +248,26 @@ const makeCheckpointStore = Effect.gen(function* () {
});
return result.stdout;
});
},
);
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.deleteCheckpointRefs";
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const operation = "CheckpointStore.deleteCheckpointRefs";
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
yield* Effect.forEach(
input.checkpointRefs,
(checkpointRef) =>
git.execute({
operation,
cwd: input.cwd,
args: ["update-ref", "-d", checkpointRef],
allowNonZeroExit: true,
}),
{ discard: true },
);
});
return {
isGitRepository,
+318
View File
@@ -0,0 +1,318 @@
import os from "node:os";
import { assert, expect, it } from "@effect/vitest";
import { ConfigProvider, Effect, FileSystem, Layer, Option, Path } from "effect";
import { NetService } from "@t3tools/shared/Net";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { deriveServerPaths } from "./config";
import { resolveServerConfig } from "./cli";
it.layer(NodeServices.layer)("cli config resolution", (it) => {
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
});
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 derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: baseDir,
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "env-token",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Warn",
mode: "desktop",
port: 4001,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "0.0.0.0",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
authToken: "env-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
}),
);
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 derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.some("web"),
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.some(baseDir),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.some(true),
authToken: Option.some("flag-token"),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.some(true),
logWebSocketEvents: Option.some(true),
},
Option.some("Debug"),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_LOG_LEVEL: "Warn",
T3CODE_MODE: "desktop",
T3CODE_PORT: "4001",
T3CODE_HOST: "0.0.0.0",
T3CODE_HOME: join(os.tmpdir(), "ignored-base"),
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
T3CODE_NO_BROWSER: "false",
T3CODE_AUTH_TOKEN: "ignored-token",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_LOG_WS_EVENTS: "false",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Debug",
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
authToken: "flag-token",
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
}),
);
it.effect("uses bootstrap envelope values as fallbacks when flags and env are absent", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = "/tmp/t3-bootstrap-home";
const fd = yield* openBootstrapFd({
mode: "desktop",
port: 4888,
host: "127.0.0.2",
t3Home: baseDir,
devUrl: "http://127.0.0.1:5173",
noBrowser: true,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:5173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
port: Option.none(),
host: Option.none(),
baseDir: Option.none(),
devUrl: Option.none(),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_BOOTSTRAP_FD: String(fd),
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Info",
mode: "desktop",
port: 4888,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.2",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:5173"),
noBrowser: true,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
assert.equal(join(baseDir, "dev"), resolved.stateDir);
}),
);
it.effect("creates derived runtime directories during config resolution", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-dirs-" });
const resolved = yield* resolveServerConfig(
{
mode: Option.some("desktop"),
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
devUrl: Option.some(new URL("http://127.0.0.1:5173")),
noBrowser: Option.none(),
authToken: Option.none(),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.none(),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
NetService.layer,
),
),
);
for (const directory of [
resolved.stateDir,
resolved.logsDir,
resolved.providerLogsDir,
resolved.terminalLogsDir,
resolved.attachmentsDir,
resolved.worktreesDir,
path.dirname(resolved.serverLogPath),
]) {
expect(yield* fs.exists(directory)).toBe(true);
}
}),
);
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 fd = yield* openBootstrapFd({
mode: "desktop",
port: 4888,
host: "127.0.0.2",
t3Home: "/tmp/t3-bootstrap-home",
devUrl: "http://127.0.0.1:5173",
noBrowser: false,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
const derivedPaths = yield* deriveServerPaths(baseDir, new URL("http://127.0.0.1:4173"));
const resolved = yield* resolveServerConfig(
{
mode: Option.none(),
port: Option.some(8788),
host: Option.some("127.0.0.1"),
baseDir: Option.none(),
devUrl: Option.some(new URL("http://127.0.0.1:4173")),
noBrowser: Option.none(),
authToken: Option.some("flag-token"),
bootstrapFd: Option.none(),
autoBootstrapProjectFromCwd: Option.none(),
logWebSocketEvents: Option.none(),
},
Option.some("Debug"),
).pipe(
Effect.provide(
Layer.mergeAll(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_MODE: "web",
T3CODE_BOOTSTRAP_FD: String(fd),
T3CODE_HOME: baseDir,
T3CODE_NO_BROWSER: "true",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
T3CODE_LOG_WS_EVENTS: "true",
},
}),
),
NetService.layer,
),
),
);
expect(resolved).toEqual({
logLevel: "Debug",
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
authToken: "flag-token",
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
}),
);
});
+37
View File
@@ -0,0 +1,37 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { NetService } from "@t3tools/shared/Net";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as CliError from "effect/unstable/cli/CliError";
import { Command } from "effect/unstable/cli";
import { cli } from "./cli.ts";
const CliRuntimeLayer = Layer.mergeAll(NodeServices.layer, NetService.layer);
it.layer(NodeServices.layer)("cli log-level parsing", (it) => {
it.effect("accepts the built-in lowercase log-level flag values", () =>
Command.runWith(cli, { version: "0.0.0" })(["--log-level", "debug", "--version"]).pipe(
Effect.provide(CliRuntimeLayer),
),
);
it.effect("rejects invalid log-level casing before launching the server", () =>
Effect.gen(function* () {
const error = yield* Command.runWith(cli, { version: "0.0.0" })([
"--log-level",
"Debug",
]).pipe(Effect.provide(CliRuntimeLayer), Effect.flip);
if (!CliError.isCliError(error)) {
assert.fail(`Expected CliError, got ${String(error)}`);
}
if (error._tag !== "InvalidValue") {
assert.fail(`Expected InvalidValue, got ${error._tag}`);
}
assert.equal(error.option, "log-level");
assert.equal(error.value, "Debug");
}),
);
});
+292
View File
@@ -0,0 +1,292 @@
import { NetService } from "@t3tools/shared/Net";
import { Config, Effect, LogLevel, Option, Schema } from "effect";
import { Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
DEFAULT_PORT,
deriveServerPaths,
ensureServerDirectories,
resolveStaticDir,
ServerConfig,
RuntimeMode,
type ServerConfigShape,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { resolveBaseDir } from "./os-jank";
import { runServer } from "./server";
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
const BootstrapEnvelopeSchema = Schema.Struct({
mode: Schema.optional(RuntimeMode),
port: Schema.optional(PortSchema),
host: Schema.optional(Schema.String),
t3Home: Schema.optional(Schema.String),
devUrl: Schema.optional(Schema.URLFromString),
noBrowser: Schema.optional(Schema.Boolean),
authToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
});
const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
Flag.optional,
);
const portFlag = Flag.integer("port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("Port for the HTTP/WebSocket server."),
Flag.optional,
);
const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
Flag.optional,
);
const baseDirFlag = Flag.string("base-dir").pipe(
Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
Flag.optional,
);
const devUrlFlag = Flag.string("dev-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
Flag.optional,
);
const noBrowserFlag = Flag.boolean("no-browser").pipe(
Flag.withDescription("Disable automatic browser opening."),
Flag.optional,
);
const authTokenFlag = Flag.string("auth-token").pipe(
Flag.withDescription("Auth token required for WebSocket connections."),
Flag.withAlias("token"),
Flag.optional,
);
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
Flag.withSchema(Schema.Int),
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
Flag.optional,
);
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
Flag.withDescription(
"Create a project for the current working directory on startup when missing.",
),
Flag.optional,
);
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
Flag.withDescription(
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
),
Flag.withAlias("log-ws-events"),
Flag.optional,
);
const EnvServerConfig = Config.all({
logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
});
interface CliServerFlags {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly baseDir: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
}
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
export const resolveServerConfig = (
flags: CliServerFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const env = yield* EnvServerConfig;
const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
: Option.none();
const mode: RuntimeMode = Option.getOrElse(
resolveOptionPrecedence(
flags.mode,
Option.fromUndefinedOr(env.mode),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
),
() => "web",
);
const port = yield* Option.match(
resolveOptionPrecedence(
flags.port,
Option.fromUndefinedOr(env.port),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
),
{
onSome: (value) => Effect.succeed(value),
onNone: () => {
if (mode === "desktop") {
return Effect.succeed(DEFAULT_PORT);
}
return findAvailablePort(DEFAULT_PORT);
},
},
);
const devUrl = Option.getOrElse(
resolveOptionPrecedence(
flags.devUrl,
Option.fromUndefinedOr(env.devUrl),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
),
() => undefined,
);
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(
resolveOptionPrecedence(
flags.baseDir,
Option.fromUndefinedOr(env.t3Home),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.t3Home),
),
),
),
);
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
const noBrowser = resolveBooleanFlag(
flags.noBrowser,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.noBrowser),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.noBrowser),
),
),
() => mode === "desktop",
),
);
const authToken = Option.getOrUndefined(
resolveOptionPrecedence(
flags.authToken,
Option.fromUndefinedOr(env.authToken),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.authToken),
),
),
);
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
flags.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
);
const logWebSocketEvents = resolveBooleanFlag(
flags.logWebSocketEvents,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
),
),
() => Boolean(devUrl),
),
);
const staticDir = devUrl ? undefined : yield* resolveStaticDir();
const host = Option.getOrElse(
resolveOptionPrecedence(
flags.host,
Option.fromUndefinedOr(env.host),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
),
() => (mode === "desktop" ? "127.0.0.1" : undefined),
);
const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
const config: ServerConfigShape = {
logLevel,
mode,
port,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host,
staticDir,
devUrl,
noBrowser,
authToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
};
return config;
});
const commandFlags = {
mode: modeFlag,
port: portFlag,
host: hostFlag,
baseDir: baseDirFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
} as const;
const rootCommand = Command.make("t3", commandFlags).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((flags) =>
Effect.gen(function* () {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveServerConfig(flags, logLevel);
return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
}),
),
);
export const cli = rootCommand;
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
+1 -1
View File
@@ -432,7 +432,7 @@ export interface CodexAppServerManagerEvents {
export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEvents> {
private readonly sessions = new Map<ThreadId, CodexSessionContext>();
private runPromise: (effect: Effect.Effect<unknown>) => Promise<unknown>;
private runPromise: (effect: Effect.Effect<unknown, never>) => Promise<unknown>;
constructor(services?: ServiceMap.ServiceMap<never>) {
super();
this.runPromise = services ? Effect.runPromiseWith(services) : Effect.runPromise;
+26 -6
View File
@@ -6,11 +6,12 @@
*
* @module ServerConfig
*/
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
export type RuntimeMode = "web" | "desktop";
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
export type RuntimeMode = typeof RuntimeMode.Type;
/**
* ServerDerivedPaths - Derived paths from the base directory.
@@ -34,6 +35,7 @@ export interface ServerDerivedPaths {
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape extends ServerDerivedPaths {
readonly logLevel: LogLevel.LogLevel;
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
@@ -73,6 +75,26 @@ export const deriveServerPaths = Effect.fn(function* (
};
});
export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* Effect.all(
[
fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
],
{ concurrency: "unbounded" },
);
});
/**
* ServerConfig - Service tag for server runtime configuration.
*/
@@ -91,12 +113,10 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
? baseDirOrPrefix
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
yield* ensureServerDirectories(derivedPaths);
return {
logLevel: "Error",
cwd,
baseDir,
...derivedPaths,
-67
View File
@@ -1,67 +0,0 @@
import { Schema } from "effect";
/**
* GitCommandError - Git command execution failed.
*/
export class GitCommandError extends Schema.TaggedErrorClass<GitCommandError>()("GitCommandError", {
operation: Schema.String,
command: Schema.String,
cwd: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git command failed in ${this.operation}: ${this.command} (${this.cwd}) - ${this.detail}`;
}
}
/**
* GitHubCliError - GitHub CLI execution or authentication failed.
*/
export class GitHubCliError extends Schema.TaggedErrorClass<GitHubCliError>()("GitHubCliError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `GitHub CLI failed in ${this.operation}: ${this.detail}`;
}
}
/**
* TextGenerationError - Commit or PR text generation failed.
*/
export class TextGenerationError extends Schema.TaggedErrorClass<TextGenerationError>()(
"TextGenerationError",
{
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Text generation failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerError - Stacked Git workflow orchestration failed.
*/
export class GitManagerError extends Schema.TaggedErrorClass<GitManagerError>()("GitManagerError", {
operation: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {
override get message(): string {
return `Git manager failed in ${this.operation}: ${this.detail}`;
}
}
/**
* GitManagerServiceError - Errors emitted by stacked Git workflow orchestration.
*/
export type GitManagerServiceError =
| GitManagerError
| GitCommandError
| GitHubCliError
| TextGenerationError;
@@ -1,7 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vite-plus/test";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
+106 -112
View File
@@ -14,7 +14,7 @@ import { ClaudeModelSelection } from "@t3tools/contracts";
import { resolveApiModelId } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "../Errors.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
@@ -66,7 +66,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
const runClaudeJson = <S extends Schema.Top>({
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -82,131 +82,125 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.claudeAgent,
).pipe(Effect.catch(() => Effect.undefined));
const runClaudeCommand = Effect.gen(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
const runClaudeCommand = Effect.fn("runClaudeJson.runClaudeCommand")(function* () {
const command = ChildProcess.make(
claudeSettings?.binaryPath || "claude",
[
"-p",
"--output-format",
"json",
"--json-schema",
jsonSchemaStr,
"--model",
resolveApiModelId(modelSelection),
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
),
);
),
],
{ concurrency: "unbounded" },
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError(
"claude",
operation,
cause,
"Failed to read Claude CLI exit code",
),
),
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
return stdout;
});
const rawStdout = yield* runClaudeCommand().pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
],
{ concurrency: "unbounded" },
);
onSome: (value) => Effect.succeed(value),
}),
),
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail:
detail.length > 0
? `Claude CLI command failed: ${detail}`
: `Claude CLI command failed with code ${exitCode}.`,
});
}
return stdout;
});
const rawStdout = yield* runClaudeCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CLAUDE_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Claude CLI request timed out." }),
),
onSome: (value) => Effect.succeed(value),
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
);
),
);
const envelope = yield* Schema.decodeEffect(Schema.fromJsonString(ClaudeOutputEnvelope))(
rawStdout,
).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude CLI returned unexpected output format.",
cause,
}),
),
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
);
return yield* Schema.decodeEffect(outputSchemaJson)(envelope.structured_output).pipe(
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Claude returned invalid structured output.",
cause,
}),
),
),
);
});
),
);
});
// ---------------------------------------------------------------------------
// TextGenerationShape methods
@@ -1,11 +1,11 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Result } from "effect";
import { expect } from "vite-plus/test";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
+154 -156
View File
@@ -8,7 +8,7 @@ import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shar
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGenerationError } from "@t3tools/contracts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
@@ -82,47 +82,46 @@ const makeCodexTextGeneration = Effect.gen(function* () {
);
};
const safeUnlink = (filePath: string): Effect.Effect<void> =>
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = (
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
_operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
attachments: BranchNameGenerationInput["attachments"],
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
Effect.gen(function* () {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
): Effect.fn.Return<MaterializedImageAttachments, TextGenerationError> {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
}
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
continue;
}
const fileInfo = yield* fileSystem
.stat(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
continue;
}
imagePaths.push(resolvedPath);
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
continue;
}
return { imagePaths };
});
const fileInfo = yield* fileSystem
.stat(resolvedPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
continue;
}
imagePaths.push(resolvedPath);
}
return { imagePaths };
});
const runCodexJson = <S extends Schema.Top>({
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -142,138 +141,137 @@ const makeCodexTextGeneration = Effect.gen(function* () {
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: CodexModelSelection;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
}): Effect.fn.Return<S["Type"], TextGenerationError, S["DecodingServices"]> {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.fn("runCodexJson.runCodexCommand")(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.providers.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
modelSelection.options,
);
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
"-",
],
{
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
});
const cleanup = Effect.all(
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
modelSelection.model,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
"--output-schema",
schemaPath,
"--output-last-message",
outputPath,
...imagePaths.flatMap((imagePath) => ["--image", imagePath]),
"-",
],
{
concurrency: "unbounded",
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
).pipe(Effect.asVoid);
);
return yield* Effect.gen(function* () {
yield* runCodexCommand.pipe(
Effect.scoped,
Effect.timeoutOption(CODEX_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
),
onSome: () => Effect.void,
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
),
);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
{ concurrency: "unbounded" },
);
if (exitCode !== 0) {
const stderrDetail = stderr.trim();
const stdoutDetail = stdout.trim();
const detail = stderrDetail.length > 0 ? stderrDetail : stdoutDetail;
return yield* new TextGenerationError({
operation,
detail:
detail.length > 0
? `Codex CLI command failed: ${detail}`
: `Codex CLI command failed with code ${exitCode}.`,
});
}
});
const cleanup = Effect.all(
[schemaPath, outputPath, ...cleanupPaths].map((filePath) => safeUnlink(filePath)),
{
concurrency: "unbounded",
},
).pipe(Effect.asVoid);
return yield* Effect.gen(function* () {
yield* runCodexCommand().pipe(
Effect.scoped,
Effect.timeoutOption(CODEX_TIMEOUT_MS),
Effect.flatMap(
Option.match({
onNone: () =>
Effect.fail(
new TextGenerationError({ operation, detail: "Codex CLI request timed out." }),
),
onSome: () => Effect.void,
}),
),
);
return yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: "Failed to read Codex output file.",
cause,
}),
),
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Codex returned invalid structured output.",
cause,
}),
),
);
return yield* fileSystem.readFileString(outputPath).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: "Failed to read Codex output file.",
cause,
}),
),
Effect.flatMap(Schema.decodeEffect(Schema.fromJsonString(outputSchemaJson))),
Effect.catchTag("SchemaError", (cause) =>
Effect.fail(
new TextGenerationError({
operation,
detail: "Codex returned invalid structured output.",
cause,
}),
),
),
);
}).pipe(Effect.ensuring(cleanup));
});
),
);
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CodexTextGeneration.generateCommitMessage",
+62 -4
View File
@@ -4,11 +4,11 @@ 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 { describe, expect, vi } from "vite-plus/test";
import { describe, expect, vi } from "vitest";
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
import { GitCommandError } from "../Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
import { ServerConfig } from "../../config.ts";
@@ -369,12 +369,70 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("parses separate branch names when column.ui is always enabled", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
const createdBranchNames = [
"go-bin",
"copilot/rewrite-cli-in-go",
"copilot/rewrite-cli-in-rust",
] as const;
for (const branchName of createdBranchNames) {
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: branchName });
}
yield* git(tmp, ["config", "column.ui", "always"]);
const rawBranchOutput = yield* git(tmp, ["branch", "--no-color"], {
...process.env,
COLUMNS: "120",
});
expect(
rawBranchOutput
.split("\n")
.some(
(line) =>
createdBranchNames.filter((branchName) => line.includes(branchName)).length >= 2,
),
).toBe(true);
const realGitCore = yield* GitCore;
const core = yield* makeIsolatedGitCore((input) =>
realGitCore.execute(
input.args[0] === "branch"
? {
...input,
env: { ...input.env, COLUMNS: "120" },
}
: input,
),
);
const result = yield* core.listBranches({ cwd: tmp });
const localBranchNames = result.branches
.filter((branch) => !branch.isRemote)
.map((branch) => branch.name);
expect(localBranchNames).toHaveLength(4);
expect(localBranchNames).toEqual(
expect.arrayContaining([initialBranch, ...createdBranchNames]),
);
expect(
localBranchNames.some(
(branchName) =>
createdBranchNames.filter((createdBranch) => branchName.includes(createdBranch))
.length >= 2,
),
).toBe(false);
}),
);
it.effect("isDefault is false when no remote exists", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
yield* initRepoWithCommit(tmp);
const result = yield* (yield* GitCore).listBranches({ cwd: tmp });
expect(result.branches.every((b) => !b.isDefault)).toBe(true);
expect(result.branches.every((b) => b.isDefault === false)).toBe(true);
}),
);
@@ -1898,7 +1956,7 @@ it.layer(TestLayer)("git integration", (it) => {
let didFailRemoteBranches = false;
let didFailRemoteNames = false;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args.join(" ") === "branch --no-color --remotes") {
if (input.args.join(" ") === "branch --no-color --no-column --remotes") {
didFailRemoteBranches = true;
return Effect.fail(
new GitCommandError({
+10 -8
View File
@@ -18,7 +18,7 @@ import {
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import {
GitCore,
type ExecuteGitProgress,
@@ -324,7 +324,7 @@ function toGitCommandError(
interface Trace2Monitor {
readonly env: NodeJS.ProcessEnv;
readonly flush: Effect.Effect<void>;
readonly flush: Effect.Effect<void, never>;
}
function trace2ChildKey(record: Record<string, unknown>): string | null {
@@ -488,7 +488,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
truncateOutputAtMaxBytes: boolean,
onLine: ((line: string) => Effect.Effect<void>) | undefined,
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
@@ -1566,7 +1566,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const localBranchResult = yield* executeGit(
"GitCore.listBranches.branchNoColor",
input.cwd,
["branch", "--no-color"],
["branch", "--no-color", "--no-column"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
@@ -1581,7 +1581,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return yield* createGitCommandError(
"GitCore.listBranches",
input.cwd,
["branch", "--no-color"],
["branch", "--no-color", "--no-column"],
stderr || "git branch failed",
);
}
@@ -1589,7 +1589,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const remoteBranchResultEffect = executeGit(
"GitCore.listBranches.remoteBranches",
input.cwd,
["branch", "--no-color", "--remotes"],
["branch", "--no-color", "--no-column", "--remotes"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
@@ -1941,8 +1941,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.forkScoped(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })),
yield* refreshCheckedOutBranchUpstream(input.cwd).pipe(
Effect.ignoreCause({ log: true }),
Effect.forkDetach({ startImmediately: true }),
);
},
);
@@ -1957,6 +1958,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
runGitStdout("GitCore.listLocalBranchNames", cwd, [
"branch",
"--list",
"--no-column",
"--format=%(refname:short)",
]).pipe(
Effect.map((stdout) =>
+1 -1
View File
@@ -1,6 +1,6 @@
import { assert, it } from "@effect/vitest";
import { Effect } from "effect";
import { afterEach, expect, vi } from "vite-plus/test";
import { afterEach, expect, vi } from "vitest";
vi.mock("../../processRunner", () => ({
runProcess: vi.fn(),
+1 -1
View File
@@ -2,7 +2,7 @@ import { Effect, Layer, Schema } from "effect";
import { PositiveInt, TrimmedNonEmptyString } from "@t3tools/contracts";
import { runProcess } from "../../processRunner";
import { GitHubCliError } from "../Errors.ts";
import { GitHubCliError } from "@t3tools/contracts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
@@ -5,10 +5,10 @@ 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 { expect } from "vite-plus/test";
import { expect } from "vitest";
import type { GitActionProgressEvent, ModelSelection } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "@t3tools/contracts";
import { type GitManagerShape } from "../Services/GitManager.ts";
import {
type GitHubCliShape,
+2 -2
View File
@@ -14,7 +14,7 @@ import {
sanitizeFeatureBranchName,
} from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import { GitManagerError } from "@t3tools/contracts";
import {
GitManager,
type GitActionProgressReporter,
@@ -25,7 +25,7 @@ import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import type { GitManagerServiceError } from "../Errors.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
+2 -2
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
buildBranchNamePrompt,
@@ -7,7 +7,7 @@ import {
buildThreadTitlePrompt,
} from "./Prompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
import { TextGenerationError } from "./Errors.ts";
import { TextGenerationError } from "@t3tools/contracts";
describe("buildCommitMessagePrompt", () => {
it("includes staged patch and summary in the prompt", () => {
+8 -8
View File
@@ -22,7 +22,7 @@ import type {
GitStatusResult,
} from "@t3tools/contracts";
import type { GitCommandError } from "../Errors.ts";
import type { GitCommandError } from "@t3tools/contracts";
export interface ExecuteGitInput {
readonly operation: string;
@@ -55,27 +55,27 @@ export interface GitPreparedCommitContext {
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void>;
readonly onStderrLine?: (line: string) => Effect.Effect<void>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void>;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void>;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void>;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
+1 -1
View File
@@ -9,7 +9,7 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProcessRunResult } from "../../processRunner";
import type { GitHubCliError } from "../Errors.ts";
import type { GitHubCliError } from "@t3tools/contracts";
export interface GitHubPullRequestSummary {
readonly number: number;
+2 -2
View File
@@ -19,10 +19,10 @@ import {
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "../Errors.ts";
import type { GitManagerServiceError } from "@t3tools/contracts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void>;
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
@@ -10,7 +10,7 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { TextGenerationError } from "../Errors.ts";
import type { TextGenerationError } from "@t3tools/contracts";
/** Providers that support git text generation (commit messages, PR content, branch names). */
export type TextGenerationProvider = "codex" | "claudeAgent";
+1 -1
View File
@@ -5,7 +5,7 @@
*/
import { Schema } from "effect";
import { TextGenerationError } from "./Errors.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { existsSync } from "node:fs";
import { join } from "node:path";
+197
View File
@@ -0,0 +1,197 @@
import Mime from "@effect/platform-node/Mime";
import { Effect, FileSystem, Option, Path } from "effect";
import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
import {
ATTACHMENTS_ROUTE_PREFIX,
normalizeAttachmentRelativePath,
resolveAttachmentRelativePath,
} from "./attachmentPaths";
import { resolveAttachmentPathById } from "./attachmentStore";
import { ServerConfig } from "./config";
import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
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>`;
export const attachmentsRouteLayer = HttpRouter.add(
"GET",
`${ATTACHMENTS_ROUTE_PREFIX}/*`,
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const config = yield* ServerConfig;
const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
if (!normalizedRelativePath) {
return HttpServerResponse.text("Invalid attachment path", { status: 400 });
}
const isIdLookup =
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
attachmentsDir: config.attachmentsDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
attachmentsDir: config.attachmentsDir,
relativePath: normalizedRelativePath,
});
if (!filePath) {
return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
status: isIdLookup ? 404 : 400,
});
}
const fileSystem = yield* FileSystem.FileSystem;
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
return HttpServerResponse.text("Not Found", { status: 404 });
}
return yield* HttpServerResponse.file(filePath, {
status: 200,
headers: {
"Cache-Control": "public, max-age=31536000, immutable",
},
}).pipe(
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
);
}),
);
export const projectFaviconRouteLayer = HttpRouter.add(
"GET",
"/api/project-favicon",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const projectCwd = url.value.searchParams.get("cwd");
if (!projectCwd) {
return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
}
const faviconResolver = yield* ProjectFaviconResolver;
const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
if (!faviconFilePath) {
return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
status: 200,
contentType: "image/svg+xml",
headers: {
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
},
});
}
return yield* HttpServerResponse.file(faviconFilePath, {
status: 200,
headers: {
"Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
},
}).pipe(
Effect.catch(() =>
Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
),
);
}),
);
export const staticAndDevRouteLayer = HttpRouter.add(
"GET",
"*",
Effect.gen(function* () {
const request = yield* HttpServerRequest.HttpServerRequest;
const url = HttpServerRequest.toURL(request);
if (Option.isNone(url)) {
return HttpServerResponse.text("Bad Request", { status: 400 });
}
const config = yield* ServerConfig;
if (config.devUrl) {
return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
}
if (!config.staticDir) {
return HttpServerResponse.text("No static directory configured and no dev URL set.", {
status: 503,
});
}
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const staticRoot = path.resolve(config.staticDir);
const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
const hasPathTraversalSegment = staticRelativePath.startsWith("..");
if (
staticRelativePath.length === 0 ||
hasRawLeadingParentSegment ||
hasPathTraversalSegment ||
staticRelativePath.includes("\0")
) {
return HttpServerResponse.text("Invalid static file path", { status: 400 });
}
const isWithinStaticRoot = (candidate: string) =>
candidate === staticRoot ||
candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
let filePath = path.resolve(staticRoot, staticRelativePath);
if (!isWithinStaticRoot(filePath)) {
return HttpServerResponse.text("Invalid static file path", { status: 400 });
}
const ext = path.extname(filePath);
if (!ext) {
filePath = path.resolve(filePath, "index.html");
if (!isWithinStaticRoot(filePath)) {
return HttpServerResponse.text("Invalid static file path", { status: 400 });
}
}
const fileInfo = yield* fileSystem
.stat(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!fileInfo || fileInfo.type !== "File") {
const indexPath = path.resolve(staticRoot, "index.html");
const indexData = yield* fileSystem
.readFile(indexPath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!indexData) {
return HttpServerResponse.text("Not Found", { status: 404 });
}
return HttpServerResponse.uint8Array(indexData, {
status: 200,
contentType: "text/html; charset=utf-8",
});
}
const contentType = Mime.getType(filePath) ?? "application/octet-stream";
const data = yield* fileSystem
.readFile(filePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!data) {
return HttpServerResponse.text("Internal Server Error", { status: 500 });
}
return HttpServerResponse.uint8Array(data, {
status: 200,
contentType,
});
}),
);
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { inferImageExtension, parseBase64DataUrl } from "./imageMime.ts";
-23
View File
@@ -1,23 +0,0 @@
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { CliConfig, t3Cli } from "./main";
import { OpenLive } from "./open";
import { Command } from "effect/unstable/cli";
import { version } from "../package.json" with { type: "json" };
import { ServerLive } from "./wsServer";
import { NetService } from "@t3tools/shared/Net";
import { FetchHttpClient } from "effect/unstable/http";
const RuntimeLayer = Layer.empty.pipe(
Layer.provideMerge(CliConfig.layer),
Layer.provideMerge(ServerLive),
Layer.provideMerge(OpenLive),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(FetchHttpClient.layer),
);
Command.run(t3Cli, { version }).pipe(Effect.provide(RuntimeLayer), NodeRuntime.runMain);
+1 -1
View File
@@ -8,13 +8,13 @@ import { ServerConfig } from "./config";
import {
DEFAULT_KEYBINDINGS,
Keybindings,
KeybindingsConfigError,
KeybindingsLive,
ResolvedKeybindingFromConfig,
compileResolvedKeybindingRule,
compileResolvedKeybindingsConfig,
parseKeybindingShortcut,
} from "./keybindings";
import { KeybindingsConfigError } from "@t3tools/contracts";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const makeKeybindingsLayer = () => {
+1 -13
View File
@@ -9,6 +9,7 @@
import {
KeybindingRule,
KeybindingsConfig,
KeybindingsConfigError,
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
@@ -46,19 +47,6 @@ import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
"KeybindingsConfigParseError",
{
configPath: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Unable to parse keybindings config at ${this.configPath}: ${this.detail}`;
}
}
type WhenToken =
| { type: "identifier"; value: string }
| { type: "not" }
-103
View File
@@ -1,103 +0,0 @@
import util from "node:util";
type LogLevel = "info" | "warn" | "error" | "event";
type LogContext = Record<string, unknown>;
const ANSI = {
reset: "\u001b[0m",
dim: "\u001b[2m",
cyan: "\u001b[36m",
yellow: "\u001b[33m",
red: "\u001b[31m",
magenta: "\u001b[35m",
} as const;
const LEVEL_LABEL: Record<LogLevel, string> = {
info: "INFO",
warn: "WARN",
error: "ERROR",
event: "EVENT",
};
const LEVEL_COLOR: Record<LogLevel, string> = {
info: ANSI.cyan,
warn: ANSI.yellow,
error: ANSI.red,
event: ANSI.magenta,
};
function useColors() {
return Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined;
}
function colorize(value: string, color: string, enabled: boolean) {
return enabled ? `${color}${value}${ANSI.reset}` : value;
}
function timeStamp() {
return new Date().toISOString().slice(11, 23);
}
function formatValue(value: unknown) {
if (typeof value === "string") {
return JSON.stringify(value);
}
if (
typeof value === "number" ||
typeof value === "boolean" ||
value === null ||
value === undefined
) {
return String(value);
}
return util.inspect(value, {
depth: 4,
breakLength: Infinity,
compact: true,
maxArrayLength: 25,
maxStringLength: 320,
});
}
function formatContext(context: LogContext | undefined) {
if (!context) return "";
const entries = Object.entries(context).filter(([, value]) => value !== undefined);
if (entries.length === 0) return "";
return entries.map(([key, value]) => `${key}=${formatValue(value)}`).join(" ");
}
function write(level: LogLevel, scope: string, message: string, context?: LogContext) {
const colorEnabled = useColors();
const ts = colorize(timeStamp(), ANSI.dim, colorEnabled);
const levelLabel = colorize(LEVEL_LABEL[level], LEVEL_COLOR[level], colorEnabled);
const contextText = formatContext(context);
const line = `${ts} ${levelLabel} [${scope}] ${message}${contextText ? ` ${contextText}` : ""}`;
if (level === "warn") {
console.warn(line);
return;
}
if (level === "error") {
console.error(line);
return;
}
console.log(line);
}
export function createLogger(scope: string) {
return {
info(message: string, context?: LogContext) {
write("info", scope, message, context);
},
warn(message: string, context?: LogContext) {
write("warn", scope, message, context);
},
error(message: string, context?: LogContext) {
write("error", scope, message, context);
},
event(message: string, context?: LogContext) {
write("event", scope, message, context);
},
};
}
-413
View File
@@ -1,413 +0,0 @@
import * as Http from "node:http";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it, vi } from "@effect/vitest";
import type { OrchestrationReadModel } from "@t3tools/contracts";
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 Command from "effect/unstable/cli/Command";
import { FetchHttpClient } from "effect/unstable/http";
import { beforeEach } from "vite-plus/test";
import { NetService } from "@t3tools/shared/Net";
import { CliConfig, recordStartupHeartbeat, t3Cli, type CliConfigShape } from "./main";
import { ServerConfig, type ServerConfigShape } from "./config";
import { Open, type OpenShape } from "./open";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { Server, type ServerShape } from "./wsServer";
import { ServerSettingsService } from "./serverSettings";
const start = vi.fn(() => undefined);
const stop = vi.fn(() => undefined);
const fixPath = vi.fn(() => undefined);
let resolvedConfig: ServerConfigShape | null = null;
const serverStart = Effect.acquireRelease(
Effect.gen(function* () {
resolvedConfig = yield* ServerConfig;
start();
return {} as unknown as Http.Server;
}),
() => Effect.sync(() => stop()),
);
const findAvailablePort = vi.fn((preferred: number) => Effect.succeed(preferred));
// Shared service layer used by this CLI test suite.
const testLayer = Layer.mergeAll(
Layer.succeed(CliConfig, {
cwd: "/tmp/t3-test-workspace",
fixPath: Effect.sync(fixPath),
resolveStaticDir: Effect.undefined,
} satisfies CliConfigShape),
Layer.succeed(NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
reserveLoopbackPort: () => Effect.succeed(0),
findAvailablePort,
}),
Layer.succeed(Server, {
start: serverStart,
stopSignal: Effect.void,
} satisfies ServerShape),
Layer.succeed(Open, {
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
ServerSettingsService.layerTest(),
AnalyticsService.layerTest,
FetchHttpClient.layer,
NodeServices.layer,
);
const runCli = (
args: ReadonlyArray<string>,
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
) => {
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
...env,
},
}),
),
),
);
};
beforeEach(() => {
vi.clearAllMocks();
resolvedConfig = null;
start.mockImplementation(() => undefined);
stop.mockImplementation(() => undefined);
fixPath.mockImplementation(() => undefined);
findAvailablePort.mockImplementation((preferred: number) => Effect.succeed(preferred));
});
it.layer(testLayer)("server CLI command", (it) => {
it.effect("parses all CLI flags and wires scoped start/stop", () =>
Effect.gen(function* () {
yield* runCli([
"--mode",
"desktop",
"--port",
"4010",
"--host",
"0.0.0.0",
"--home-dir",
"/tmp/t3-cli-home",
"--dev-url",
"http://127.0.0.1:5173",
"--no-browser",
"--auth-token",
"auth-secret",
]);
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4010);
assert.equal(resolvedConfig?.host, "0.0.0.0");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-cli-home");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-cli-home/dev");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "auth-secret");
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
assert.equal(resolvedConfig?.logWebSocketEvents, true);
assert.equal(stop.mock.calls.length, 1);
}),
);
it.effect("supports --token as an alias for --auth-token", () =>
Effect.gen(function* () {
yield* runCli(["--token", "token-secret"]);
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.authToken, "token-secret");
}),
);
it.effect("uses env fallbacks when flags are not provided", () =>
Effect.gen(function* () {
yield* runCli([], {
T3CODE_MODE: "desktop",
T3CODE_PORT: "4999",
T3CODE_HOST: "100.88.10.4",
T3CODE_HOME: "/tmp/t3-env-home",
VITE_DEV_SERVER_URL: "http://localhost:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "env-token",
});
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4999);
assert.equal(resolvedConfig?.host, "100.88.10.4");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-env-home/dev");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "env-token");
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
assert.equal(resolvedConfig?.logWebSocketEvents, true);
assert.equal(findAvailablePort.mock.calls.length, 0);
}),
);
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
});
it.effect("recognizes bootstrap fd from environment config", () =>
Effect.gen(function* () {
const fd = yield* openBootstrapFd({ authToken: "bootstrap-token" });
yield* runCli([], {
T3CODE_MODE: "web",
T3CODE_BOOTSTRAP_FD: String(fd),
T3CODE_AUTH_TOKEN: "env-token",
T3CODE_NO_BROWSER: "true",
});
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.mode, "web");
assert.equal(resolvedConfig?.authToken, "env-token");
}),
);
it.effect("uses bootstrap envelope values as fallbacks when CLI and env are absent", () =>
Effect.gen(function* () {
const fd = yield* openBootstrapFd({
mode: "desktop",
port: 4888,
host: "127.0.0.2",
t3Home: "/tmp/t3-bootstrap-home",
devUrl: "http://127.0.0.1:5173",
noBrowser: true,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: true,
});
yield* runCli([], {
T3CODE_BOOTSTRAP_FD: String(fd),
});
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.port, 4888);
assert.equal(resolvedConfig?.host, "127.0.0.2");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-bootstrap-home");
assert.equal(resolvedConfig?.stateDir, "/tmp/t3-bootstrap-home/dev");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "bootstrap-token");
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, false);
assert.equal(resolvedConfig?.logWebSocketEvents, true);
}),
);
it.effect("applies CLI then env precedence over bootstrap envelope values", () =>
Effect.gen(function* () {
const fd = yield* openBootstrapFd({
mode: "desktop",
port: 4888,
host: "127.0.0.2",
t3Home: "/tmp/t3-bootstrap-home",
devUrl: "http://127.0.0.1:5173",
noBrowser: false,
authToken: "bootstrap-token",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
yield* runCli(["--port", "4999", "--host", "0.0.0.0", "--auth-token", "cli-token"], {
T3CODE_MODE: "web",
T3CODE_BOOTSTRAP_FD: String(fd),
T3CODE_HOME: "/tmp/t3-env-home",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "true",
T3CODE_LOG_WS_EVENTS: "true",
});
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.mode, "web");
assert.equal(resolvedConfig?.port, 4999);
assert.equal(resolvedConfig?.host, "0.0.0.0");
assert.equal(resolvedConfig?.baseDir, "/tmp/t3-env-home");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "cli-token");
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
assert.equal(resolvedConfig?.logWebSocketEvents, true);
}),
);
it.effect("prefers --mode over T3CODE_MODE", () =>
Effect.gen(function* () {
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(4666));
yield* runCli(["--mode", "web"], {
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "true",
});
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.mode, "web");
assert.equal(resolvedConfig?.port, 4666);
assert.equal(resolvedConfig?.host, undefined);
}),
);
it.effect("prefers --no-browser over T3CODE_NO_BROWSER", () =>
Effect.gen(function* () {
yield* runCli(["--no-browser"], {
T3CODE_NO_BROWSER: "false",
});
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.noBrowser, true);
}),
);
it.effect("uses dynamic port discovery in web mode when port is omitted", () =>
Effect.gen(function* () {
findAvailablePort.mockImplementation((_preferred: number) => Effect.succeed(5444));
yield* runCli([]);
assert.deepStrictEqual(findAvailablePort.mock.calls, [[3773]]);
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.port, 5444);
assert.equal(resolvedConfig?.mode, "web");
}),
);
it.effect("uses fixed localhost defaults in desktop mode", () =>
Effect.gen(function* () {
yield* runCli([], {
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "true",
});
assert.equal(findAvailablePort.mock.calls.length, 0);
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.port, 3773);
assert.equal(resolvedConfig?.host, "127.0.0.1");
assert.equal(resolvedConfig?.mode, "desktop");
}),
);
it.effect("allows overriding desktop host with --host", () =>
Effect.gen(function* () {
yield* runCli(["--host", "0.0.0.0"], {
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "true",
});
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.mode, "desktop");
assert.equal(resolvedConfig?.host, "0.0.0.0");
}),
);
it.effect("supports CLI and env for bootstrap/log websocket toggles", () =>
Effect.gen(function* () {
yield* runCli(["--auto-bootstrap-project-from-cwd"], {
T3CODE_MODE: "desktop",
T3CODE_LOG_WS_EVENTS: "false",
T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD: "false",
T3CODE_NO_BROWSER: "true",
});
assert.equal(start.mock.calls.length, 1);
assert.equal(resolvedConfig?.autoBootstrapProjectFromCwd, true);
assert.equal(resolvedConfig?.logWebSocketEvents, false);
}),
);
it.effect("hydrates PATH before server startup", () =>
Effect.gen(function* () {
yield* runCli([]);
assert.equal(fixPath.mock.calls.length, 1);
assert.equal(start.mock.calls.length, 1);
const fixPathOrder = fixPath.mock.invocationCallOrder[0];
const startOrder = start.mock.invocationCallOrder[0];
if (typeof fixPathOrder !== "number" || typeof startOrder !== "number") {
assert.fail("Expected fixPath and start to be called");
}
assert.isTrue(fixPathOrder < startOrder);
}),
);
it.effect("records a startup heartbeat with thread/project counts", () =>
Effect.gen(function* () {
const recordTelemetry = vi.fn(
(_event: string, _properties?: Readonly<Record<string, unknown>>) => Effect.void,
);
const getSnapshot = vi.fn(() =>
Effect.succeed({
snapshotSequence: 2,
projects: [{} as OrchestrationReadModel["projects"][number]],
threads: [
{} as OrchestrationReadModel["threads"][number],
{} as OrchestrationReadModel["threads"][number],
],
updatedAt: new Date(1).toISOString(),
} satisfies OrchestrationReadModel),
);
yield* recordStartupHeartbeat.pipe(
Effect.provideService(ProjectionSnapshotQuery, {
getSnapshot,
}),
Effect.provideService(AnalyticsService, {
record: recordTelemetry,
flush: Effect.void,
}),
);
assert.deepEqual(recordTelemetry.mock.calls[0], [
"server.boot.heartbeat",
{
threadCount: 2,
projectCount: 1,
},
]);
}),
);
it.effect("does not start server for invalid --mode values", () =>
Effect.gen(function* () {
yield* runCli(["--mode", "invalid"]).pipe(Effect.catch(() => Effect.void));
assert.equal(start.mock.calls.length, 0);
assert.equal(stop.mock.calls.length, 0);
}),
);
it.effect("does not start server for invalid --dev-url values", () =>
Effect.gen(function* () {
yield* runCli(["--dev-url", "not-a-url"]).pipe(Effect.catch(() => Effect.void));
assert.equal(start.mock.calls.length, 0);
assert.equal(stop.mock.calls.length, 0);
}),
);
it.effect("does not start server for out-of-range --port values", () =>
Effect.gen(function* () {
yield* runCli(["--port", "70000"]).pipe(Effect.catch(() => Effect.void));
// effect/unstable/cli renders help/errors for parse failures and returns success.
assert.equal(start.mock.calls.length, 0);
assert.equal(stop.mock.calls.length, 0);
}),
);
});
-456
View File
@@ -1,456 +0,0 @@
/**
* CliConfig - CLI/runtime bootstrap service definitions.
*
* Defines startup-only service contracts used while resolving process config
* and constructing server runtime layers.
*
* @module CliConfig
*/
import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
import { Command, Flag } from "effect/unstable/cli";
import { NetService } from "@t3tools/shared/Net";
import {
DEFAULT_PORT,
deriveServerPaths,
resolveStaticDir,
ServerConfig,
type RuntimeMode,
type ServerConfigShape,
} from "./config";
import { fixPath, resolveBaseDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
import { Server } from "./wsServer";
import { ServerLoggerLive } from "./serverLogger";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
import { readBootstrapEnvelope } from "./bootstrap";
import { ServerSettingsLive } from "./serverSettings";
export class StartupError extends Data.TaggedError("StartupError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
const BootstrapEnvelopeSchema = Schema.Struct({
mode: Schema.optional(Schema.String),
port: Schema.optional(PortSchema),
host: Schema.optional(Schema.String),
t3Home: Schema.optional(Schema.String),
devUrl: Schema.optional(Schema.URLFromString),
noBrowser: Schema.optional(Schema.Boolean),
authToken: Schema.optional(Schema.String),
autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
logWebSocketEvents: Schema.optional(Schema.Boolean),
});
interface CliInput {
readonly mode: Option.Option<RuntimeMode>;
readonly port: Option.Option<number>;
readonly host: Option.Option<string>;
readonly t3Home: Option.Option<string>;
readonly devUrl: Option.Option<URL>;
readonly noBrowser: Option.Option<boolean>;
readonly authToken: Option.Option<string>;
readonly bootstrapFd: Option.Option<number>;
readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
readonly logWebSocketEvents: Option.Option<boolean>;
}
/**
* CliConfigShape - Startup helpers required while building server layers.
*/
export interface CliConfigShape {
/**
* Current process working directory.
*/
readonly cwd: string;
/**
* Apply OS-specific PATH normalization.
*/
readonly fixPath: Effect.Effect<void>;
/**
* Resolve static web asset directory for server mode.
*/
readonly resolveStaticDir: Effect.Effect<string | undefined>;
}
/**
* CliConfig - Service tag for startup CLI/runtime helpers.
*/
export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
"t3/main/CliConfig",
) {
static readonly layer = Layer.effect(
CliConfig,
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
return {
cwd: process.cwd(),
fixPath: Effect.sync(fixPath),
resolveStaticDir: resolveStaticDir().pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
),
} satisfies CliConfigShape;
}),
);
}
const CliEnvConfig = Config.all({
mode: Config.string("T3CODE_MODE").pipe(
Config.option,
Config.map(Option.map((value) => (value === "desktop" ? "desktop" : "web"))),
Config.map(Option.getOrUndefined),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
});
const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
const resolveOptionPrecedence = <Value>(
...values: ReadonlyArray<Option.Option<Value>>
): Option.Option<Value> => Option.firstSomeOf(values);
const isValidPort = (value: number): boolean => value >= 1 && value <= 65_535;
const isRuntimeMode = (value: string): value is RuntimeMode =>
value === "web" || value === "desktop";
const ServerConfigLive = (input: CliInput) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
const { findAvailablePort } = yield* NetService;
const env = yield* CliEnvConfig.asEffect().pipe(
Effect.mapError(
(cause) =>
new StartupError({ message: "Failed to read environment configuration", cause }),
),
);
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
: Option.none();
const mode: RuntimeMode = Option.getOrElse(
resolveOptionPrecedence(
input.mode,
Option.fromUndefinedOr(env.mode),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode),
),
),
() => "web",
);
const port = yield* Option.match(
resolveOptionPrecedence(
input.port,
Option.fromUndefinedOr(env.port),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort),
),
),
{
onSome: (value) => Effect.succeed(value),
onNone: () => {
if (mode === "desktop") {
return Effect.succeed(DEFAULT_PORT);
}
return findAvailablePort(DEFAULT_PORT);
},
},
);
const devUrl = Option.getOrElse(
resolveOptionPrecedence(
input.devUrl,
Option.fromUndefinedOr(env.devUrl),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.devUrl),
),
),
() => undefined,
);
const baseDir = yield* resolveBaseDir(
Option.getOrUndefined(
resolveOptionPrecedence(
input.t3Home,
Option.fromUndefinedOr(env.t3Home),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.t3Home),
),
),
),
);
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
const noBrowser = resolveBooleanFlag(
input.noBrowser,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.noBrowser),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.noBrowser),
),
),
() => mode === "desktop",
),
);
const authToken = resolveOptionPrecedence(
input.authToken,
Option.fromUndefinedOr(env.authToken),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.authToken),
),
);
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
input.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
);
const logWebSocketEvents = resolveBooleanFlag(
input.logWebSocketEvents,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.logWebSocketEvents),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
),
),
() => Boolean(devUrl),
),
);
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
const host = Option.getOrElse(
resolveOptionPrecedence(
input.host,
Option.fromUndefinedOr(env.host),
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
),
() => (mode === "desktop" ? "127.0.0.1" : undefined),
);
const config: ServerConfigShape = {
mode,
port,
cwd: cliConfig.cwd,
host,
baseDir,
...derivedPaths,
staticDir,
devUrl,
noBrowser,
authToken: Option.getOrUndefined(authToken),
autoBootstrapProjectFromCwd,
logWebSocketEvents,
} satisfies ServerConfigShape;
return config;
}),
);
const LayerLive = (input: CliInput) =>
Layer.empty.pipe(
Layer.provideMerge(makeServerRuntimeServicesLayer()),
Layer.provideMerge(makeServerProviderLayer()),
Layer.provideMerge(ProviderRegistryLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerLoggerLive),
Layer.provideMerge(AnalyticsServiceLayerLive),
Layer.provideMerge(ServerSettingsLive),
Layer.provideMerge(ServerConfigLive(input)),
);
const isWildcardHost = (host: string | undefined): boolean =>
host === "0.0.0.0" || host === "::" || host === "[::]";
const formatHostForUrl = (host: string): string =>
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
export const recordStartupHeartbeat = Effect.gen(function* () {
const analytics = yield* AnalyticsService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
Effect.map((snapshot) => ({
threadCount: snapshot.threads.length,
projectCount: snapshot.projects.length,
})),
Effect.catch((cause) =>
Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
Effect.as({
threadCount: 0,
projectCount: 0,
}),
),
),
);
yield* analytics.record("server.boot.heartbeat", {
threadCount,
projectCount,
});
});
const makeServerRuntimeProgram = (input: CliInput) =>
Effect.gen(function* () {
const { start, stopSignal } = yield* Server;
const openDeps = yield* Open;
const config = yield* ServerConfig;
if (!config.devUrl && !config.staticDir) {
yield* Effect.logWarning(
"web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
{
hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
},
);
}
yield* start;
yield* Effect.forkChild(recordStartupHeartbeat);
const localUrl = `http://localhost:${config.port}`;
const bindUrl =
config.host && !isWildcardHost(config.host)
? `http://${formatHostForUrl(config.host)}:${config.port}`
: localUrl;
const { authToken, devUrl, ...safeConfig } = config;
yield* Effect.logInfo("T3 Code running", {
...safeConfig,
devUrl: devUrl?.toString(),
authEnabled: Boolean(authToken),
});
if (!config.noBrowser) {
const target = config.devUrl?.toString() ?? bindUrl;
yield* openDeps.openBrowser(target).pipe(
Effect.catch(() =>
Effect.logInfo("browser auto-open unavailable", {
hint: `Open ${target} in your browser.`,
}),
),
);
}
return yield* stopSignal;
}).pipe(Effect.provide(LayerLive(input)));
const makeServerProgram = (input: CliInput) =>
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
yield* cliConfig.fixPath;
return yield* makeServerRuntimeProgram(input);
});
/**
* These flags mirrors the environment variables and the config shape.
*/
const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
Flag.optional,
);
const portFlag = Flag.integer("port").pipe(
Flag.withSchema(PortSchema),
Flag.withDescription("Port for the HTTP/WebSocket server."),
Flag.optional,
);
const hostFlag = Flag.string("host").pipe(
Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
Flag.optional,
);
const t3HomeFlag = Flag.string("home-dir").pipe(
Flag.withDescription("Base directory for all T3 Code data (equivalent to T3CODE_HOME)."),
Flag.optional,
);
const devUrlFlag = Flag.string("dev-url").pipe(
Flag.withSchema(Schema.URLFromString),
Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
Flag.optional,
);
const noBrowserFlag = Flag.boolean("no-browser").pipe(
Flag.withDescription("Disable automatic browser opening."),
Flag.optional,
);
const authTokenFlag = Flag.string("auth-token").pipe(
Flag.withDescription("Auth token required for WebSocket connections."),
Flag.withAlias("token"),
Flag.optional,
);
const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
Flag.withSchema(Schema.Int),
Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
Flag.optional,
);
const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
Flag.withDescription(
"Create a project for the current working directory on startup when missing.",
),
Flag.optional,
);
const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
Flag.withDescription(
"Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
),
Flag.withAlias("log-ws-events"),
Flag.optional,
);
export const t3Cli = Command.make("t3", {
mode: modeFlag,
port: portFlag,
host: hostFlag,
t3Home: t3HomeFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
}).pipe(
Command.withDescription("Run the T3 Code server."),
Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
);
+20 -1
View File
@@ -31,6 +31,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["/tmp/workspace"],
});
const traeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLaunch, {
command: "trae",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
@@ -89,6 +98,15 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const traeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "trae" },
"darwin",
);
assert.deepEqual(traeLineAndColumn, {
command: "trae",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
@@ -256,6 +274,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
yield* fs.writeFileString(path.join(dir, "trae.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
@@ -263,7 +282,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
+3 -6
View File
@@ -10,17 +10,14 @@ import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Effect, Layer } from "effect";
// ==============================
// Definitions
// ==============================
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
export { OpenError };
export interface OpenInEditorInput {
readonly cwd: string;
@@ -15,7 +15,7 @@ import {
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
@@ -39,6 +39,7 @@ import {
import { checkpointRefForThreadTurn } from "../../checkpointing/Utils.ts";
import { ServerConfig } from "../../config.ts";
import { WorkspaceEntriesLive } from "../../workspace/Layers/WorkspaceEntries.ts";
import { WorkspacePathsLive } from "../../workspace/Layers/WorkspacePaths.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
@@ -69,7 +70,7 @@ function createProviderServiceHarness(
);
const unsupported = <A>() =>
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A>;
Effect.die(new Error("Unsupported provider call in test")) as Effect.Effect<A, never>;
const listSessions = () =>
hasSession
? Effect.succeed([
@@ -94,7 +95,9 @@ function createProviderServiceHarness(
listSessions,
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation,
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const emit = (event: LegacyProviderRuntimeEvent): void => {
@@ -115,7 +118,7 @@ async function waitForThread(
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
timeoutMs = 5000,
timeoutMs = 15_000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<{
@@ -140,7 +143,7 @@ async function waitForThread(
async function waitForEvent(
engine: OrchestrationEngineShape,
predicate: (event: { type: string }) => boolean,
timeoutMs = 5000,
timeoutMs = 15_000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async () => {
@@ -191,7 +194,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 5000) {
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (gitRefExists(cwd, ref)) {
@@ -263,7 +266,8 @@ describe("CheckpointReactor", () => {
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(WorkspaceEntriesLive),
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
@@ -1007,18 +1011,7 @@ describe("CheckpointReactor", () => {
}),
);
const deadline = Date.now() + 2000;
const waitForRollbackCalls = async (): Promise<void> => {
if (harness.provider.rollbackConversation.mock.calls.length >= 2) {
return;
}
if (Date.now() >= deadline) {
throw new Error("Timed out waiting for rollbackConversation calls.");
}
await new Promise((resolve) => setTimeout(resolve, 10));
return waitForRollbackCalls();
};
await waitForRollbackCalls();
await harness.drain();
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
@@ -499,21 +499,8 @@ const make = Effect.gen(function* () {
});
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
event: Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" | "thread.message-sent" }
>,
event: Extract<OrchestrationEvent, { type: "thread.turn-start-requested" }>,
) {
if (event.type === "thread.message-sent") {
if (
event.payload.role !== "user" ||
event.payload.streaming ||
event.payload.turnId !== null
) {
return;
}
}
const threadId = event.payload.threadId;
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
@@ -686,7 +673,7 @@ const make = Effect.gen(function* () {
});
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
if (event.type === "thread.turn-start-requested") {
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
return;
}
@@ -748,7 +735,7 @@ const make = Effect.gen(function* () {
const processInput = (
input: ReactorInput,
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError> =>
): Effect.Effect<void, CheckpointStoreError | OrchestrationDispatchError, never> =>
input.source === "domain" ? processDomainEvent(input.event) : processRuntimeEvent(input.event);
const processInputSafely = (input: ReactorInput) =>
@@ -772,7 +759,6 @@ const make = Effect.gen(function* () {
Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => {
if (
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.message-sent" &&
event.type !== "thread.checkpoint-revert-requested" &&
event.type !== "thread.turn-diff-completed"
) {
@@ -9,7 +9,7 @@ import {
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -205,7 +205,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
yield* Effect.log("orchestration engine started").pipe(
yield* Effect.logDebug("orchestration engine started").pipe(
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
);
@@ -1,5 +1,5 @@
import { Effect, Exit, Layer, ManagedRuntime, Scope } from "effect";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it } from "vitest";
import { CheckpointReactor } from "../Services/CheckpointReactor.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
@@ -3,7 +3,6 @@ import {
type ChatAttachment,
type OrchestrationEvent,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer, Option, Path, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -624,31 +623,46 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
const existingRows = yield* projectionThreadMessageRepository.listByThreadId({
threadId: event.payload.threadId,
});
const existingMessage = existingRows.find(
(row) => row.messageId === event.payload.messageId,
);
const nextText =
existingMessage && event.payload.streaming
? `${existingMessage.text}${event.payload.text}`
: existingMessage && event.payload.text.length === 0
? existingMessage.text
: event.payload.text;
const nextAttachments =
event.payload.attachments !== undefined
? yield* materializeAttachmentsForProjection({
attachments: event.payload.attachments,
})
: existingMessage?.attachments;
: undefined;
if (event.payload.streaming) {
yield* projectionThreadMessageRepository.appendTextDelta({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
role: event.payload.role,
delta: event.payload.text,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: true,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
}
const existingMessage = yield* projectionThreadMessageRepository
.getByMessageId({
messageId: event.payload.messageId,
})
.pipe(Effect.map(Option.getOrUndefined));
const nextText =
existingMessage !== undefined && event.payload.text.length === 0
? existingMessage.text
: event.payload.text;
const persistedAttachments = nextAttachments ?? existingMessage?.attachments;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
role: event.payload.role,
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
...(persistedAttachments !== undefined
? { attachments: [...persistedAttachments] }
: {}),
isStreaming: event.payload.streaming,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -1271,7 +1285,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.tap(() =>
Effect.log("orchestration projection pipeline bootstrapped").pipe(
Effect.logDebug("orchestration projection pipeline bootstrapped").pipe(
Effect.annotateLogs({ projectors: projectors.length }),
),
),
@@ -1291,7 +1305,6 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
OrchestrationProjectionPipeline,
makeOrchestrationProjectionPipeline(),
).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ProjectionProjectRepositoryLive),
Layer.provideMerge(ProjectionThreadRepositoryLive),
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
@@ -14,10 +14,10 @@ import {
TurnId,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../../git/Errors.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -207,7 +207,9 @@ describe("ProviderCommandReactor", () => {
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
}),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -724,39 +724,40 @@ const make = Effect.gen(function* () {
});
});
const processDomainEvent = (event: ProviderIntentEvent) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread?.session || thread.session.status === "stopped") {
return;
}
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
event: ProviderIntentEvent,
) {
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread?.session || thread.session.status === "stopped") {
return;
}
case "thread.turn-start-requested":
yield* processTurnStartRequested(event);
return;
case "thread.turn-interrupt-requested":
yield* processTurnInterruptRequested(event);
return;
case "thread.approval-response-requested":
yield* processApprovalResponseRequested(event);
return;
case "thread.user-input-response-requested":
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
return;
}
});
case "thread.turn-start-requested":
yield* processTurnStartRequested(event);
return;
case "thread.turn-interrupt-requested":
yield* processTurnInterruptRequested(event);
return;
case "thread.approval-response-requested":
yield* processApprovalResponseRequested(event);
return;
case "thread.user-input-response-requested":
yield* processUserInputResponseRequested(event);
return;
case "thread.session-stop-requested":
yield* processSessionStopRequested(event);
return;
}
});
const processDomainEventSafely = (event: ProviderIntentEvent) =>
processDomainEvent(event).pipe(
@@ -20,7 +20,7 @@ import {
TurnId,
} from "@t3tools/contracts";
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it } from "vitest";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -97,7 +97,9 @@ function createProviderServiceHarness() {
listSessions: () => Effect.succeed([...runtimeSessions]),
getCapabilities: () => Effect.succeed({ sessionModelSwitch: "in-session" }),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
get streamEvents() {
return Stream.fromPubSub(runtimeEventPubSub);
},
};
const setSession = (session: ProviderSession): void => {
@@ -1626,7 +1628,8 @@ describe("ProviderRuntimeIngestion", () => {
return false;
}
return (
event.payload.messageId === "assistant:item-complete-dedup" && !event.payload.streaming
event.payload.messageId === "assistant:item-complete-dedup" &&
event.payload.streaming === false
);
});
expect(completionEvents).toHaveLength(1);
@@ -11,7 +11,9 @@ const makeRuntimeReceiptBus = Effect.gen(function* () {
return {
publish: (receipt) => PubSub.publish(pubSub, receipt).pipe(Effect.asVoid),
stream: Stream.fromPubSub(pubSub),
get stream() {
return Stream.fromPubSub(pubSub);
},
} satisfies RuntimeReceiptBusShape;
});
+121
View File
@@ -0,0 +1,121 @@
import { Effect, FileSystem, Path } from "effect";
import {
type ClientOrchestrationCommand,
type OrchestrationCommand,
OrchestrationDispatchCommandError,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore";
import { ServerConfig } from "../config";
import { parseBase64DataUrl } from "../imageMime";
import { WorkspacePaths } from "../workspace/Services/WorkspacePaths";
export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const workspacePaths = yield* WorkspacePaths;
const normalizeProjectWorkspaceRoot = (workspaceRoot: string) =>
workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
Effect.mapError(
(cause) =>
new OrchestrationDispatchCommandError({
message: cause.message,
}),
),
);
if (command.type === "project.create") {
return {
...command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
} satisfies OrchestrationCommand;
}
if (command.type === "project.meta.update" && command.workspaceRoot !== undefined) {
return {
...command,
workspaceRoot: yield* normalizeProjectWorkspaceRoot(command.workspaceRoot),
} satisfies OrchestrationCommand;
}
if (command.type !== "thread.turn.start") {
return command as OrchestrationCommand;
}
const normalizedAttachments = yield* Effect.forEach(
command.message.attachments,
(attachment) =>
Effect.gen(function* () {
const parsed = parseBase64DataUrl(attachment.dataUrl);
if (!parsed || !parsed.mimeType.startsWith("image/")) {
return yield* new OrchestrationDispatchCommandError({
message: `Invalid image attachment payload for '${attachment.name}'.`,
});
}
const bytes = Buffer.from(parsed.base64, "base64");
if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
return yield* new OrchestrationDispatchCommandError({
message: `Image attachment '${attachment.name}' is empty or too large.`,
});
}
const attachmentId = createAttachmentId(command.threadId);
if (!attachmentId) {
return yield* new OrchestrationDispatchCommandError({
message: "Failed to create a safe attachment id.",
});
}
const persistedAttachment = {
type: "image" as const,
id: attachmentId,
name: attachment.name,
mimeType: parsed.mimeType.toLowerCase(),
sizeBytes: bytes.byteLength,
};
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
attachment: persistedAttachment,
});
if (!attachmentPath) {
return yield* new OrchestrationDispatchCommandError({
message: `Failed to resolve persisted path for '${attachment.name}'.`,
});
}
yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
Effect.mapError(
() =>
new OrchestrationDispatchCommandError({
message: `Failed to create attachment directory for '${attachment.name}'.`,
}),
),
);
yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
Effect.mapError(
() =>
new OrchestrationDispatchCommandError({
message: `Failed to persist attachment '${attachment.name}'.`,
}),
),
);
return persistedAttachment;
}),
{ concurrency: 1 },
);
return {
...command,
message: {
...command.message,
attachments: normalizedAttachments,
},
} satisfies OrchestrationCommand;
});
@@ -30,7 +30,7 @@ export interface OrchestrationEngineShape {
*
* @returns Effect containing the latest read model.
*/
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never>;
readonly getReadModel: () => Effect.Effect<OrchestrationReadModel, never, never>;
/**
* Replay persisted orchestration events from an exclusive sequence cursor.
@@ -40,7 +40,7 @@ export interface OrchestrationEngineShape {
*/
readonly readEvents: (
fromSequenceExclusive: number,
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError>;
) => Stream.Stream<OrchestrationEvent, OrchestrationEventStoreError, never>;
/**
* Dispatch a validated orchestration command.
@@ -53,7 +53,7 @@ export interface OrchestrationEngineShape {
*/
readonly dispatch: (
command: OrchestrationCommand,
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError>;
) => Effect.Effect<{ sequence: number }, OrchestrationDispatchError, never>;
/**
* Stream persisted domain events in dispatch order.
@@ -1,4 +1,4 @@
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import {
MessageId,
CommandId,
@@ -6,7 +6,7 @@ import {
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { Effect } from "effect";
import { decideOrchestrationCommand } from "./decider.ts";
+1 -1
View File
@@ -679,7 +679,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
default: {
command satisfies never;
const fallback = command as { type: string };
const fallback = command as never as { type: string };
return yield* new OrchestrationCommandInvariantError({
commandType: fallback.type,
detail: `Unknown command type: ${fallback.type}`,
@@ -6,7 +6,7 @@ import {
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect } from "effect";
import { describe, expect, it } from "vite-plus/test";
import { describe, expect, it } from "vitest";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
+1 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it, vi } from "vite-plus/test";
import { describe, expect, it, vi } from "vitest";
import { fixPath } from "./os-jank";
@@ -0,0 +1,188 @@
import { afterEach, describe, expect, it } from "vitest";
import { Effect, Stream } from "effect";
import { PERF_CATALOG_IDS } from "@t3tools/shared/perf/scenarioCatalog";
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
const STREAM_SAMPLE_EVENT_COUNT = 96;
describe("PerfProviderAdapter", () => {
const previousScenarioEnv = process.env[PERF_SCENARIO_ENV];
afterEach(() => {
if (previousScenarioEnv === undefined) {
delete process.env[PERF_SCENARIO_ENV];
return;
}
process.env[PERF_SCENARIO_ENV] = previousScenarioEnv;
});
it("emits canonical runtime events for the dense assistant stream scenario", async () => {
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
const adapter = await Effect.runPromise(makePerfProviderAdapter);
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
await Effect.runPromise(
adapter.startSession({
threadId,
provider: "codex",
runtimeMode: "full-access",
}),
);
const firstEventsPromise = Effect.runPromise(
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
);
await Effect.runPromise(
adapter.sendTurn({
threadId,
input: "exercise the dense perf scenario",
attachments: [],
}),
);
const firstEvents = Array.from(await firstEventsPromise);
expect(firstEvents.filter((event) => event.type === "turn.started")).toHaveLength(3);
expect(new Set(firstEvents.slice(0, 18).map((event) => String(event.threadId)))).toEqual(
new Set([
String(threadId),
String(PERF_CATALOG_IDS.burstBase.navigationThreadId),
String(PERF_CATALOG_IDS.burstBase.fillerThreadId),
]),
);
expect(
firstEvents.some(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
event.type === "content.delta" &&
event.payload.delta.includes("Navigation lane"),
),
).toBe(true);
expect(
firstEvents.some(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message",
),
).toBe(true);
expect(
firstEvents.some(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.fillerThreadId &&
event.type === "item.updated" &&
event.payload.itemType === "command_execution",
),
).toBe(true);
const firstBurstFollowupCompletionIndex = firstEvents.findIndex(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message" &&
String(event.itemId ?? "").includes("followup"),
);
const burstWorklogIdsBeforeFollowup = new Set(
firstEvents
.slice(0, firstBurstFollowupCompletionIndex)
.filter(
(event) =>
event.threadId === threadId &&
event.type === "item.started" &&
event.payload.itemType === "command_execution",
)
.map((event) => String(event.itemId)),
);
const burstAssistantMessageLengths = firstEvents
.flatMap((event) => {
if (
event.threadId !== threadId ||
event.type !== "item.completed" ||
event.payload.itemType !== "assistant_message" ||
event.payload.detail === undefined
) {
return [];
}
return [event.payload.detail.length];
})
.slice(0, 4);
expect(firstBurstFollowupCompletionIndex).toBeGreaterThan(0);
expect(burstWorklogIdsBeforeFollowup.size).toBeGreaterThanOrEqual(3);
expect(new Set(burstAssistantMessageLengths).size).toBeGreaterThan(1);
});
it("assigns fresh runtime ids when the same burst thread is sent twice", async () => {
process.env[PERF_SCENARIO_ENV] = "dense_assistant_stream";
const adapter = await Effect.runPromise(makePerfProviderAdapter);
const threadId = PERF_CATALOG_IDS.burstBase.burstThreadId;
await Effect.runPromise(
adapter.startSession({
threadId,
provider: "codex",
runtimeMode: "full-access",
}),
);
const firstEventsPromise = Effect.runPromise(
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
);
await Effect.runPromise(
adapter.sendTurn({
threadId,
input: "first dense perf pass",
attachments: [],
}),
);
const firstEvents = Array.from(await firstEventsPromise);
const secondEventsPromise = Effect.runPromise(
Stream.runCollect(Stream.take(adapter.streamEvents, STREAM_SAMPLE_EVENT_COUNT)),
);
await Effect.runPromise(
adapter.sendTurn({
threadId,
input: "second dense perf pass",
attachments: [],
}),
);
const secondEvents = Array.from(await secondEventsPromise);
const firstNavigationTurnStarted = firstEvents.find(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
event.type === "turn.started",
);
const secondNavigationTurnStarted = secondEvents.find(
(event) =>
event.threadId === PERF_CATALOG_IDS.burstBase.navigationThreadId &&
event.type === "turn.started",
);
const firstBurstAssistantCompletion = firstEvents.find(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message",
);
const secondBurstAssistantCompletion = secondEvents.find(
(event) =>
event.threadId === threadId &&
event.type === "item.completed" &&
event.payload.itemType === "assistant_message",
);
const secondRunNamespaceSuffix = `--perf-run-${String(threadId)}-0002`;
expect(firstNavigationTurnStarted?.turnId).toBe(PERF_CATALOG_IDS.provider.navigationLiveTurnId);
expect(firstBurstAssistantCompletion?.itemId).toBeDefined();
expect(secondNavigationTurnStarted?.turnId).toBeDefined();
expect(secondBurstAssistantCompletion?.itemId).toBeDefined();
expect(secondNavigationTurnStarted?.turnId).not.toBe(firstNavigationTurnStarted?.turnId);
expect(secondBurstAssistantCompletion?.itemId).not.toBe(firstBurstAssistantCompletion?.itemId);
expect(String(secondNavigationTurnStarted?.turnId)).toContain(secondRunNamespaceSuffix);
expect(String(secondBurstAssistantCompletion?.itemId)).toContain(secondRunNamespaceSuffix);
});
});
+456
View File
@@ -0,0 +1,456 @@
import {
EventId,
RuntimeItemId,
RuntimeRequestId,
RuntimeSessionId,
TurnId,
type ApprovalRequestId,
type ProviderApprovalDecision,
type ProviderRuntimeEvent,
type ProviderSendTurnInput,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderTurnStartResult,
type ProviderUserInputAnswers,
type ThreadId,
} from "@t3tools/contracts";
import { Effect, Queue, Stream } from "effect";
import {
getPerfProviderScenario,
type PerfProviderScenario,
type TimedFixtureProviderRuntimeEvent,
} from "@t3tools/shared/perf/scenarioCatalog";
import {
ProviderAdapterSessionNotFoundError,
ProviderAdapterValidationError,
type ProviderAdapterError,
} from "../provider/Errors.ts";
import type {
ProviderAdapterShape,
ProviderThreadSnapshot,
ProviderThreadTurnSnapshot,
} from "../provider/Services/ProviderAdapter.ts";
import { getPerfProviderScenarioId } from "./config.ts";
interface PerfSessionState {
session: ProviderSession;
snapshot: ProviderThreadSnapshot;
turnCount: number;
pendingTimers: Set<ReturnType<typeof setTimeout>>;
}
function nowIso(): string {
return new Date().toISOString();
}
function sessionNotFound(threadId: ThreadId): ProviderAdapterSessionNotFoundError {
return new ProviderAdapterSessionNotFoundError({
provider: "codex",
threadId: String(threadId),
});
}
function resolvePerfScenario(inputText: string | undefined): PerfProviderScenario {
const scenarioId = getPerfProviderScenarioId();
if (scenarioId) {
return getPerfProviderScenario(scenarioId);
}
const trimmedInput = inputText?.trim() || "perf request";
return {
id: "dense_assistant_stream",
provider: "codex",
sentinelText: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
totalDurationMs: 48,
events: [
{
delayMs: 0,
type: "turn.started",
payload: {
model: "gpt-5.4",
},
},
{
delayMs: 16,
type: "content.delta",
payload: {
streamKind: "assistant_text",
delta: `Perf fallback response for: ${trimmedInput}. `,
},
},
{
delayMs: 32,
type: "content.delta",
payload: {
streamKind: "assistant_text",
delta: `PERF_STREAM_SENTINEL:fallback:${trimmedInput}`,
},
},
{
delayMs: 48,
type: "turn.completed",
payload: {
state: "completed",
},
},
],
};
}
function toIdleSession(session: ProviderSession, updatedAt: string): ProviderSession {
const { activeTurnId: _activeTurnId, ...rest } = session;
return {
...rest,
status: "ready",
updatedAt,
};
}
function namespacePerfFixtureId(
baseId: string,
sourceThreadId: ThreadId,
runIndex: number,
): string {
return `${baseId}--perf-run-${String(sourceThreadId)}-${runIndex.toString().padStart(4, "0")}`;
}
function buildRuntimeEvent(input: {
readonly template: TimedFixtureProviderRuntimeEvent;
readonly threadId: ThreadId;
readonly turnId: TurnId;
readonly startedAtMs: number;
readonly index: number;
readonly runIndex: number;
}): ProviderRuntimeEvent {
const eventThreadId = input.template.threadId ?? input.threadId;
const eventTurnId =
input.template.turnId === undefined
? input.turnId
: input.runIndex === 1
? input.template.turnId
: TurnId.makeUnsafe(
namespacePerfFixtureId(String(input.template.turnId), input.threadId, input.runIndex),
);
const createdAt = new Date(input.startedAtMs + (input.template.delayMs ?? 0)).toISOString();
return {
type: input.template.type,
eventId: EventId.makeUnsafe(
`perf-runtime:${String(eventThreadId)}:${String(eventTurnId)}:${input.index.toString().padStart(4, "0")}`,
),
provider: "codex",
threadId: eventThreadId,
turnId: eventTurnId,
createdAt,
...(input.template.itemId
? {
itemId: RuntimeItemId.makeUnsafe(
input.runIndex === 1
? input.template.itemId
: namespacePerfFixtureId(input.template.itemId, input.threadId, input.runIndex),
),
}
: {}),
...(input.template.requestId
? {
requestId: RuntimeRequestId.makeUnsafe(
input.runIndex === 1
? input.template.requestId
: namespacePerfFixtureId(input.template.requestId, input.threadId, input.runIndex),
),
}
: {}),
payload: input.template.payload,
} as ProviderRuntimeEvent;
}
export const makePerfProviderAdapter = Effect.gen(function* () {
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
const sessions = new Map<ThreadId, PerfSessionState>();
const clearPendingTimers = (threadId: ThreadId) =>
Effect.sync(() => {
const state = sessions.get(threadId);
if (!state) {
return;
}
for (const timer of state.pendingTimers) {
clearTimeout(timer);
}
state.pendingTimers.clear();
});
const scheduleRuntimeEvent = (input: {
readonly state: PerfSessionState;
readonly event: ProviderRuntimeEvent;
readonly delayMs: number;
readonly onAfterEmit?: () => void;
}) =>
Effect.sync(() => {
const timer = setTimeout(() => {
input.state.pendingTimers.delete(timer);
Effect.runFork(
Queue.offer(runtimeEvents, input.event).pipe(
Effect.tap(() => Effect.sync(() => input.onAfterEmit?.())),
Effect.asVoid,
),
);
}, input.delayMs);
input.state.pendingTimers.add(timer);
});
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (
input: ProviderSessionStartInput,
) =>
Effect.gen(function* () {
if (input.provider !== undefined && input.provider !== "codex") {
return yield* new ProviderAdapterValidationError({
provider: "codex",
operation: "startSession",
issue: `Perf provider only supports codex sessions, received '${input.provider}'.`,
});
}
const createdAt = nowIso();
const session: ProviderSession = {
provider: "codex",
status: "ready",
runtimeMode: input.runtimeMode,
threadId: input.threadId,
...(input.cwd ? { cwd: input.cwd } : {}),
...(input.modelSelection?.model ? { model: input.modelSelection.model } : {}),
resumeCursor:
input.resumeCursor ??
RuntimeSessionId.makeUnsafe(`perf-resume:${String(input.threadId)}:${Date.now()}`),
createdAt,
updatedAt: createdAt,
};
sessions.set(input.threadId, {
session,
snapshot: {
threadId: input.threadId,
turns: [],
},
turnCount: 0,
pendingTimers: new Set(),
});
return session;
});
const sendTurn: ProviderAdapterShape<ProviderAdapterError>["sendTurn"] = (
input: ProviderSendTurnInput,
) =>
Effect.gen(function* () {
const state = sessions.get(input.threadId);
if (!state) {
return yield* Effect.fail(sessionNotFound(input.threadId));
}
yield* clearPendingTimers(input.threadId);
state.turnCount += 1;
const turnId = TurnId.makeUnsafe(
`perf-turn:${String(input.threadId)}:${state.turnCount.toString().padStart(4, "0")}`,
);
const scenario = resolvePerfScenario(input.input);
const startedAtMs = Date.now();
const sentAt = new Date(startedAtMs).toISOString();
state.session = {
...state.session,
status: "running",
activeTurnId: turnId,
updatedAt: sentAt,
};
const userTurnItem = {
type: "userMessage",
content: [{ type: "text", text: input.input ?? "" }],
} as const;
const nextTurn: ProviderThreadTurnSnapshot = {
id: turnId,
items: [userTurnItem],
};
state.snapshot = {
threadId: state.snapshot.threadId,
turns: [...state.snapshot.turns, nextTurn],
};
let assistantText = "";
const updateAssistantSnapshot = (completedAt: string) => {
state.session = toIdleSession(state.session, completedAt);
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.map((turn) =>
turn.id === turnId
? {
...turn,
items:
assistantText.length > 0
? [...turn.items, { type: "agentMessage", text: assistantText }]
: turn.items,
}
: turn,
),
};
};
yield* Effect.forEach(
scenario.events,
(template, index) => {
const event = buildRuntimeEvent({
template,
threadId: input.threadId,
turnId,
startedAtMs,
index,
runIndex: state.turnCount,
});
const delayMs = template.delayMs ?? 0;
return scheduleRuntimeEvent({
state,
event,
delayMs,
onAfterEmit: () => {
if (
event.threadId === input.threadId &&
event.type === "content.delta" &&
event.payload.streamKind === "assistant_text"
) {
assistantText += event.payload.delta;
}
if (event.threadId === input.threadId && event.type === "turn.completed") {
updateAssistantSnapshot(event.createdAt);
}
},
});
},
{ concurrency: 1 },
);
return {
threadId: input.threadId,
turnId,
} satisfies ProviderTurnStartResult;
});
const interruptTurn: ProviderAdapterShape<ProviderAdapterError>["interruptTurn"] = (
threadId,
turnId,
) =>
Effect.gen(function* () {
const state = sessions.get(threadId);
if (!state) {
return yield* Effect.fail(sessionNotFound(threadId));
}
yield* clearPendingTimers(threadId);
const interruptedTurnId = turnId ?? state.session.activeTurnId;
state.session = toIdleSession(state.session, nowIso());
if (interruptedTurnId) {
yield* Queue.offer(runtimeEvents, {
type: "turn.completed",
eventId: EventId.makeUnsafe(
`perf-runtime:${String(threadId)}:${String(interruptedTurnId)}:interrupted`,
),
provider: "codex",
threadId,
turnId: interruptedTurnId,
createdAt: nowIso(),
payload: {
state: "interrupted",
},
} satisfies ProviderRuntimeEvent);
}
});
const respondToRequest: ProviderAdapterShape<ProviderAdapterError>["respondToRequest"] = (
threadId,
_requestId: ApprovalRequestId,
_decision: ProviderApprovalDecision,
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
const respondToUserInput: ProviderAdapterShape<ProviderAdapterError>["respondToUserInput"] = (
threadId,
_requestId,
_answers: ProviderUserInputAnswers,
) => (sessions.has(threadId) ? Effect.void : Effect.fail(sessionNotFound(threadId)));
const stopSession: ProviderAdapterShape<ProviderAdapterError>["stopSession"] = (threadId) =>
Effect.gen(function* () {
if (!sessions.has(threadId)) {
return yield* Effect.fail(sessionNotFound(threadId));
}
yield* clearPendingTimers(threadId);
sessions.delete(threadId);
});
const listSessions: ProviderAdapterShape<ProviderAdapterError>["listSessions"] = () =>
Effect.sync(() => Array.from(sessions.values(), (state) => state.session));
const hasSession: ProviderAdapterShape<ProviderAdapterError>["hasSession"] = (threadId) =>
Effect.succeed(sessions.has(threadId));
const readThread: ProviderAdapterShape<ProviderAdapterError>["readThread"] = (threadId) =>
sessions.has(threadId)
? Effect.succeed(sessions.get(threadId)!.snapshot)
: Effect.fail(sessionNotFound(threadId));
const rollbackThread: ProviderAdapterShape<ProviderAdapterError>["rollbackThread"] = (
threadId,
numTurns,
) =>
Effect.gen(function* () {
const state = sessions.get(threadId);
if (!state) {
return yield* Effect.fail(sessionNotFound(threadId));
}
if (!Number.isInteger(numTurns) || numTurns < 0 || numTurns > state.snapshot.turns.length) {
return yield* new ProviderAdapterValidationError({
provider: "codex",
operation: "rollbackThread",
issue: "numTurns must be an integer between 0 and the current turn count.",
});
}
state.snapshot = {
threadId: state.snapshot.threadId,
turns: state.snapshot.turns.slice(0, state.snapshot.turns.length - numTurns),
};
state.turnCount = state.snapshot.turns.length;
return state.snapshot;
});
const stopAll: ProviderAdapterShape<ProviderAdapterError>["stopAll"] = () =>
Effect.gen(function* () {
yield* Effect.forEach(
Array.from(sessions.keys()),
(threadId) => clearPendingTimers(threadId),
{
concurrency: "unbounded",
},
);
sessions.clear();
});
return {
provider: "codex",
capabilities: {
sessionModelSwitch: "in-session",
},
startSession,
sendTurn,
interruptTurn,
respondToRequest,
respondToUserInput,
stopSession,
listSessions,
hasSession,
readThread,
rollbackThread,
stopAll,
get streamEvents() {
return Stream.fromQueue(runtimeEvents);
},
} satisfies ProviderAdapterShape<ProviderAdapterError>;
});
@@ -0,0 +1,29 @@
import { Effect, Layer } from "effect";
import { ProviderSessionRuntimeRepositoryLive } from "../persistence/Layers/ProviderSessionRuntime.ts";
import { ProviderUnsupportedError } from "../provider/Errors.ts";
import { makeProviderServiceLive } from "../provider/Layers/ProviderService.ts";
import { ProviderSessionDirectoryLive } from "../provider/Layers/ProviderSessionDirectory.ts";
import { ProviderAdapterRegistry } from "../provider/Services/ProviderAdapterRegistry.ts";
import { makePerfProviderAdapter } from "./PerfProviderAdapter.ts";
export const PerfProviderLayerLive = Layer.unwrap(
Effect.gen(function* () {
const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(ProviderSessionRuntimeRepositoryLive),
);
const adapter = yield* makePerfProviderAdapter;
const adapterRegistryLayer = Layer.succeed(ProviderAdapterRegistry, {
getByProvider: (provider) =>
provider === adapter.provider
? Effect.succeed(adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed([adapter.provider]),
} as typeof ProviderAdapterRegistry.Service);
return makeProviderServiceLive().pipe(
Layer.provide(adapterRegistryLayer),
Layer.provide(providerSessionDirectoryLayer),
);
}),
);
@@ -0,0 +1,160 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
import { getClaudeModelCapabilities } from "../provider/Layers/ClaudeProvider.ts";
import { getCodexModelCapabilities } from "../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../serverSettings.ts";
import {
ProviderRegistry,
type ProviderRegistryShape,
} from "../provider/Services/ProviderRegistry.ts";
const makeProviderModel = (input: {
readonly slug: string;
readonly name: string;
readonly capabilities: ServerProviderModel["capabilities"];
}): ServerProviderModel => ({
slug: input.slug,
name: input.name,
isCustom: false,
capabilities: input.capabilities,
});
const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
makeProviderModel({
slug: DEFAULT_MODEL_BY_PROVIDER.codex,
name: "GPT-5.4",
capabilities: getCodexModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.codex),
}),
];
const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
makeProviderModel({
slug: DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
name: "Claude Sonnet 4.6",
capabilities: getClaudeModelCapabilities(DEFAULT_MODEL_BY_PROVIDER.claudeAgent),
}),
];
const makeProviderSnapshot = (input: {
readonly provider: ServerProvider["provider"];
readonly enabled: boolean;
readonly checkedAt: string;
}): ServerProvider => {
if (input.provider === "codex") {
return {
provider: "codex",
enabled: input.enabled,
installed: true,
version: "perf-fixture",
status: input.enabled ? "ready" : "disabled",
auth: input.enabled
? {
status: "authenticated",
type: "perf",
label: "Local perf harness",
}
: {
status: "unknown",
},
checkedAt: input.checkedAt,
message: input.enabled ? "Perf fixture provider active." : "Disabled in T3 Code settings.",
models: CODEX_MODELS,
};
}
return {
provider: "claudeAgent",
enabled: input.enabled,
installed: false,
version: null,
status: input.enabled ? "warning" : "disabled",
auth: {
status: "unknown",
},
checkedAt: input.checkedAt,
message: input.enabled
? "Perf harness only stubs Codex runtime sessions."
: "Disabled in T3 Code settings.",
models: CLAUDE_MODELS,
};
};
const loadPerfProviderSnapshots = Effect.fn("loadPerfProviderSnapshots")(function* (input: {
readonly serverSettings: ServerSettingsService["Service"];
}) {
const settings = yield* input.serverSettings.getSettings;
const checkedAt = new Date().toISOString();
return [
makeProviderSnapshot({
provider: "codex",
enabled: settings.providers.codex.enabled,
checkedAt,
}),
makeProviderSnapshot({
provider: "claudeAgent",
enabled: settings.providers.claudeAgent.enabled,
checkedAt,
}),
] as const;
});
const loadPerfProviderSnapshotsSafely = (
serverSettings: ServerSettingsService["Service"],
fallback: ReadonlyArray<ServerProvider>,
) =>
loadPerfProviderSnapshots({ serverSettings }).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => fallback),
);
export const PerfProviderRegistryLive = Layer.effect(
ProviderRegistry,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
PubSub.shutdown,
);
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
yield* loadPerfProviderSnapshotsSafely(serverSettings, [
makeProviderSnapshot({
provider: "codex",
enabled: true,
checkedAt: new Date().toISOString(),
}),
makeProviderSnapshot({
provider: "claudeAgent",
enabled: false,
checkedAt: new Date().toISOString(),
}),
]),
);
const refreshProviders = Effect.fn("refreshPerfProviders")(function* () {
const previous = yield* Ref.get(providersRef);
const next = yield* loadPerfProviderSnapshotsSafely(serverSettings, previous);
yield* Ref.set(providersRef, next);
if (!Equal.equals(previous, next)) {
yield* PubSub.publish(changesPubSub, next);
}
return next;
});
yield* Stream.runForEach(serverSettings.streamChanges, () => refreshProviders()).pipe(
Effect.forkScoped,
);
return {
getProviders: Ref.get(providersRef),
refresh: (_provider) => refreshProviders(),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ProviderRegistryShape;
}),
);
+18
View File
@@ -0,0 +1,18 @@
import type { PerfProviderScenarioId } from "@t3tools/shared/perf/scenarioCatalog";
export const PERF_PROVIDER_ENV = "T3CODE_PERF_PROVIDER";
export const PERF_SCENARIO_ENV = "T3CODE_PERF_SCENARIO";
export const PERF_ARTIFACT_DIR_ENV = "T3CODE_PERF_ARTIFACT_DIR";
export const PERF_HEADFUL_ENV = "T3CODE_PERF_HEADFUL";
export function isPerfProviderEnabled(): boolean {
return process.env[PERF_PROVIDER_ENV] === "1";
}
export function getPerfProviderScenarioId(): PerfProviderScenarioId | null {
const rawScenarioId = process.env[PERF_SCENARIO_ENV]?.trim();
if (rawScenarioId === "dense_assistant_stream" || rawScenarioId === "parallel_assistant_stream") {
return rawScenarioId;
}
return null;
}
@@ -1,6 +1,6 @@
import { MessageId, ThreadId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import { Effect, Layer, Option } from "effect";
import { ProjectionThreadMessageRepository } from "../Services/ProjectionThreadMessages.ts";
import { ProjectionThreadMessageRepositoryLive } from "./ProjectionThreadMessages.ts";
@@ -103,4 +103,84 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.deepEqual(rows[0]?.attachments, []);
}),
);
it.effect("looks up a projected message by id", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.makeUnsafe("thread-get-by-message-id");
const messageId = MessageId.makeUnsafe("message-get-by-message-id");
const createdAt = "2026-02-28T19:20:00.000Z";
const updatedAt = "2026-02-28T19:20:01.000Z";
yield* repository.upsert({
messageId,
threadId,
turnId: null,
role: "assistant",
text: "lookup me",
isStreaming: false,
createdAt,
updatedAt,
});
const maybeRow = yield* repository.getByMessageId({ messageId });
assert.isTrue(Option.isSome(maybeRow));
const row = Option.getOrThrow(maybeRow);
assert.equal(row.messageId, messageId);
assert.equal(row.threadId, threadId);
assert.equal(row.text, "lookup me");
assert.equal(row.createdAt, createdAt);
assert.equal(row.updatedAt, updatedAt);
}),
);
it.effect("appends streaming deltas without losing createdAt or attachments", () =>
Effect.gen(function* () {
const repository = yield* ProjectionThreadMessageRepository;
const threadId = ThreadId.makeUnsafe("thread-append-delta");
const messageId = MessageId.makeUnsafe("message-append-delta");
const createdAt = "2026-02-28T19:30:00.000Z";
const persistedAttachments = [
{
type: "image" as const,
id: "thread-append-delta-att-1",
name: "example.png",
mimeType: "image/png",
sizeBytes: 5,
},
];
yield* repository.appendTextDelta({
messageId,
threadId,
turnId: null,
role: "assistant",
delta: "Hello",
attachments: persistedAttachments,
isStreaming: true,
createdAt,
updatedAt: "2026-02-28T19:30:01.000Z",
});
yield* repository.appendTextDelta({
messageId,
threadId,
turnId: null,
role: "assistant",
delta: " world",
isStreaming: true,
createdAt: "2026-02-28T19:30:05.000Z",
updatedAt: "2026-02-28T19:30:06.000Z",
});
const maybeRow = yield* repository.getByMessageId({ messageId });
assert.isTrue(Option.isSome(maybeRow));
const row = Option.getOrThrow(maybeRow);
assert.equal(row.text, "Hello world");
assert.equal(row.createdAt, createdAt);
assert.equal(row.updatedAt, "2026-02-28T19:30:06.000Z");
assert.deepEqual(row.attachments, persistedAttachments);
assert.isTrue(row.isStreaming);
}),
);
});
@@ -1,10 +1,12 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
AppendProjectionThreadMessageDeltaInput,
GetProjectionThreadMessageInput,
ProjectionThreadMessageRepository,
type ProjectionThreadMessageRepositoryShape,
DeleteProjectionThreadMessagesInput,
@@ -18,6 +20,19 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
attachments: Schema.NullOr(Schema.fromJsonString(Schema.Array(ChatAttachment))),
}),
);
type ProjectionThreadMessageDbRow = typeof ProjectionThreadMessageDbRowSchema.Type;
const toProjectionThreadMessage = (row: ProjectionThreadMessageDbRow) => ({
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
});
const makeProjectionThreadMessageRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -95,6 +110,70 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
`,
});
const getProjectionThreadMessageRow = SqlSchema.findOneOption({
Request: GetProjectionThreadMessageInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ messageId }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE message_id = ${messageId}
`,
});
const appendProjectionThreadMessageDeltaRow = SqlSchema.void({
Request: AppendProjectionThreadMessageDeltaInput,
execute: (row) => {
const nextAttachmentsJson =
row.attachments !== undefined ? JSON.stringify(row.attachments) : null;
return sql`
INSERT INTO projection_thread_messages (
message_id,
thread_id,
turn_id,
role,
text,
attachments_json,
is_streaming,
created_at,
updated_at
)
VALUES (
${row.messageId},
${row.threadId},
${row.turnId},
${row.role},
${row.delta},
${nextAttachmentsJson},
${row.isStreaming ? 1 : 0},
${row.createdAt},
${row.updatedAt}
)
ON CONFLICT (message_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = COALESCE(excluded.turn_id, projection_thread_messages.turn_id),
role = excluded.role,
text = projection_thread_messages.text || excluded.text,
attachments_json = COALESCE(
excluded.attachments_json,
projection_thread_messages.attachments_json
),
is_streaming = excluded.is_streaming,
updated_at = excluded.updated_at
`;
},
});
const deleteProjectionThreadMessageRows = SqlSchema.void({
Request: DeleteProjectionThreadMessagesInput,
execute: ({ threadId }) =>
@@ -114,18 +193,21 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
),
Effect.map((rows) =>
rows.map((row) => ({
messageId: row.messageId,
threadId: row.threadId,
turnId: row.turnId,
role: row.role,
text: row.text,
isStreaming: row.isStreaming === 1,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
...(row.attachments !== null ? { attachments: row.attachments } : {}),
})),
Effect.map((rows) => rows.map(toProjectionThreadMessage)),
);
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
getProjectionThreadMessageRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
),
Effect.map(Option.map(toProjectionThreadMessage)),
);
const appendTextDelta: ProjectionThreadMessageRepositoryShape["appendTextDelta"] = (input) =>
appendProjectionThreadMessageDeltaRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.appendTextDelta:query"),
),
);
@@ -139,6 +221,8 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
return {
upsert,
listByThreadId,
getByMessageId,
appendTextDelta,
deleteByThreadId,
} satisfies ProjectionThreadMessageRepositoryShape;
});
+15 -15
View File
@@ -16,15 +16,14 @@ const defaultSqliteClientLoaders = {
node: () => import("../NodeSqliteClient.ts"),
} satisfies Record<string, () => Promise<Loader>>;
const makeRuntimeSqliteLayer = (
const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
config: RuntimeSqliteLayerConfig,
): Layer.Layer<SqlClient.SqlClient> =>
Effect.gen(function* () {
const runtime = process.versions.bun !== undefined ? "bun" : "node";
const loader = defaultSqliteClientLoaders[runtime];
const clientModule = yield* Effect.promise<Loader>(loader);
return clientModule.layer(config);
}).pipe(Layer.unwrap);
) {
const runtime = process.versions.bun !== undefined ? "bun" : "node";
const loader = defaultSqliteClientLoaders[runtime];
const clientModule = yield* Effect.promise<Loader>(loader);
return clientModule.layer(config);
}, Layer.unwrap);
const setup = Layer.effectDiscard(
Effect.gen(function* () {
@@ -35,14 +34,15 @@ const setup = Layer.effectDiscard(
}),
);
export const makeSqlitePersistenceLive = (dbPath: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
export const makeSqlitePersistenceLive = Effect.fn("makeSqlitePersistenceLive")(function* (
dbPath: string,
) {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
yield* fs.makeDirectory(path.dirname(dbPath), { recursive: true });
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
}).pipe(Layer.unwrap);
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
}, Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
setup,
+14 -13
View File
@@ -92,19 +92,20 @@ export interface RunMigrationsOptions {
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
Effect.gen(function* () {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
export const runMigrations = Effect.fn("runMigrations")(function* ({
toMigrationInclusive,
}: RunMigrationsOptions = {}) {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
/**
* Layer that runs migrations when the layer is built.
+127 -134
View File
@@ -72,160 +72,153 @@ const checkNodeSqliteCompat = () => {
return Effect.void;
};
const makeWithDatabase = (
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
options: SqliteClientConfig,
openDatabase: () => DatabaseSync,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
Effect.gen(function* () {
yield* checkNodeSqliteCompat();
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
yield* checkNodeSqliteCompat();
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
: undefined;
const compiler = Statement.makeCompilerSqlite(options.transformQueryNames);
const transformRows = options.transformResultNames
? Statement.defaultTransforms(options.transformResultNames).array
: undefined;
const makeConnection = Effect.gen(function* () {
const scope = yield* Effect.scope;
const db = openDatabase();
yield* Scope.addFinalizer(
scope,
Effect.sync(() => db.close()),
);
const makeConnection = Effect.gen(function* () {
const scope = yield* Effect.scope;
const db = openDatabase();
yield* Scope.addFinalizer(
scope,
Effect.sync(() => db.close()),
);
const statementReaderCache = new WeakMap<StatementSync, boolean>();
const hasRows = (statement: StatementSync): boolean => {
const cached = statementReaderCache.get(statement);
if (cached !== undefined) {
return cached;
}
const value = statement.columns().length > 0;
statementReaderCache.set(statement, value);
return value;
};
const statementReaderCache = new WeakMap<StatementSync, boolean>();
const hasRows = (statement: StatementSync): boolean => {
const cached = statementReaderCache.get(statement);
if (cached !== undefined) {
return cached;
}
const value = statement.columns().length > 0;
statementReaderCache.set(statement, value);
return value;
};
const prepareCache = yield* Cache.make({
capacity: options.prepareCacheSize ?? 200,
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to prepare statement",
operation: "prepare",
}),
const prepareCache = yield* Cache.make({
capacity: options.prepareCacheSize ?? 200,
timeToLive: options.prepareCacheTTL ?? Duration.minutes(10),
lookup: (sql: string) =>
Effect.try({
try: () => db.prepare(sql),
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to prepare statement",
operation: "prepare",
}),
}),
}),
}),
});
const runStatement = (statement: StatementSync, params: ReadonlyArray<unknown>, raw: boolean) =>
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
try {
if (hasRows(statement)) {
return Effect.succeed(statement.all(...(params as any)));
}
const result = statement.run(...(params as any));
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
} catch (cause) {
return Effect.fail(
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
);
}
});
const runStatement = (
statement: StatementSync,
params: ReadonlyArray<unknown>,
raw: boolean,
) =>
Effect.withFiber<ReadonlyArray<any>, SqlError>((fiber) => {
statement.setReadBigInts(Boolean(ServiceMap.get(fiber.services, Client.SafeIntegers)));
try {
if (hasRows(statement)) {
return Effect.succeed(statement.all(...(params as any)));
}
const result = statement.run(...(params as any));
return Effect.succeed(raw ? (result as unknown as ReadonlyArray<any>) : []);
} catch (cause) {
return Effect.fail(
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
Effect.acquireUseRelease(
Cache.get(prepareCache, sql),
(statement) =>
Effect.try({
try: () => {
if (hasRows(statement)) {
statement.setReturnArrays(true);
// Safe to cast to array after we've setReturnArrays(true)
return statement.all(...(params as any)) as unknown as ReadonlyArray<
ReadonlyArray<unknown>
>;
}
statement.run(...(params as any));
return [];
},
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
);
}
});
const run = (sql: string, params: ReadonlyArray<unknown>, raw = false) =>
Effect.flatMap(Cache.get(prepareCache, sql), (s) => runStatement(s, params, raw));
const runValues = (sql: string, params: ReadonlyArray<unknown>) =>
Effect.acquireUseRelease(
Cache.get(prepareCache, sql),
(statement) =>
Effect.try({
try: () => {
if (hasRows(statement)) {
statement.setReturnArrays(true);
// Safe to cast to array after we've setReturnArrays(true)
return statement.all(...(params as any)) as unknown as ReadonlyArray<
ReadonlyArray<unknown>
>;
}
statement.run(...(params as any));
return [];
},
catch: (cause) =>
new SqlError({
reason: classifySqliteError(cause, {
message: "Failed to execute statement",
operation: "execute",
}),
}),
}),
(statement) =>
Effect.sync(() => {
if (hasRows(statement)) {
statement.setReturnArrays(false);
}
}),
);
return identity<Connection>({
execute(sql, params, rowTransform) {
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
},
executeRaw(sql, params) {
return run(sql, params, true);
},
executeValues(sql, params) {
return runValues(sql, params);
},
executeUnprepared(sql, params, rowTransform) {
const effect = runStatement(db.prepare(sql), params ?? [], false);
return rowTransform ? Effect.map(effect, rowTransform) : effect;
},
executeStream(_sql, _params) {
return Stream.die("executeStream not implemented");
},
});
});
const semaphore = yield* Semaphore.make(1);
const connection = yield* makeConnection;
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
const fiber = Fiber.getCurrent()!;
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
return Effect.as(
Effect.tap(restore(semaphore.take(1)), () =>
Scope.addFinalizer(scope, semaphore.release(1)),
),
connection,
}),
(statement) =>
Effect.sync(() => {
if (hasRows(statement)) {
statement.setReturnArrays(false);
}
}),
);
});
return yield* Client.make({
acquirer,
compiler,
transactionAcquirer,
spanAttributes: [
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
[ATTR_DB_SYSTEM_NAME, "sqlite"],
],
transformRows,
return identity<Connection>({
execute(sql, params, rowTransform) {
return rowTransform ? Effect.map(run(sql, params), rowTransform) : run(sql, params);
},
executeRaw(sql, params) {
return run(sql, params, true);
},
executeValues(sql, params) {
return runValues(sql, params);
},
executeUnprepared(sql, params, rowTransform) {
const effect = runStatement(db.prepare(sql), params ?? [], false);
return rowTransform ? Effect.map(effect, rowTransform) : effect;
},
executeStream(_sql, _params) {
return Stream.die("executeStream not implemented");
},
});
});
const semaphore = yield* Semaphore.make(1);
const connection = yield* makeConnection;
const acquirer = semaphore.withPermits(1)(Effect.succeed(connection));
const transactionAcquirer = Effect.uninterruptibleMask((restore) => {
const fiber = Fiber.getCurrent()!;
const scope = ServiceMap.getUnsafe(fiber.services, Scope.Scope);
return Effect.as(
Effect.tap(restore(semaphore.take(1)), () => Scope.addFinalizer(scope, semaphore.release(1))),
connection,
);
});
return yield* Client.make({
acquirer,
compiler,
transactionAcquirer,
spanAttributes: [
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
[ATTR_DB_SYSTEM_NAME, "sqlite"],
],
transformRows,
});
});
const make = (
options: SqliteClientConfig,
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
Loaded 100 of 303 files, more files were not shown because too many files have changed in this diff. Show more