Compare commits

..
Author SHA1 Message Date
Julius Marminge ae625d277c Handle missing workspaces across server and UI
- validate workspace paths before git, provider, terminal, and WS ops
- surface workspace availability in projections and client state
- add tests for missing cwd recovery and status handling
2026-03-29 00:45:41 -07:00
280 changed files with 14660 additions and 33021 deletions

No files matched your search

-1
View File
@@ -1,7 +1,6 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"ignorePatterns": [
".reference",
".plans",
"dist",
"dist-electron",
-89
View File
@@ -1,89 +0,0 @@
# 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 -30
View File
@@ -2,42 +2,18 @@
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## Installation
## How to use
> [!WARNING]
> T3 Code currently supports Codex and Claude.
> Install and authenticate at least one provider before use:
>
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
> - Claude: install Claude Code and run `claude auth login`
### Run without installing
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
```bash
npx t3
```
### Desktop app
You can also just install the desktop app. It's cooler.
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
#### Windows (`winget`)
```bash
winget install T3Tools.T3Code
```
#### macOS (Homebrew)
```bash
brew install --cask t3-code
```
#### Arch Linux (AUR)
```bash
yay -S t3code-bin
```
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
## Some notes
@@ -45,8 +21,6 @@ We are very very early in this project. Expect bugs.
We are not accepting contributions yet.
Observability guide: [docs/observability.md](./docs/observability.md)
## If you REALLY want to contribute still.... read this first
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
+2 -1
View File
@@ -24,7 +24,8 @@
"@types/node": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
"vitest": "catalog:",
"wait-on": "^8.0.2"
},
"productName": "T3 Code (Alpha)"
}
+5 -7
View File
@@ -1,29 +1,27 @@
import { spawn, spawnSync } from "node:child_process";
import { watch } from "node:fs";
import { join } from "node:path";
import waitOn from "wait-on";
import { desktopDir, resolveElectronPath } from "./electron-launcher.mjs";
import { waitForResources } from "./wait-for-resources.mjs";
const port = Number(process.env.ELECTRON_RENDERER_PORT ?? 5733);
const devServerUrl = `http://localhost:${port}`;
const requiredFiles = [
"dist-electron/main.js",
"dist-electron/preload.js",
"../server/dist/bin.mjs",
"../server/dist/index.mjs",
];
const watchedDirectories = [
{ directory: "dist-electron", files: new Set(["main.js", "preload.js"]) },
{ directory: "../server/dist", files: new Set(["bin.mjs"]) },
{ directory: "../server/dist", files: new Set(["index.mjs"]) },
];
const forcedShutdownTimeoutMs = 1_500;
const restartDebounceMs = 120;
const childTreeGracePeriodMs = 1_200;
await waitForResources({
baseDir: desktopDir,
files: requiredFiles,
tcpPort: port,
await waitOn({
resources: [`tcp:${port}`, ...requiredFiles.map((filePath) => `file:${filePath}`)],
});
const childEnv = { ...process.env };
-119
View File
@@ -1,119 +0,0 @@
import * as FileSystem from "node:fs/promises";
import * as Net from "node:net";
import * as Path from "node:path";
import * as Timers from "node:timers/promises";
const defaultTcpHosts = ["127.0.0.1", "localhost", "::1"];
async function fileExists(filePath) {
try {
await FileSystem.access(filePath);
return true;
} catch {
return false;
}
}
function tcpPortIsReady({ host, port, connectTimeoutMs = 500 }) {
return new Promise((resolveReady) => {
const socket = Net.createConnection({ host, port });
let settled = false;
const finish = (ready) => {
if (settled) {
return;
}
settled = true;
socket.removeAllListeners();
socket.destroy();
resolveReady(ready);
};
socket.once("connect", () => {
finish(true);
});
socket.once("timeout", () => {
finish(false);
});
socket.once("error", () => {
finish(false);
});
socket.setTimeout(connectTimeoutMs);
});
}
async function resolvePendingResources({ baseDir, files, tcpPort, tcpHosts, connectTimeoutMs }) {
const pendingFiles = [];
for (const relativeFilePath of files) {
const ready = await fileExists(Path.resolve(baseDir, relativeFilePath));
if (!ready) {
pendingFiles.push(relativeFilePath);
}
}
let tcpReady = false;
for (const host of tcpHosts) {
tcpReady = await tcpPortIsReady({
host,
port: tcpPort,
connectTimeoutMs,
});
if (tcpReady) {
break;
}
}
return {
pendingFiles,
tcpReady,
};
}
export async function waitForResources({
baseDir,
files = [],
intervalMs = 100,
timeoutMs = 120_000,
tcpHost,
tcpPort,
connectTimeoutMs = 500,
}) {
if (!Number.isInteger(tcpPort) || tcpPort <= 0) {
throw new TypeError("waitForResources requires a positive integer tcpPort");
}
const startedAt = Date.now();
const tcpHosts = tcpHost ? [tcpHost] : defaultTcpHosts;
while (true) {
const { pendingFiles, tcpReady } = await resolvePendingResources({
baseDir,
files,
tcpPort,
tcpHosts,
connectTimeoutMs,
});
if (pendingFiles.length === 0 && tcpReady) {
return;
}
if (Date.now() - startedAt >= timeoutMs) {
const pendingResources = [];
if (!tcpReady) {
pendingResources.push(tcpHost ? `tcp:${tcpHost}:${tcpPort}` : `tcp:${tcpPort}`);
}
for (const filePath of pendingFiles) {
pendingResources.push(`file:${filePath}`);
}
throw new Error(
`Timed out waiting for desktop dev resources after ${timeoutMs}ms: ${pendingResources.join(", ")}`,
);
}
await Timers.setTimeout(intervalMs);
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
+2 -48
View File
@@ -28,7 +28,6 @@ import { autoUpdater } from "electron-updater";
import type { ContextMenuItem } from "@t3tools/contracts";
import { NetService } from "@t3tools/shared/Net";
import { RotatingFileSink } from "@t3tools/shared/logging";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { showDesktopConfirmDialog } from "./confirmDialog";
import { syncShellEnvironment } from "./syncShellEnvironment";
import { getAutoUpdateDisabledReason, shouldBroadcastDownloadProgress } from "./updateState";
@@ -67,8 +66,6 @@ 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;
@@ -77,16 +74,12 @@ const LOG_DIR = Path.join(STATE_DIR, "logs");
const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
const LOG_FILE_MAX_FILES = 10;
const APP_RUN_ID = Crypto.randomBytes(6).toString("hex");
const SERVER_SETTINGS_PATH = Path.join(STATE_DIR, "settings.json");
const AUTO_UPDATE_STARTUP_DELAY_MS = 15_000;
const AUTO_UPDATE_POLL_INTERVAL_MS = 4 * 60 * 60 * 1000;
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;
@@ -101,10 +94,8 @@ let aboutCommitHashCache: string | null | undefined;
let desktopLogSink: RotatingFileSink | null = null;
let backendLogSink: RotatingFileSink | null = null;
let restoreStdIoCapture: (() => void) | null = null;
let backendObservabilitySettings = readPersistedBackendObservabilitySettings();
let destructiveMenuIconCache: Electron.NativeImage | null | undefined;
const expectedBackendExitChildren = new WeakSet<ChildProcess.ChildProcess>();
const desktopRuntimeInfo = resolveDesktopRuntimeInfo({
platform: process.platform,
processArch: process.arch,
@@ -125,21 +116,6 @@ function sanitizeLogValue(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function readPersistedBackendObservabilitySettings(): {
readonly otlpTracesUrl: string | undefined;
readonly otlpMetricsUrl: string | undefined;
} {
try {
if (!FS.existsSync(SERVER_SETTINGS_PATH)) {
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
return parsePersistedServerObservabilitySettings(FS.readFileSync(SERVER_SETTINGS_PATH, "utf8"));
} catch (error) {
console.warn("[desktop] failed to read persisted backend observability settings", error);
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
}
function backendChildEnv(): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env.T3CODE_PORT;
@@ -287,10 +263,6 @@ 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) {
@@ -418,7 +390,7 @@ function resolveAboutCommitHash(): string | null {
}
function resolveBackendEntry(): string {
return Path.join(resolveAppRoot(), "apps/server/dist/bin.mjs");
return Path.join(resolveAppRoot(), "apps/server/dist/index.mjs");
}
function resolveBackendCwd(): string {
@@ -743,10 +715,6 @@ 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) {
@@ -1007,7 +975,6 @@ function scheduleBackendRestart(reason: string): void {
function startBackend(): void {
if (isQuitting || backendProcess) return;
backendObservabilitySettings = readPersistedBackendObservabilitySettings();
const backendEntry = resolveBackendEntry();
if (!FS.existsSync(backendEntry)) {
scheduleBackendRestart(`missing server entry at ${backendEntry}`);
@@ -1036,12 +1003,6 @@ function startBackend(): void {
port: backendPort,
t3Home: BASE_DIR,
authToken: backendAuthToken,
...(backendObservabilitySettings.otlpTracesUrl
? { otlpTracesUrl: backendObservabilitySettings.otlpTracesUrl }
: {}),
...(backendObservabilitySettings.otlpMetricsUrl
? { otlpMetricsUrl: backendObservabilitySettings.otlpMetricsUrl }
: {}),
})}\n`,
);
bootstrapStream.end();
@@ -1068,26 +1029,21 @@ function startBackend(): void {
});
child.on("error", (error) => {
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(`pid=${child.pid ?? "unknown"} error=${error.message}`);
if (wasExpected) {
return;
}
scheduleBackendRestart(error.message);
});
child.on("exit", (code, signal) => {
const wasExpected = expectedBackendExitChildren.has(child);
if (backendProcess === child) {
backendProcess = null;
}
closeBackendSession(
`pid=${child.pid ?? "unknown"} code=${code ?? "null"} signal=${signal ?? "null"}`,
);
if (isQuitting || wasExpected) return;
if (isQuitting) return;
const reason = `code=${code ?? "null"} signal=${signal ?? "null"}`;
scheduleBackendRestart(reason);
});
@@ -1104,7 +1060,6 @@ function stopBackend(): void {
if (!child) return;
if (child.exitCode === null && child.signalCode === null) {
expectedBackendExitChildren.add(child);
child.kill("SIGTERM");
setTimeout(() => {
if (child.exitCode === null && child.signalCode === null) {
@@ -1125,7 +1080,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
if (!child) return;
const backendChild = child;
if (backendChild.exitCode !== null || backendChild.signalCode !== null) return;
expectedBackendExitChildren.add(backendChild);
await new Promise<void>((resolve) => {
let settled = false;
@@ -68,8 +68,6 @@ import {
type TestProviderAdapterHarness,
} 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, {
@@ -126,7 +124,7 @@ function waitFor<A, E>(
read: Effect.Effect<A, E>,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 40_000,
timeoutMs = 10_000,
): Effect.Effect<A, never> {
const RETRY_SIGNAL = "wait_for_retry";
const retryIntervalMs = 10;
@@ -289,10 +287,9 @@ export const makeOrchestrationIntegrationHarness = (
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const projectionSnapshotQueryLayer = OrchestrationProjectionSnapshotQueryLive;
const runtimeServicesLayer = Layer.mergeAll(
projectionSnapshotQueryLayer,
orchestrationLayer.pipe(Layer.provide(projectionSnapshotQueryLayer)),
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
@@ -320,23 +317,13 @@ export const makeOrchestrationIntegrationHarness = (
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
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),
Layer.provideMerge(providerCommandReactorLayer),
Layer.provideMerge(checkpointReactorLayer),
);
const layer = Layer.empty.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(orchestrationReactorLayer),
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
@@ -57,7 +57,7 @@ function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
description: string,
timeoutMs = 10_000,
timeoutMs = 3000,
): Effect.Effect<A, never> {
return Effect.gen(function* () {
const deadline = Date.now() + timeoutMs;
+6 -5
View File
@@ -8,29 +8,29 @@
"directory": "apps/server"
},
"bin": {
"t3": "./dist/bin.mjs"
"t3": "./dist/index.mjs"
},
"files": [
"dist"
],
"type": "module",
"scripts": {
"dev": "bun run src/bin.ts",
"dev": "bun run src/index.ts",
"build": "node scripts/cli.ts build",
"start": "node dist/bin.mjs",
"start": "node dist/index.mjs",
"prepare": "effect-language-service patch",
"typecheck": "tsc --noEmit",
"test": "vitest run"
},
"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"
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@effect/language-service": "catalog:",
@@ -40,6 +40,7 @@
"@t3tools/web": "workspace:*",
"@types/bun": "catalog:",
"@types/node": "catalog:",
"@types/ws": "^8.5.13",
"tsdown": "catalog:",
"typescript": "catalog:",
"vitest": "catalog:"
-17
View File
@@ -1,17 +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 { 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
@@ -1,6 +1,6 @@
import { Schema } from "effect";
import type { ProjectionRepositoryError } from "../persistence/Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCommandError } from "../git/Errors.ts";
/**
* CheckpointUnavailableError - Expected checkpoint does not exist.
@@ -1,38 +1,87 @@
import { CheckpointRef, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { Effect, Layer, Option } from "effect";
import {
CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
ProjectId,
ThreadId,
TurnId,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { Effect, Layer } from "effect";
import { describe, expect, it } from "vitest";
import {
ProjectionSnapshotQuery,
type ProjectionThreadCheckpointContext,
} from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { CheckpointDiffQueryLive } from "./CheckpointDiffQuery.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointDiffQuery } from "../Services/CheckpointDiffQuery.ts";
function makeThreadCheckpointContext(input: {
function makeSnapshot(input: {
readonly projectId: ProjectId;
readonly threadId: ThreadId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpointTurnCount: number;
readonly checkpointRef: CheckpointRef;
}): ProjectionThreadCheckpointContext {
}): OrchestrationReadModel {
return {
threadId: input.threadId,
projectId: input.projectId,
workspaceRoot: input.workspaceRoot,
worktreePath: input.worktreePath,
checkpoints: [
snapshotSequence: 0,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
{
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
workspaceState: "available",
defaultModelSelection: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [
{
id: input.threadId,
projectId: input.projectId,
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: input.worktreePath,
effectiveCwd: input.worktreePath ?? input.workspaceRoot,
effectiveCwdSource: input.worktreePath ? "worktree" : "project",
effectiveCwdState: "available",
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-01-01T00:00:00.000Z",
startedAt: "2026-01-01T00:00:00.000Z",
completedAt: "2026-01-01T00:00:00.000Z",
assistantMessageId: null,
},
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
activities: [],
proposedPlans: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: input.checkpointTurnCount,
checkpointRef: input.checkpointRef,
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-01-01T00:00:00.000Z",
},
],
session: null,
},
],
};
@@ -50,7 +99,7 @@ describe("CheckpointDiffQueryLive", () => {
readonly cwd: string;
}> = [];
const threadCheckpointContext = makeThreadCheckpointContext({
const snapshot = makeSnapshot({
projectId,
threadId,
workspaceRoot: "/tmp/workspace",
@@ -80,12 +129,7 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(Layer.succeed(CheckpointStore, checkpointStore)),
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.some(threadCheckpointContext)),
getSnapshot: () => Effect.succeed(snapshot),
}),
),
);
@@ -135,11 +179,12 @@ describe("CheckpointDiffQueryLive", () => {
Layer.provideMerge(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () =>
Effect.die("CheckpointDiffQuery should not request the full orchestration snapshot"),
getCounts: () => Effect.succeed({ projectCount: 0, threadCount: 0 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
Effect.succeed({
snapshotSequence: 0,
projects: [],
threads: [],
updatedAt: "2026-01-01T00:00:00.000Z",
} satisfies OrchestrationReadModel),
}),
),
);
@@ -4,11 +4,11 @@ import {
type OrchestrationGetFullThreadDiffResult,
type OrchestrationGetTurnDiffResult as OrchestrationGetTurnDiffResultType,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Schema } from "effect";
import { Effect, Layer, Schema } from "effect";
import { ProjectionSnapshotQuery } from "../../orchestration/Services/ProjectionSnapshotQuery.ts";
import { CheckpointInvariantError, CheckpointUnavailableError } from "../Errors.ts";
import { checkpointRefForThreadTurn } from "../Utils.ts";
import { checkpointRefForThreadTurn, resolveThreadWorkspaceCwd } from "../Utils.ts";
import { CheckpointStore } from "../Services/CheckpointStore.ts";
import {
CheckpointDiffQuery,
@@ -21,8 +21,8 @@ const make = Effect.gen(function* () {
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
const checkpointStore = yield* CheckpointStore;
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = Effect.fn("getTurnDiff")(
function* (input) {
const getTurnDiff: CheckpointDiffQueryShape["getTurnDiff"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointDiffQuery.getTurnDiff";
if (input.fromTurnCount === input.toTurnCount) {
@@ -41,17 +41,16 @@ const make = Effect.gen(function* () {
return emptyDiff;
}
const threadContext = yield* projectionSnapshotQuery.getThreadCheckpointContext(
input.threadId,
);
if (Option.isNone(threadContext)) {
const snapshot = yield* projectionSnapshotQuery.getSnapshot();
const thread = snapshot.threads.find((entry) => entry.id === input.threadId);
if (!thread) {
return yield* new CheckpointInvariantError({
operation,
detail: `Thread '${input.threadId}' not found.`,
});
}
const maxTurnCount = threadContext.value.checkpoints.reduce(
const maxTurnCount = thread.checkpoints.reduce(
(max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
0,
);
@@ -63,7 +62,10 @@ const make = Effect.gen(function* () {
});
}
const workspaceCwd = threadContext.value.worktreePath ?? threadContext.value.workspaceRoot;
const workspaceCwd = resolveThreadWorkspaceCwd({
thread,
projects: snapshot.projects,
});
if (!workspaceCwd) {
return yield* new CheckpointInvariantError({
operation,
@@ -74,7 +76,7 @@ const make = Effect.gen(function* () {
const fromCheckpointRef =
input.fromTurnCount === 0
? checkpointRefForThreadTurn(input.threadId, 0)
: threadContext.value.checkpoints.find(
: thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.fromTurnCount,
)?.checkpointRef;
if (!fromCheckpointRef) {
@@ -85,7 +87,7 @@ const make = Effect.gen(function* () {
});
}
const toCheckpointRef = threadContext.value.checkpoints.find(
const toCheckpointRef = thread.checkpoints.find(
(checkpoint) => checkpoint.checkpointTurnCount === input.toTurnCount,
)?.checkpointRef;
if (!toCheckpointRef) {
@@ -147,8 +149,7 @@ const make = Effect.gen(function* () {
}
return turnDiff;
},
);
});
const getFullThreadDiff: CheckpointDiffQueryShape["getFullThreadDiff"] = (
input: OrchestrationGetFullThreadDiffInput,
@@ -10,7 +10,7 @@ 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 "@t3tools/contracts";
import { GitCommandError } from "../../git/Errors.ts";
import { ServerConfig } from "../../config.ts";
import { ThreadId } from "@t3tools/contracts";
@@ -80,7 +80,7 @@ function initRepoWithCommit(
});
}
function buildLargeText(lineCount = 5_000): string {
function buildLargeText(lineCount = 20_000): string {
return Array.from({ length: lineCount }, (_, index) => `line ${String(index).padStart(5, "0")}`)
.join("\n")
.concat("\n");
@@ -115,7 +115,7 @@ it.layer(TestLayer)("CheckpointStoreLive", (it) => {
expect(diff).toContain("diff --git");
expect(diff).not.toContain("[truncated]");
expect(diff).toContain("+line 04999");
expect(diff).toContain("+line 19999");
}),
);
});
@@ -14,7 +14,7 @@ import { randomUUID } from "node:crypto";
import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
@@ -86,140 +86,139 @@ const makeCheckpointStore = Effect.gen(function* () {
Effect.catch(() => Effect.succeed(false)),
);
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = Effect.fn(
"captureCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.captureCheckpoint";
const captureCheckpoint: CheckpointStoreShape["captureCheckpoint"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.captureCheckpoint";
yield* Effect.acquireUseRelease(
fs.makeTempDirectory({ prefix: "t3-fs-checkpoint-" }),
Effect.fn("captureCheckpoint.withTempDirectory")(function* (tempDir) {
const tempIndexPath = path.join(tempDir, `index-${randomUUID()}`);
const commitEnv: NodeJS.ProcessEnv = {
...process.env,
GIT_INDEX_FILE: tempIndexPath,
GIT_AUTHOR_NAME: "T3 Code",
GIT_AUTHOR_EMAIL: "[email protected]",
GIT_COMMITTER_NAME: "T3 Code",
GIT_COMMITTER_EMAIL: "[email protected]",
};
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]",
};
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"] = Effect.fn(
"restoreCheckpoint",
)(function* (input) {
const operation = "CheckpointStore.restoreCheckpoint";
const restoreCheckpoint: CheckpointStoreShape["restoreCheckpoint"] = (input) =>
Effect.gen(function* () {
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", "--", "."],
args: ["restore", "--source", commitOid, "--worktree", "--staged", "--", "."],
});
yield* git.execute({
operation,
cwd: input.cwd,
args: ["clean", "-fd", "--", "."],
});
}
return true;
});
const headExists = yield* hasHeadCommit(input.cwd);
if (headExists) {
yield* git.execute({
operation,
cwd: input.cwd,
args: ["reset", "--quiet", "--", "."],
});
}
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = Effect.fn("diffCheckpoints")(
function* (input) {
return true;
});
const diffCheckpoints: CheckpointStoreShape["diffCheckpoints"] = (input) =>
Effect.gen(function* () {
const operation = "CheckpointStore.diffCheckpoints";
let fromCommitOid = yield* resolveCheckpointCommit(input.cwd, input.fromCheckpointRef);
@@ -248,26 +247,24 @@ const makeCheckpointStore = Effect.gen(function* () {
});
return result.stdout;
},
);
});
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = Effect.fn(
"deleteCheckpointRefs",
)(function* (input) {
const operation = "CheckpointStore.deleteCheckpointRefs";
const deleteCheckpointRefs: CheckpointStoreShape["deleteCheckpointRefs"] = (input) =>
Effect.gen(function* () {
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,
-411
View File
@@ -1,411 +0,0 @@
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 defaultObservabilityConfig = {
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
} as const;
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(),
cwd: 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",
...defaultObservabilityConfig,
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),
cwd: Option.none(),
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",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: 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,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
});
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(),
cwd: 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",
...defaultObservabilityConfig,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
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 customCwd = path.join(baseDir, "nested", "project");
const resolved = yield* resolveServerConfig(
{
mode: Option.some("desktop"),
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
cwd: Option.some(customCwd),
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 [
customCwd,
resolved.stateDir,
resolved.logsDir,
resolved.providerLogsDir,
resolved.terminalLogsDir,
resolved.attachmentsDir,
resolved.worktreesDir,
path.dirname(resolved.serverLogPath),
path.dirname(resolved.serverTracePath),
]) {
expect(yield* fs.exists(directory)).toBe(true);
}
expect(resolved.cwd).toBe(path.resolve(customCwd));
}),
);
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(),
cwd: 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",
...defaultObservabilityConfig,
mode: "web",
port: 8788,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: undefined,
devUrl: new URL("http://127.0.0.1:4173"),
noBrowser: true,
authToken: "flag-token",
autoBootstrapProjectFromCwd: true,
logWebSocketEvents: true,
});
}),
);
it.effect("falls back to persisted observability settings when env vars are absent", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-cli-config-settings-" });
const derivedPaths = yield* deriveServerPaths(baseDir, undefined);
yield* fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true });
yield* fs.writeFileString(
derivedPaths.settingsPath,
`${JSON.stringify({
observability: {
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
},
})}\n`,
);
const resolved = yield* resolveServerConfig(
{
mode: Option.some("desktop"),
port: Option.some(4888),
host: Option.none(),
baseDir: Option.some(baseDir),
cwd: 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: {} })),
NetService.layer,
),
),
);
expect(resolved.otlpTracesUrl).toBe("http://localhost:4318/v1/traces");
expect(resolved.otlpMetricsUrl).toBe("http://localhost:4318/v1/metrics");
expect(resolved).toEqual({
logLevel: "Info",
...defaultObservabilityConfig,
otlpTracesUrl: "http://localhost:4318/v1/traces",
otlpMetricsUrl: "http://localhost:4318/v1/metrics",
mode: "desktop",
port: 4888,
cwd: process.cwd(),
baseDir,
...derivedPaths,
host: "127.0.0.1",
staticDir: resolved.staticDir,
devUrl: undefined,
noBrowser: true,
authToken: undefined,
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
});
}),
);
});
-37
View File
@@ -1,37 +0,0 @@
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");
}),
);
});
-368
View File
@@ -1,368 +0,0 @@
import { NetService } from "@t3tools/shared/Net";
import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect";
import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
import {
DEFAULT_PORT,
deriveServerPaths,
ensureServerDirectories,
resolveStaticDir,
ServerConfig,
RuntimeMode,
type ServerConfigShape,
} from "./config";
import { readBootstrapEnvelope } from "./bootstrap";
import { expandHomePath, 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),
otlpTracesUrl: Schema.optional(Schema.String),
otlpMetricsUrl: Schema.optional(Schema.String),
});
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")),
traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
Config.withDefault(10_000),
),
otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
Config.option,
Config.map(Option.getOrUndefined),
),
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 cwd: 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);
const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
const fs = yield* FileSystem.FileSystem;
const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
if (!exists) {
return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
}
const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
return parsePersistedServerObservabilitySettings(raw);
});
export const resolveServerConfig = (
flags: CliServerFlags,
cliLogLevel: Option.Option<LogLevel.LogLevel>,
) =>
Effect.gen(function* () {
const { findAvailablePort } = yield* NetService;
const path = yield* Path.Path;
const fs = yield* FileSystem.FileSystem;
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 rawCwd = Option.getOrElse(flags.cwd, () => process.cwd());
const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
yield* fs.makeDirectory(cwd, { recursive: true });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
derivedPaths.settingsPath,
);
const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
const 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,
traceMinLevel: env.traceMinLevel,
traceTimingEnabled: env.traceTimingEnabled,
traceBatchWindowMs: env.traceBatchWindowMs,
traceMaxBytes: env.traceMaxBytes,
traceMaxFiles: env.traceMaxFiles,
otlpTracesUrl:
env.otlpTracesUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
),
) ??
persistedObservabilitySettings.otlpTracesUrl,
otlpMetricsUrl:
env.otlpMetricsUrl ??
Option.getOrUndefined(
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
),
) ??
persistedObservabilitySettings.otlpMetricsUrl,
otlpExportIntervalMs: env.otlpExportIntervalMs,
otlpServiceName: env.otlpServiceName,
mode,
port,
cwd,
baseDir,
...derivedPaths,
serverTracePath,
host,
staticDir,
devUrl,
noBrowser,
authToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
};
return config;
});
const commandFlags = {
mode: modeFlag,
port: portFlag,
host: hostFlag,
baseDir: baseDirFlag,
cwd: Argument.string("cwd").pipe(
Argument.withDescription(
"Working directory for provider sessions (defaults to the current directory).",
),
Argument.optional,
),
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
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;
+2 -25
View File
@@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
});
});
it("disables spark for api key accounts", () => {
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
@@ -318,20 +318,7 @@ describe("readCodexAccountSnapshot", () => {
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: false,
});
});
it("disables spark for unknown chatgpt plans", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
}),
).toEqual({
type: "chatgpt",
planType: "unknown",
sparkEnabled: false,
sparkEnabled: true,
});
});
});
@@ -356,16 +343,6 @@ describe("resolveCodexModelForAccount", () => {
}),
).toBe("gpt-5.3-codex-spark");
});
it("falls back from spark to default for api key auth", () => {
expect(
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
type: "apiKey",
planType: null,
sparkEnabled: false,
}),
).toBe("gpt-5.3-codex");
});
});
describe("startSession", () => {
+94 -10
View File
@@ -26,15 +26,6 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "./provider/codexCliVersion";
import {
readCodexAccountSnapshot,
resolveCodexModelForAccount,
type CodexAccountSnapshot,
} from "./provider/codexAccount";
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
export { buildCodexInitializeParams } from "./provider/codexAppServer";
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
type PendingRequestKey = string;
@@ -105,6 +96,23 @@ interface JsonRpcNotification {
params?: unknown;
}
type CodexPlanType =
| "free"
| "go"
| "plus"
| "pro"
| "team"
| "business"
| "enterprise"
| "edu"
| "unknown";
interface CodexAccountSnapshot {
readonly type: "apiKey" | "chatgpt" | "unknown";
readonly planType: CodexPlanType | null;
readonly sparkEnabled: boolean;
}
export interface CodexAppServerSendTurnInput {
readonly threadId: ThreadId;
readonly input?: string;
@@ -154,6 +162,50 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
"unknown thread",
"does not exist",
];
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
function asObject(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object") {
return undefined;
}
return value as Record<string, unknown>;
}
function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
const record = asObject(response);
const account = asObject(record?.account) ?? record;
const accountType = asString(account?.type);
if (accountType === "apiKey") {
return {
type: "apiKey",
planType: null,
sparkEnabled: true,
};
}
if (accountType === "chatgpt") {
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
return {
type: "chatgpt",
planType,
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
};
}
return {
type: "unknown",
planType: null,
sparkEnabled: true,
};
}
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
@@ -306,13 +358,32 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
};
}
export function resolveCodexModelForAccount(
model: string | undefined,
account: CodexAccountSnapshot,
): string | undefined {
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
return model;
}
return CODEX_DEFAULT_MODEL;
}
/**
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
* entire process tree instead.
*/
function killChildTree(child: ChildProcessWithoutNullStreams): void {
killCodexChildProcess(child);
if (process.platform === "win32" && child.pid !== undefined) {
try {
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
return;
} catch {
// fallback to direct kill
}
}
child.kill();
}
export function normalizeCodexModelSlug(
@@ -331,6 +402,19 @@ export function normalizeCodexModelSlug(
return normalized;
}
export function buildCodexInitializeParams() {
return {
clientInfo: {
name: "t3code_desktop",
title: "T3 Code Desktop",
version: "0.1.0",
},
capabilities: {
experimentalApi: true,
},
} as const;
}
function buildCodexCollaborationMode(input: {
readonly interactionMode?: "default" | "plan";
readonly model?: string;
+6 -46
View File
@@ -6,12 +6,11 @@
*
* @module ServerConfig
*/
import { Effect, FileSystem, Layer, LogLevel, Path, Schema, ServiceMap } from "effect";
import { Effect, FileSystem, Layer, Path, ServiceMap } from "effect";
export const DEFAULT_PORT = 3773;
export const RuntimeMode = Schema.Literals(["web", "desktop"]);
export type RuntimeMode = typeof RuntimeMode.Type;
export type RuntimeMode = "web" | "desktop";
/**
* ServerDerivedPaths - Derived paths from the base directory.
@@ -25,7 +24,6 @@ export interface ServerDerivedPaths {
readonly attachmentsDir: string;
readonly logsDir: string;
readonly serverLogPath: string;
readonly serverTracePath: string;
readonly providerLogsDir: string;
readonly providerEventLogPath: string;
readonly terminalLogsDir: string;
@@ -36,16 +34,6 @@ export interface ServerDerivedPaths {
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape extends ServerDerivedPaths {
readonly logLevel: LogLevel.LogLevel;
readonly traceMinLevel: LogLevel.LogLevel;
readonly traceTimingEnabled: boolean;
readonly traceBatchWindowMs: number;
readonly traceMaxBytes: number;
readonly traceMaxFiles: number;
readonly otlpTracesUrl: string | undefined;
readonly otlpMetricsUrl: string | undefined;
readonly otlpExportIntervalMs: number;
readonly otlpServiceName: string;
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
@@ -78,7 +66,6 @@ export const deriveServerPaths = Effect.fn(function* (
attachmentsDir,
logsDir,
serverLogPath: join(logsDir, "server.log"),
serverTracePath: join(logsDir, "server.trace.ndjson"),
providerLogsDir,
providerEventLogPath: join(providerLogsDir, "events.log"),
terminalLogsDir: join(logsDir, "terminals"),
@@ -86,26 +73,6 @@ 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.
*/
@@ -124,19 +91,12 @@ export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigS
? baseDirOrPrefix
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* ensureServerDirectories(derivedPaths);
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
return {
logLevel: "Error",
traceMinLevel: "Info",
traceTimingEnabled: true,
traceBatchWindowMs: 200,
traceMaxBytes: 10 * 1024 * 1024,
traceMaxFiles: 10,
otlpTracesUrl: undefined,
otlpMetricsUrl: undefined,
otlpExportIntervalMs: 10_000,
otlpServiceName: "t3-server",
cwd,
baseDir,
...derivedPaths,
+67
View File
@@ -0,0 +1,67 @@
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;
+118 -113
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 "@t3tools/contracts";
import { TextGenerationError } from "../Errors.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
@@ -29,9 +29,8 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -66,7 +65,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
const runClaudeJson = Effect.fn("runClaudeJson")(function* <S extends Schema.Top>({
const runClaudeJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -82,126 +81,132 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
}): 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 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)),
},
},
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptions(
modelSelection.model,
modelSelection.options,
);
const settings = {
...(typeof normalizedOptions?.thinking === "boolean"
? { alwaysThinkingEnabled: normalizedOptions.thinking }
: {}),
...(normalizedOptions?.fastMode ? { fastMode: true } : {}),
};
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
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 [stdout, stderr, exitCode] = yield* Effect.all(
[
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to read Claude CLI exit code"),
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
),
],
{ 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",
),
),
),
],
{ 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
? `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),
}),
),
);
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}.`,
});
}
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 stdout;
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,
}),
),
),
);
});
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),
}),
),
);
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,
}),
),
),
);
});
// ---------------------------------------------------------------------------
// TextGenerationShape methods
// ---------------------------------------------------------------------------
@@ -5,7 +5,7 @@ import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
+153 -152
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 "@t3tools/contracts";
import { TextGenerationError } from "../Errors.ts";
import {
type BranchNameGenerationInput,
type ThreadTitleGenerationResult,
@@ -28,9 +28,8 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
@@ -85,43 +84,44 @@ const makeCodexTextGeneration = Effect.gen(function* () {
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
fileSystem.remove(filePath).pipe(Effect.catch(() => Effect.void));
const materializeImageAttachments = Effect.fn("materializeImageAttachments")(function* (
const materializeImageAttachments = (
_operation:
| "generateCommitMessage"
| "generatePrContent"
| "generateBranchName"
| "generateThreadTitle",
attachments: BranchNameGenerationInput["attachments"],
): 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;
): Effect.Effect<MaterializedImageAttachments, TextGenerationError> =>
Effect.gen(function* () {
if (!attachments || attachments.length === 0) {
return { imagePaths: [] };
}
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);
}
return { imagePaths };
});
const imagePaths: string[] = [];
for (const attachment of attachments) {
if (attachment.type !== "image") {
continue;
}
const runCodexJson = Effect.fn("runCodexJson")(function* <S extends Schema.Top>({
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);
}
return { imagePaths };
});
const runCodexJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
@@ -141,138 +141,139 @@ const makeCodexTextGeneration = Effect.gen(function* () {
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: CodexModelSelection;
}): 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,
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
);
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
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 = normalizeCodexModelOptions(
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 } : {}),
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)),
},
},
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 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,
}),
),
);
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"),
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,
}),
),
),
],
{ 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}.`,
});
}
);
}).pipe(Effect.ensuring(cleanup));
});
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,
}),
),
),
);
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CodexTextGeneration.generateCommitMessage",
)(function* (input) {
+88 -424
View File
@@ -1,14 +1,15 @@
import { existsSync } from "node:fs";
import os from "node:os";
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 { Cause, Effect, Exit, FileSystem, Layer, PlatformError, Scope } from "effect";
import { describe, expect, vi } from "vitest";
import { GitCoreLive, makeGitCore } from "./GitCore.ts";
import { GitCore, type GitCoreShape } from "../Services/GitCore.ts";
import { GitCommandError } from "@t3tools/contracts";
import { GitCommandError } from "../Errors.ts";
import { type ProcessRunResult, runProcess } from "../../processRunner.ts";
import { ServerConfig } from "../../config.ts";
@@ -59,23 +60,6 @@ function git(
});
}
function configureRemote(
cwd: string,
remoteName: string,
remotePath: string,
fetchNamespace: string,
): Effect.Effect<string, GitCommandError, GitCore> {
return Effect.gen(function* () {
yield* git(cwd, ["config", `remote.${remoteName}.url`, remotePath]);
return yield* git(cwd, [
"config",
"--replace-all",
`remote.${remoteName}.fetch`,
`+refs/heads/*:refs/remotes/${fetchNamespace}/*`,
]);
});
}
function runShellCommand(input: {
command: string;
cwd: string;
@@ -155,13 +139,6 @@ function buildLargeText(lineCount = 20_000): string {
.concat("\n");
}
function splitNullSeparatedPaths(input: string): string[] {
return input
.split("\0")
.map((value) => value.trim())
.filter((value) => value.length > 0);
}
// ── Tests ──
it.layer(TestLayer)("git integration", (it) => {
@@ -205,55 +182,6 @@ it.layer(TestLayer)("git integration", (it) => {
);
});
describe("workspace helpers", () => {
it.effect("filterIgnoredPaths chunks large path lists and preserves kept paths", () =>
Effect.gen(function* () {
const cwd = "/virtual/repo";
const relativePaths = Array.from({ length: 340 }, (_, index) => {
const prefix = index % 3 === 0 ? "ignored" : "kept";
return `${prefix}/segment-${String(index).padStart(4, "0")}/${"x".repeat(900)}.ts`;
});
const expectedPaths = relativePaths.filter(
(relativePath) => !relativePath.startsWith("ignored/"),
);
const seenChunks: string[][] = [];
const core = yield* makeIsolatedGitCore((input) => {
if (input.args.join(" ") !== "check-ignore --no-index -z --stdin") {
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "unexpected git command in chunking test",
}),
);
}
const chunkPaths = splitNullSeparatedPaths(input.stdin ?? "");
seenChunks.push(chunkPaths);
const ignoredPaths = chunkPaths.filter((relativePath) =>
relativePath.startsWith("ignored/"),
);
return Effect.succeed({
code: ignoredPaths.length > 0 ? 0 : 1,
stdout: ignoredPaths.length > 0 ? `${ignoredPaths.join("\0")}\0` : "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
});
const result = yield* core.filterIgnoredPaths(cwd, relativePaths);
expect(seenChunks.length).toBeGreaterThan(1);
expect(seenChunks.flat()).toEqual(relativePaths);
expect(result).toEqual(expectedPaths);
}),
);
});
// ── listGitBranches ──
describe("listGitBranches", () => {
@@ -386,94 +314,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("paginates branch results and returns paging metadata", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-a" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-b" });
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature-c" });
const firstPage = yield* (yield* GitCore).listBranches({ cwd: tmp, limit: 2 });
expect(firstPage.totalCount).toBe(4);
expect(firstPage.nextCursor).toBe(2);
expect(firstPage.branches.map((branch) => branch.name)).toEqual([
initialBranch,
"feature-a",
]);
const secondPage = yield* (yield* GitCore).listBranches({
cwd: tmp,
cursor: firstPage.nextCursor ?? 0,
limit: 2,
});
expect(secondPage.totalCount).toBe(4);
expect(secondPage.nextCursor).toBeNull();
expect(secondPage.branches.map((branch) => branch.name)).toEqual([
"feature-b",
"feature-c",
]);
}),
);
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();
@@ -561,41 +401,6 @@ it.layer(TestLayer)("git integration", (it) => {
expect(remoteBranch?.remoteName).toBe(remoteName);
}),
);
it.effect(
"filters branch queries before pagination and dedupes origin refs with local matches",
() =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const tmp = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* git(tmp, ["remote", "add", "origin", remote]);
yield* git(tmp, ["push", "-u", "origin", initialBranch]);
yield* (yield* GitCore).createBranch({ cwd: tmp, branch: "feature/demo" });
yield* git(tmp, ["push", "-u", "origin", "feature/demo"]);
yield* git(tmp, ["checkout", "-b", "feature/remote-only"]);
yield* git(tmp, ["push", "-u", "origin", "feature/remote-only"]);
yield* git(tmp, ["checkout", initialBranch]);
yield* git(tmp, ["branch", "-D", "feature/remote-only"]);
const result = yield* (yield* GitCore).listBranches({
cwd: tmp,
query: "feature/",
limit: 10,
});
expect(result.totalCount).toBe(2);
expect(result.nextCursor).toBeNull();
expect(result.branches.map((branch) => branch.name)).toEqual([
"feature/demo",
"origin/feature/remote-only",
]);
}),
);
});
// ── checkoutGitBranch ──
@@ -653,23 +458,17 @@ it.layer(TestLayer)("git integration", (it) => {
yield* (yield* GitCore).checkoutBranch({ cwd: source, branch: featureBranch });
const core = yield* GitCore;
yield* Effect.promise(() =>
vi.waitFor(
async () => {
const details = await runPromise(core.statusDetails(source));
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
},
{
timeout: 10_000,
interval: 100,
},
),
vi.waitFor(async () => {
const details = await runPromise(core.statusDetails(source));
expect(details.branch).toBe(featureBranch);
expect(details.aheadCount).toBe(0);
expect(details.behindCount).toBe(1);
}),
);
}),
);
it.effect("statusDetails remains successful when upstream refresh fails after checkout", () =>
it.effect("keeps checkout successful when upstream refresh fails", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -694,7 +493,7 @@ it.layer(TestLayer)("git integration", (it) => {
const realGitCore = yield* GitCore;
let refreshFetchAttempts = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
if (input.args[0] === "fetch") {
refreshFetchAttempts += 1;
return Effect.fail(
new GitCommandError({
@@ -708,15 +507,16 @@ it.layer(TestLayer)("git integration", (it) => {
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
const status = yield* core.statusDetails(source);
expect(refreshFetchAttempts).toBe(1);
expect(status.branch).toBe(featureBranch);
expect(status.upstreamRef).toBe(`origin/${featureBranch}`);
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(refreshFetchAttempts).toBe(1);
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
}),
);
it.effect("defers upstream refresh until statusDetails is requested", () =>
it.effect("refresh fetch is scoped to the checked out branch upstream refspec", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
@@ -738,152 +538,76 @@ it.layer(TestLayer)("git integration", (it) => {
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let refreshFetchAttempts = 0;
let fetchArgs: readonly string[] | null = null;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
refreshFetchAttempts += 1;
return Effect.succeed({
code: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
if (input.args[0] === "fetch") {
fetchArgs = [...input.args];
return Effect.succeed({ code: 0, stdout: "", stderr: "" });
}
return realGitCore.execute(input);
});
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() => new Promise<void>((resolve) => setTimeout(resolve, 50)));
expect(refreshFetchAttempts).toBe(0);
const status = yield* core.statusDetails(source);
expect(status.branch).toBe(featureBranch);
expect(refreshFetchAttempts).toBe(1);
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchArgs).not.toBeNull();
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
expect(fetchArgs).toEqual([
"fetch",
"--quiet",
"--no-tags",
"origin",
`+refs/heads/${featureBranch}:refs/remotes/origin/${featureBranch}`,
]);
}),
);
it.effect("shares upstream refreshes across worktrees that use the same git common dir", () =>
it.effect("returns checkout result before background upstream refresh completes", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
const remote = yield* makeTmpDir();
const source = yield* makeTmpDir();
yield* git(remote, ["init", "--bare"]);
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
expect(input.cwd).toBe("/repo");
return ok();
}
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in shared refresh cache test.",
}),
);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* git(source, ["remote", "add", "origin", remote]);
yield* git(source, ["push", "-u", "origin", defaultBranch]);
const featureBranch = "feature/background-refresh";
yield* git(source, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(source, "feature.txt"), "feature base\n");
yield* git(source, ["add", "feature.txt"]);
yield* git(source, ["commit", "-m", "feature base"]);
yield* git(source, ["push", "-u", "origin", featureBranch]);
yield* git(source, ["checkout", defaultBranch]);
const realGitCore = yield* GitCore;
let fetchStarted = false;
let releaseFetch!: () => void;
const waitForReleasePromise = new Promise<void>((resolve) => {
releaseFetch = resolve;
});
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
}),
);
it.effect("briefly backs off failed upstream refreshes across sibling worktrees", () =>
Effect.gen(function* () {
const ok = (stdout = "") =>
Effect.succeed({
code: 0,
stdout,
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
let fetchCount = 0;
const core = yield* makeIsolatedGitCore((input) => {
if (
input.args[0] === "rev-parse" &&
input.args[1] === "--abbrev-ref" &&
input.args[2] === "--symbolic-full-name" &&
input.args[3] === "@{upstream}"
) {
return ok("origin/main\n");
}
if (input.args[0] === "remote") {
return ok("origin\n");
}
if (input.args[0] === "rev-parse" && input.args[1] === "--git-common-dir") {
return ok("/repo/.git\n");
}
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchCount += 1;
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "simulated fetch timeout",
}),
if (input.args[0] === "fetch") {
fetchStarted = true;
return Effect.promise(() =>
waitForReleasePromise.then(() => ({ code: 0, stdout: "", stderr: "" })),
);
}
if (input.operation === "GitCore.statusDetails.status") {
return ok("# branch.head main\n# branch.upstream origin/main\n# branch.ab +0 -0\n");
}
if (
input.operation === "GitCore.statusDetails.unstagedNumstat" ||
input.operation === "GitCore.statusDetails.stagedNumstat"
) {
return ok();
}
if (input.operation === "GitCore.statusDetails.defaultRef") {
return ok("refs/remotes/origin/main\n");
}
return Effect.fail(
new GitCommandError({
operation: input.operation,
command: `git ${input.args.join(" ")}`,
cwd: input.cwd,
detail: "Unexpected git command in refresh failure cooldown test.",
}),
);
return realGitCore.execute(input);
});
yield* core.statusDetails("/repo/worktrees/main");
yield* core.statusDetails("/repo/worktrees/pr-123");
expect(fetchCount).toBe(1);
yield* core.checkoutBranch({ cwd: source, branch: featureBranch });
yield* Effect.promise(() =>
vi.waitFor(() => {
expect(fetchStarted).toBe(true);
}),
);
expect(yield* git(source, ["branch", "--show-current"])).toBe(featureBranch);
releaseFetch();
}),
);
@@ -924,21 +648,16 @@ it.layer(TestLayer)("git integration", (it) => {
it.effect("checks out a remote tracking branch when remote name contains slashes", () =>
Effect.gen(function* () {
const remote = yield* makeTmpDir();
const prefixRemote = yield* makeTmpDir();
const source = yield* makeTmpDir();
const prefixFetchNamespace = "prefix-my-org";
const prefixRemoteName = "my-org";
const remoteName = "my-org/upstream";
const featureBranch = "feature";
yield* git(remote, ["init", "--bare"]);
yield* git(prefixRemote, ["init", "--bare"]);
yield* initRepoWithCommit(source);
const defaultBranch = (yield* (yield* GitCore).listBranches({ cwd: source })).branches.find(
(branch) => branch.current,
)!.name;
yield* configureRemote(source, prefixRemoteName, prefixRemote, prefixFetchNamespace);
yield* configureRemote(source, remoteName, remote, remoteName);
yield* git(source, ["remote", "add", remoteName, remote]);
yield* git(source, ["push", "-u", remoteName, defaultBranch]);
yield* git(source, ["checkout", "-b", featureBranch]);
@@ -955,34 +674,6 @@ it.layer(TestLayer)("git integration", (it) => {
});
expect(yield* git(source, ["branch", "--show-current"])).toBe("upstream/feature");
const realGitCore = yield* GitCore;
let fetchArgs: readonly string[] | null = null;
const core = yield* makeIsolatedGitCore((input) => {
if (input.args[0] === "--git-dir" && input.args[2] === "fetch") {
fetchArgs = [...input.args];
return Effect.succeed({
code: 0,
stdout: "",
stderr: "",
stdoutTruncated: false,
stderrTruncated: false,
});
}
return realGitCore.execute(input);
});
const status = yield* core.statusDetails(source);
expect(status.branch).toBe("upstream/feature");
expect(status.upstreamRef).toBe(`${remoteName}/${featureBranch}`);
expect(fetchArgs).toEqual([
"--git-dir",
path.join(source, ".git"),
"fetch",
"--quiet",
"--no-tags",
remoteName,
`+refs/heads/${featureBranch}:refs/remotes/${remoteName}/${featureBranch}`,
]);
}),
);
@@ -1593,6 +1284,20 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("fails cleanly when statusDetails is requested for a missing workspace", () =>
Effect.gen(function* () {
const missingCwd = path.join(os.tmpdir(), `git-missing-${crypto.randomUUID()}`);
const result = yield* Effect.exit((yield* GitCore).statusDetails(missingCwd));
expect(Exit.isFailure(result)).toBe(true);
if (Exit.isFailure(result)) {
const error = Cause.squash(result.cause);
expect(error).toBeInstanceOf(GitCommandError);
expect((error as GitCommandError).detail).toContain("Workspace folder is missing");
}
}),
);
it.effect("computes ahead count against base branch when no upstream is configured", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -1869,47 +1574,6 @@ it.layer(TestLayer)("git integration", (it) => {
}),
);
it.effect("pushes to the tracked upstream when the remote name contains slashes", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
const remote = yield* makeTmpDir();
const prefixRemote = yield* makeTmpDir();
const prefixFetchNamespace = "prefix-my-org";
const prefixRemoteName = "my-org";
const remoteName = "my-org/upstream";
const featureBranch = "feature/slash-remote-push";
yield* git(remote, ["init", "--bare"]);
yield* git(prefixRemote, ["init", "--bare"]);
const { initialBranch } = yield* initRepoWithCommit(tmp);
yield* configureRemote(tmp, prefixRemoteName, prefixRemote, prefixFetchNamespace);
yield* configureRemote(tmp, remoteName, remote, remoteName);
yield* git(tmp, ["push", "-u", remoteName, initialBranch]);
yield* git(tmp, ["checkout", "-b", featureBranch]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "first revision\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature base"]);
yield* git(tmp, ["push", "-u", remoteName, featureBranch]);
yield* writeTextFile(path.join(tmp, "feature.txt"), "second revision\n");
yield* git(tmp, ["add", "feature.txt"]);
yield* git(tmp, ["commit", "-m", "feature update"]);
const core = yield* GitCore;
const pushed = yield* core.pushCurrentBranch(tmp, null);
expect(pushed.status).toBe("pushed");
expect(pushed.setUpstream).toBe(false);
expect(pushed.upstreamBranch).toBe(`${remoteName}/${featureBranch}`);
expect(yield* git(tmp, ["rev-parse", "--abbrev-ref", "@{upstream}"])).toBe(
`${remoteName}/${featureBranch}`,
);
expect(yield* git(tmp, ["ls-remote", "--heads", remoteName, featureBranch])).toContain(
featureBranch,
);
}),
);
it.effect("includes command context when worktree removal fails", () =>
Effect.gen(function* () {
const tmp = yield* makeTmpDir();
@@ -2175,7 +1839,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 --no-column --remotes") {
if (input.args.join(" ") === "branch --no-color --remotes") {
didFailRemoteBranches = true;
return Effect.fail(
new GitCommandError({
+141 -385
View File
@@ -18,10 +18,7 @@ import {
} from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError, type GitBranch } from "@t3tools/contracts";
import { dedupeRemoteBranchesWithLocalMatches } from "@t3tools/shared/git";
import { compactTraceAttributes } from "../../observability/Attributes.ts";
import { gitCommandDuration, gitCommandsTotal, withMetrics } from "../../observability/Metrics.ts";
import { GitCommandError } from "../Errors.ts";
import {
GitCore,
type ExecuteGitProgress,
@@ -30,13 +27,9 @@ import {
type ExecuteGitInput,
type ExecuteGitResult,
} from "../Services/GitCore.ts";
import {
parseRemoteNames,
parseRemoteNamesInGitOrder,
parseRemoteRefWithRemoteNames,
} from "../remoteRefs.ts";
import { ServerConfig } from "../../config.ts";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
@@ -45,14 +38,10 @@ const PREPARED_COMMIT_PATCH_MAX_OUTPUT_BYTES = 49_000;
const RANGE_COMMIT_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
const RANGE_DIFF_SUMMARY_MAX_OUTPUT_BYTES = 19_000;
const RANGE_DIFF_PATCH_MAX_OUTPUT_BYTES = 59_000;
const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
const GIT_CHECK_IGNORE_MAX_STDIN_BYTES = 256 * 1024;
const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15);
const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5);
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
const GIT_LIST_BRANCHES_DEFAULT_LIMIT = 100;
type TraceTailState = {
processedChars: number;
@@ -60,14 +49,13 @@ type TraceTailState = {
};
class StatusUpstreamRefreshCacheKey extends Data.Class<{
gitCommonDir: string;
cwd: string;
upstreamRef: string;
remoteName: string;
upstreamBranch: string;
}> {}
interface ExecuteGitOptions {
stdin?: string | undefined;
timeoutMs?: number | undefined;
allowNonZeroExit?: boolean | undefined;
fallbackErrorMessage?: string | undefined;
@@ -109,47 +97,6 @@ function parseNumstatEntries(
return entries;
}
function splitNullSeparatedPaths(input: string, truncated: boolean): string[] {
const parts = input.split("\0");
if (parts.length === 0) return [];
if (truncated && parts[parts.length - 1]?.length) {
parts.pop();
}
return parts.filter((value) => value.length > 0);
}
function chunkPathsForGitCheckIgnore(relativePaths: readonly string[]): string[][] {
const chunks: string[][] = [];
let chunk: string[] = [];
let chunkBytes = 0;
for (const relativePath of relativePaths) {
const relativePathBytes = Buffer.byteLength(relativePath) + 1;
if (chunk.length > 0 && chunkBytes + relativePathBytes > GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
chunk.push(relativePath);
chunkBytes += relativePathBytes;
if (chunkBytes >= GIT_CHECK_IGNORE_MAX_STDIN_BYTES) {
chunks.push(chunk);
chunk = [];
chunkBytes = 0;
}
}
if (chunk.length > 0) {
chunks.push(chunk);
}
return chunks;
}
function parsePorcelainPath(line: string): string | null {
if (line.startsWith("? ") || line.startsWith("! ")) {
const simple = line.slice(2).trim();
@@ -187,38 +134,12 @@ function parseBranchLine(line: string): { name: string; current: boolean } | nul
};
}
function filterBranchesForListQuery(
branches: ReadonlyArray<GitBranch>,
query?: string,
): ReadonlyArray<GitBranch> {
if (!query) {
return branches;
}
const normalizedQuery = query.toLowerCase();
return branches.filter((branch) => branch.name.toLowerCase().includes(normalizedQuery));
}
function paginateBranches(input: {
branches: ReadonlyArray<GitBranch>;
cursor?: number | undefined;
limit?: number | undefined;
}): {
branches: ReadonlyArray<GitBranch>;
nextCursor: number | null;
totalCount: number;
} {
const cursor = input.cursor ?? 0;
const limit = input.limit ?? GIT_LIST_BRANCHES_DEFAULT_LIMIT;
const totalCount = input.branches.length;
const branches = input.branches.slice(cursor, cursor + limit);
const nextCursor = cursor + branches.length < totalCount ? cursor + branches.length : null;
return {
branches,
nextCursor,
totalCount,
};
function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.toSorted((a, b) => b.length - a.length);
}
function sanitizeRemoteName(value: string): string {
@@ -253,41 +174,30 @@ function parseRemoteFetchUrls(stdout: string): Map<string, string> {
return remotes;
}
function parseUpstreamRefWithRemoteNames(
upstreamRef: string,
function parseRemoteRefWithRemoteNames(
branchName: string,
remoteNames: ReadonlyArray<string>,
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
const parsed = parseRemoteRefWithRemoteNames(upstreamRef, remoteNames);
if (!parsed) {
return null;
): { remoteRef: string; remoteName: string; localBranch: string } | null {
const trimmedBranchName = branchName.trim();
if (trimmedBranchName.length === 0) return null;
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedBranchName.startsWith(remotePrefix)) {
continue;
}
const localBranch = trimmedBranchName.slice(remotePrefix.length).trim();
if (localBranch.length === 0) {
return null;
}
return {
remoteRef: trimmedBranchName,
remoteName,
localBranch,
};
}
return {
upstreamRef,
remoteName: parsed.remoteName,
upstreamBranch: parsed.branchName,
};
}
function parseUpstreamRefByFirstSeparator(
upstreamRef: string,
): { upstreamRef: string; remoteName: string; upstreamBranch: string } | null {
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0 || separatorIndex === upstreamRef.length - 1) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex).trim();
const upstreamBranch = upstreamRef.slice(separatorIndex + 1).trim();
if (remoteName.length === 0 || upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
return null;
}
function parseTrackingBranchByUpstreamRef(stdout: string, upstreamRef: string): string | null {
@@ -374,18 +284,6 @@ interface Trace2Monitor {
readonly flush: Effect.Effect<void, never>;
}
const nowUnixNano = (): bigint => BigInt(Date.now()) * 1_000_000n;
const addCurrentSpanEvent = (name: string, attributes: Record<string, unknown>) =>
Effect.currentSpan.pipe(
Effect.tap((span) =>
Effect.sync(() => {
span.event(name, nowUnixNano(), compactTraceAttributes(attributes));
}),
),
Effect.catch(() => Effect.void),
);
function trace2ChildKey(record: Record<string, unknown>): string | null {
const childId = record.child_id;
if (typeof childId === "number" || typeof childId === "string") {
@@ -458,9 +356,6 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
if (event === "child_start") {
hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
yield* addCurrentSpanEvent("git.hook.started", {
hookName,
});
if (progress.onHookStarted) {
yield* progress.onHookStarted(hookName);
}
@@ -469,19 +364,12 @@ const createTrace2Monitor = Effect.fn("createTrace2Monitor")(function* (
if (event === "child_exit") {
hookStartByChildKey.delete(childKey);
const code = traceRecord.success.code;
const exitCode = typeof code === "number" && Number.isInteger(code) ? code : null;
const durationMs = started ? Math.max(0, Date.now() - started.startedAtMs) : null;
yield* addCurrentSpanEvent("git.hook.finished", {
hookName: started?.hookName ?? hookName,
exitCode,
durationMs,
});
if (progress.onHookFinished) {
const code = traceRecord.success.code;
yield* progress.onHookFinished({
hookName: started?.hookName ?? hookName,
exitCode,
durationMs,
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
});
}
}
@@ -558,7 +446,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
maxOutputBytes: number,
truncateOutputAtMaxBytes: boolean,
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
): Effect.fn.Return<{ readonly text: string; readonly truncated: boolean }, GitCommandError> {
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
@@ -620,10 +508,7 @@ const collectOutput = Effect.fn("collectOutput")(function* <E>(
text += remainder;
lineBuffer += remainder;
yield* emitCompleteLines(true);
return {
text,
truncated,
};
return truncated ? `${text}${OUTPUT_TRUNCATED_MARKER}` : text;
});
export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
@@ -633,13 +518,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const path = yield* Path.Path;
const { worktreesDir } = yield* ServerConfig;
let executeRaw: GitCoreShape["execute"];
let execute: GitCoreShape["execute"];
let rawExecute: GitCoreShape["execute"];
if (options?.executeOverride) {
executeRaw = options.executeOverride;
rawExecute = options.executeOverride;
} else {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
executeRaw = Effect.fnUntraced(function* (input) {
rawExecute = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
@@ -687,18 +573,13 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
input.stdin === undefined
? Effect.void
: Stream.run(Stream.encodeText(Stream.make(input.stdin)), child.stdin).pipe(
Effect.mapError(toGitCommandError(commandInput, "failed to write stdin.")),
),
],
{ concurrency: "unbounded" },
).pipe(Effect.map(([stdout, stderr, exitCode]) => [stdout, stderr, exitCode] as const));
);
yield* trace2Monitor.flush;
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.text.trim();
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
@@ -710,13 +591,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
}
return {
code: exitCode,
stdout: stdout.text,
stderr: stderr.text,
stdoutTruncated: stdout.truncated,
stderrTruncated: stderr.truncated,
} satisfies ExecuteGitResult;
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
});
return yield* runGitCommand().pipe(
@@ -740,36 +615,32 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
}
const execute: GitCoreShape["execute"] = (input) =>
executeRaw(input).pipe(
withMetrics({
counter: gitCommandsTotal,
timer: gitCommandDuration,
attributes: {
operation: input.operation,
},
}),
Effect.withSpan(input.operation, {
kind: "client",
attributes: {
"git.operation": input.operation,
"git.cwd": input.cwd,
"git.args_count": input.args.length,
},
}),
execute = Effect.fnUntraced(function* (input) {
yield* assertWorkspaceDirectory(input.cwd, input.operation).pipe(
Effect.mapError(
(error) =>
new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: error.message,
cause: error,
}),
),
);
return yield* rawExecute(input);
});
const executeGit = (
operation: string,
cwd: string,
args: readonly string[],
options: ExecuteGitOptions = {},
): Effect.Effect<ExecuteGitResult, GitCommandError> =>
): Effect.Effect<{ code: number; stdout: string; stderr: string }, GitCommandError> =>
execute({
operation,
cwd,
args,
...(options.stdin !== undefined ? { stdin: options.stdin } : {}),
allowNonZeroExit: true,
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
...(options.maxOutputBytes !== undefined ? { maxOutputBytes: options.maxOutputBytes } : {}),
@@ -802,6 +673,20 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
}),
);
const ensureGitWorkspace = (operation: string, cwd: string, args: readonly string[] = []) =>
assertWorkspaceDirectory(cwd, operation).pipe(
Effect.mapError(
(error) =>
new GitCommandError({
operation,
command: quoteGitCommand(args),
cwd,
detail: error.message,
cause: error,
}),
),
);
const runGit = (
operation: string,
cwd: string,
@@ -826,11 +711,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
args: readonly string[],
options: ExecuteGitOptions = {},
): Effect.Effect<string, GitCommandError> =>
executeGit(operation, cwd, args, options).pipe(
Effect.map((result) =>
result.stdoutTruncated ? `${result.stdout}${OUTPUT_TRUNCATED_MARKER}` : result.stdout,
),
);
executeGit(operation, cwd, args, options).pipe(Effect.map((result) => result.stdout));
const branchExists = (cwd: string, branch: string): Effect.Effect<boolean, GitCommandError> =>
executeGit(
@@ -880,27 +761,45 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
return null;
}
const remoteNames = yield* runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map(parseRemoteNames),
Effect.catch(() => Effect.succeed<ReadonlyArray<string>>([])),
);
return (
parseUpstreamRefWithRemoteNames(upstreamRef, remoteNames) ??
parseUpstreamRefByFirstSeparator(upstreamRef)
);
const separatorIndex = upstreamRef.indexOf("/");
if (separatorIndex <= 0) {
return null;
}
const remoteName = upstreamRef.slice(0, separatorIndex);
const upstreamBranch = upstreamRef.slice(separatorIndex + 1);
if (remoteName.length === 0 || upstreamBranch.length === 0) {
return null;
}
return {
upstreamRef,
remoteName,
upstreamBranch,
};
});
const fetchUpstreamRefForStatus = (
gitCommonDir: string,
const fetchUpstreamRef = (
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
return runGit(
"GitCore.fetchUpstreamRef",
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
true,
);
};
const fetchUpstreamRefForStatus = (
cwd: string,
upstream: { upstreamRef: string; remoteName: string; upstreamBranch: string },
): Effect.Effect<void, GitCommandError> => {
const refspec = `+refs/heads/${upstream.upstreamBranch}:refs/remotes/${upstream.upstreamRef}`;
const fetchCwd =
path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir;
return executeGit(
"GitCore.fetchUpstreamRefForStatus",
fetchCwd,
["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
cwd,
["fetch", "--quiet", "--no-tags", upstream.remoteName, refspec],
{
allowNonZeroExit: true,
timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT),
@@ -908,18 +807,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
).pipe(Effect.asVoid);
};
const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) {
const gitCommonDir = yield* runGitStdout("GitCore.resolveGitCommonDir", cwd, [
"rev-parse",
"--git-common-dir",
]).pipe(Effect.map((stdout) => stdout.trim()));
return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir);
});
const refreshStatusUpstreamCacheEntry = Effect.fn("refreshStatusUpstreamCacheEntry")(function* (
cacheKey: StatusUpstreamRefreshCacheKey,
) {
yield* fetchUpstreamRefForStatus(cacheKey.gitCommonDir, {
yield* fetchUpstreamRefForStatus(cacheKey.cwd, {
upstreamRef: cacheKey.upstreamRef,
remoteName: cacheKey.remoteName,
upstreamBranch: cacheKey.upstreamBranch,
@@ -930,11 +821,8 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const statusUpstreamRefreshCache = yield* Cache.makeWith({
capacity: STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY,
lookup: refreshStatusUpstreamCacheEntry,
// Keep successful refreshes warm and briefly back off failed refreshes to avoid retry storms.
timeToLive: (exit) =>
Exit.isSuccess(exit)
? STATUS_UPSTREAM_REFRESH_INTERVAL
: STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN,
// Keep successful refreshes warm; drop failures immediately so next request can retry.
timeToLive: (exit) => (Exit.isSuccess(exit) ? STATUS_UPSTREAM_REFRESH_INTERVAL : Duration.zero),
});
const refreshStatusUpstreamIfStale = Effect.fn("refreshStatusUpstreamIfStale")(function* (
@@ -942,11 +830,10 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
const gitCommonDir = yield* resolveGitCommonDir(cwd);
yield* Cache.get(
statusUpstreamRefreshCache,
new StatusUpstreamRefreshCacheKey({
gitCommonDir,
cwd,
upstreamRef: upstream.upstreamRef,
remoteName: upstream.remoteName,
upstreamBranch: upstream.upstreamBranch,
@@ -954,6 +841,14 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
);
});
const refreshCheckedOutBranchUpstream = Effect.fn("refreshCheckedOutBranchUpstream")(function* (
cwd: string,
) {
const upstream = yield* resolveCurrentUpstream(cwd);
if (!upstream) return;
yield* fetchUpstreamRef(cwd, upstream);
});
const resolveDefaultBranchName = (
cwd: string,
remoteName: string,
@@ -993,7 +888,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const listRemoteNames = (cwd: string): Effect.Effect<ReadonlyArray<string>, GitCommandError> =>
runGitStdout("GitCore.listRemoteNames", cwd, ["remote"]).pipe(
Effect.map(parseRemoteNamesInGitOrder),
Effect.map((stdout) => parseRemoteNames(stdout).toReversed()),
);
const resolvePrimaryRemoteName = Effect.fn("resolvePrimaryRemoteName")(function* (cwd: string) {
@@ -1178,54 +1073,22 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
});
const statusDetails: GitCoreShape["statusDetails"] = Effect.fn("statusDetails")(function* (cwd) {
yield* ensureGitWorkspace("GitCore.statusDetails", cwd, [
"status",
"--porcelain=2",
"--branch",
]);
yield* refreshStatusUpstreamIfStale(cwd).pipe(Effect.ignoreCause({ log: true }));
const statusResult = yield* executeGit(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
{
allowNonZeroExit: true,
},
const [statusStdout, unstagedNumstatStdout, stagedNumstatStdout] = yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.status", cwd, ["status", "--porcelain=2", "--branch"]),
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, ["diff", "--cached", "--numstat"]),
],
{ concurrency: "unbounded" },
);
if (statusResult.code !== 0) {
const stderr = statusResult.stderr.trim();
return yield* createGitCommandError(
"GitCore.statusDetails.status",
cwd,
["status", "--porcelain=2", "--branch"],
stderr || "git status failed",
);
}
const [unstagedNumstatStdout, stagedNumstatStdout, defaultRefResult, hasOriginRemote] =
yield* Effect.all(
[
runGitStdout("GitCore.statusDetails.unstagedNumstat", cwd, ["diff", "--numstat"]),
runGitStdout("GitCore.statusDetails.stagedNumstat", cwd, [
"diff",
"--cached",
"--numstat",
]),
executeGit(
"GitCore.statusDetails.defaultRef",
cwd,
["symbolic-ref", "refs/remotes/origin/HEAD"],
{
allowNonZeroExit: true,
},
),
originRemoteExists(cwd).pipe(Effect.catch(() => Effect.succeed(false))),
],
{ concurrency: "unbounded" },
);
const statusStdout = statusResult.stdout;
const defaultBranch =
defaultRefResult.code === 0
? defaultRefResult.stdout.trim().replace(/^refs\/remotes\/origin\//, "")
: null;
let branch: string | null = null;
let upstreamRef: string | null = null;
let aheadCount = 0;
@@ -1292,12 +1155,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
files.sort((a, b) => a.path.localeCompare(b.path));
return {
isRepo: true,
hasOriginRemote,
isDefaultBranch:
branch !== null &&
(branch === defaultBranch ||
(defaultBranch === null && (branch === "main" || branch === "master"))),
branch,
upstreamRef,
hasWorkingTreeChanges,
@@ -1315,9 +1172,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const status: GitCoreShape["status"] = (input) =>
statusDetails(input.cwd).pipe(
Effect.map((details) => ({
isRepo: details.isRepo,
hasOriginRemote: details.hasOriginRemote,
isDefaultBranch: details.isDefaultBranch,
branch: details.branch,
hasWorkingTreeChanges: details.hasWorkingTreeChanges,
workingTree: details.workingTree,
@@ -1466,7 +1320,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
"push",
"-u",
publishRemoteName,
`HEAD:refs/heads/${branch}`,
branch,
]);
return {
status: "pushed" as const,
@@ -1599,86 +1453,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
Effect.map((trimmed) => (trimmed.length > 0 ? trimmed : null)),
);
const isInsideWorkTree: GitCoreShape["isInsideWorkTree"] = (cwd) =>
executeGit("GitCore.isInsideWorkTree", cwd, ["rev-parse", "--is-inside-work-tree"], {
allowNonZeroExit: true,
timeoutMs: 5_000,
maxOutputBytes: 4_096,
}).pipe(Effect.map((result) => result.code === 0 && result.stdout.trim() === "true"));
const listWorkspaceFiles: GitCoreShape["listWorkspaceFiles"] = (cwd) =>
executeGit(
"GitCore.listWorkspaceFiles",
cwd,
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
{
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
},
).pipe(
Effect.flatMap((result) =>
result.code === 0
? Effect.succeed({
paths: splitNullSeparatedPaths(result.stdout, result.stdoutTruncated),
truncated: result.stdoutTruncated,
})
: Effect.fail(
createGitCommandError(
"GitCore.listWorkspaceFiles",
cwd,
["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
result.stderr.trim().length > 0 ? result.stderr.trim() : "git ls-files failed",
),
),
),
);
const filterIgnoredPaths: GitCoreShape["filterIgnoredPaths"] = (cwd, relativePaths) =>
Effect.gen(function* () {
if (relativePaths.length === 0) {
return relativePaths;
}
const ignoredPaths = new Set<string>();
const chunks = chunkPathsForGitCheckIgnore(relativePaths);
for (const chunk of chunks) {
const result = yield* executeGit(
"GitCore.filterIgnoredPaths",
cwd,
["check-ignore", "--no-index", "-z", "--stdin"],
{
stdin: `${chunk.join("\0")}\0`,
allowNonZeroExit: true,
timeoutMs: 20_000,
maxOutputBytes: WORKSPACE_FILES_MAX_OUTPUT_BYTES,
truncateOutputAtMaxBytes: true,
},
);
if (result.code !== 0 && result.code !== 1) {
return yield* createGitCommandError(
"GitCore.filterIgnoredPaths",
cwd,
["check-ignore", "--no-index", "-z", "--stdin"],
result.stderr.trim().length > 0 ? result.stderr.trim() : "git check-ignore failed",
);
}
for (const ignoredPath of splitNullSeparatedPaths(result.stdout, result.stdoutTruncated)) {
ignoredPaths.add(ignoredPath);
}
}
if (ignoredPaths.size === 0) {
return relativePaths;
}
return relativePaths.filter((relativePath) => !ignoredPaths.has(relativePath));
});
const listBranches: GitCoreShape["listBranches"] = Effect.fn("listBranches")(function* (input) {
const branchRecencyPromise = readBranchRecency(input.cwd).pipe(
Effect.catch(() => Effect.succeed(new Map<string, number>())),
@@ -1686,7 +1460,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const localBranchResult = yield* executeGit(
"GitCore.listBranches.branchNoColor",
input.cwd,
["branch", "--no-color", "--no-column"],
["branch", "--no-color"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
@@ -1696,18 +1470,12 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
if (localBranchResult.code !== 0) {
const stderr = localBranchResult.stderr.trim();
if (stderr.toLowerCase().includes("not a git repository")) {
return {
branches: [],
isRepo: false,
hasOriginRemote: false,
nextCursor: null,
totalCount: 0,
};
return { branches: [], isRepo: false, hasOriginRemote: false };
}
return yield* createGitCommandError(
"GitCore.listBranches",
input.cwd,
["branch", "--no-color", "--no-column"],
["branch", "--no-color"],
stderr || "git branch failed",
);
}
@@ -1715,7 +1483,7 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
const remoteBranchResultEffect = executeGit(
"GitCore.listBranches.remoteBranches",
input.cwd,
["branch", "--no-color", "--no-column", "--remotes"],
["branch", "--no-color", "--remotes"],
{
timeoutMs: 10_000,
allowNonZeroExit: true,
@@ -1866,22 +1634,9 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
})
: [];
const branches = paginateBranches({
branches: filterBranchesForListQuery(
dedupeRemoteBranchesWithLocalMatches([...localBranches, ...remoteBranches]),
input.query,
),
cursor: input.cursor,
limit: input.limit,
});
const branches = [...localBranches, ...remoteBranches];
return {
branches: [...branches.branches],
isRepo: true,
hasOriginRemote: remoteNames.includes("origin"),
nextCursor: branches.nextCursor,
totalCount: branches.totalCount,
};
return { branches, isRepo: true, hasOriginRemote: remoteNames.includes("origin") };
});
const createWorktree: GitCoreShape["createWorktree"] = Effect.fn("createWorktree")(
@@ -2078,6 +1833,11 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
timeoutMs: 10_000,
fallbackErrorMessage: "git checkout failed",
});
// Refresh upstream refs in the background so checkout remains responsive.
yield* Effect.forkScoped(
refreshCheckedOutBranchUpstream(input.cwd).pipe(Effect.ignoreCause({ log: true })),
);
},
);
@@ -2091,7 +1851,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
runGitStdout("GitCore.listLocalBranchNames", cwd, [
"branch",
"--list",
"--no-column",
"--format=%(refname:short)",
]).pipe(
Effect.map((stdout) =>
@@ -2112,9 +1871,6 @@ export const makeGitCore = Effect.fn("makeGitCore")(function* (options?: {
pullCurrentBranch,
readRangeContext,
readConfigValue,
isInsideWorkTree,
listWorkspaceFiles,
filterIgnoredPaths,
listBranches,
createWorktree,
fetchPullRequestBranch,
+2 -2
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 "@t3tools/contracts";
import { GitHubCliError } from "../Errors.ts";
import {
GitHubCli,
type GitHubRepositoryCloneUrls,
@@ -187,7 +187,7 @@ const makeGitHubCli = Effect.sync(() => {
"--limit",
String(input.limit ?? 1),
"--json",
"number,title,url,baseRefName,headRefName,state,mergedAt,isCrossRepository,headRepository,headRepositoryOwner",
"number,title,url,baseRefName,headRefName",
],
}).pipe(
Effect.map((result) => result.stdout.trim()),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -7,7 +7,7 @@ import {
buildThreadTitlePrompt,
} from "./Prompts.ts";
import { normalizeCliError, sanitizeThreadTitle } from "./Utils.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGenerationError } from "./Errors.ts";
describe("buildCommitMessagePrompt", () => {
it("includes staged patch and summary in the prompt", () => {
+1 -29
View File
@@ -22,13 +22,12 @@ import type {
GitStatusResult,
} from "@t3tools/contracts";
import type { GitCommandError } from "@t3tools/contracts";
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly stdin?: string;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
@@ -41,8 +40,6 @@ export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
readonly stdoutTruncated: boolean;
readonly stderrTruncated: boolean;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
@@ -96,11 +93,6 @@ export interface GitRangeContext {
diffPatch: string;
}
export interface GitListWorkspaceFilesResult {
readonly paths: ReadonlyArray<string>;
readonly truncated: boolean;
}
export interface GitRenameBranchInput {
cwd: string;
oldBranch: string;
@@ -198,26 +190,6 @@ export interface GitCoreShape {
key: string,
) => Effect.Effect<string | null, GitCommandError>;
/**
* Determine whether the provided cwd is inside a git work tree.
*/
readonly isInsideWorkTree: (cwd: string) => Effect.Effect<boolean, GitCommandError>;
/**
* List tracked and untracked workspace file paths relative to cwd.
*/
readonly listWorkspaceFiles: (
cwd: string,
) => Effect.Effect<GitListWorkspaceFilesResult, GitCommandError>;
/**
* Remove gitignored paths from a relative path list.
*/
readonly filterIgnoredPaths: (
cwd: string,
relativePaths: ReadonlyArray<string>,
) => Effect.Effect<ReadonlyArray<string>, GitCommandError>;
/**
* List local + remote branches and branch metadata.
*/
+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 "@t3tools/contracts";
import type { GitHubCliError } from "../Errors.ts";
export interface GitHubPullRequestSummary {
readonly number: number;
+2 -2
View File
@@ -19,7 +19,7 @@ import {
} from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "@t3tools/contracts";
import type { GitManagerServiceError } from "../Errors.ts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
@@ -56,7 +56,7 @@ export interface GitManagerShape {
) => Effect.Effect<GitPreparePullRequestThreadResult, GitManagerServiceError>;
/**
* Run a Git action (`commit`, `push`, `create_pr`, `commit_push`, `commit_push_pr`).
* Run a stacked Git action (`commit`, `commit_push`, `commit_push_pr`).
* When `featureBranch` is set, creates and checks out a feature branch first.
*/
readonly runStackedAction: (
@@ -10,7 +10,7 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { TextGenerationError } from "@t3tools/contracts";
import type { TextGenerationError } from "../Errors.ts";
/** 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 "@t3tools/contracts";
import { TextGenerationError } from "./Errors.ts";
import { existsSync } from "node:fs";
import { join } from "node:path";
-67
View File
@@ -1,67 +0,0 @@
export function parseRemoteNamesInGitOrder(stdout: string): ReadonlyArray<string> {
return stdout
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
export function parseRemoteNames(stdout: string): ReadonlyArray<string> {
return parseRemoteNamesInGitOrder(stdout).toSorted((a, b) => b.length - a.length);
}
export function parseRemoteRefWithRemoteNames(
ref: string,
remoteNames: ReadonlyArray<string>,
): { remoteRef: string; remoteName: string; branchName: string } | null {
const trimmedRef = ref.trim();
if (trimmedRef.length === 0) {
return null;
}
for (const remoteName of remoteNames) {
const remotePrefix = `${remoteName}/`;
if (!trimmedRef.startsWith(remotePrefix)) {
continue;
}
const branchName = trimmedRef.slice(remotePrefix.length).trim();
if (branchName.length === 0) {
return null;
}
return {
remoteRef: trimmedRef,
remoteName,
branchName,
};
}
return null;
}
export function extractBranchNameFromRemoteRef(
ref: string,
options?: {
remoteName?: string | null;
remoteNames?: ReadonlyArray<string>;
},
): string {
const normalized = ref.trim();
if (normalized.length === 0) {
return "";
}
if (normalized.startsWith("refs/remotes/")) {
return extractBranchNameFromRemoteRef(normalized.slice("refs/remotes/".length), options);
}
const remoteNames = options?.remoteName ? [options.remoteName] : (options?.remoteNames ?? []);
const parsedRemoteRef = parseRemoteRefWithRemoteNames(normalized, remoteNames);
if (parsedRemoteRef) {
return parsedRemoteRef.branchName;
}
const firstSlash = normalized.indexOf("/");
if (firstSlash === -1) {
return normalized;
}
return normalized.slice(firstSlash + 1).trim();
}
-197
View File
@@ -1,197 +0,0 @@
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,
});
}),
);
+23
View File
@@ -0,0 +1,23 @@
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 = () => {
+13 -1
View File
@@ -9,7 +9,6 @@
import {
KeybindingRule,
KeybindingsConfig,
KeybindingsConfigError,
KeybindingShortcut,
KeybindingWhenNode,
MAX_KEYBINDINGS_COUNT,
@@ -47,6 +46,19 @@ 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
@@ -0,0 +1,103 @@
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
@@ -0,0 +1,413 @@
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 "vitest";
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
@@ -0,0 +1,456 @@
/**
* 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))),
);
@@ -1,46 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { compactTraceAttributes, normalizeModelMetricLabel } from "./Attributes.ts";
describe("Attributes", () => {
it("normalizes circular arrays, maps, and sets without recursing forever", () => {
const array: Array<unknown> = ["alpha"];
array.push(array);
const map = new Map<string, unknown>();
map.set("self", map);
const set = new Set<unknown>();
set.add(set);
assert.deepStrictEqual(
compactTraceAttributes({
array,
map,
set,
}),
{
array: ["alpha", "[Circular]"],
map: { self: "[Circular]" },
set: ["[Circular]"],
},
);
});
it("normalizes invalid dates without throwing", () => {
assert.deepStrictEqual(
compactTraceAttributes({
invalidDate: new Date("not-a-real-date"),
}),
{
invalidDate: "Invalid Date",
},
);
});
it("groups GPT-family models under a shared metric label", () => {
assert.strictEqual(normalizeModelMetricLabel("gpt-4o"), "gpt");
assert.strictEqual(normalizeModelMetricLabel("gpt-5.4"), "gpt");
assert.strictEqual(normalizeModelMetricLabel("claude-sonnet-4"), "claude");
});
});
-128
View File
@@ -1,128 +0,0 @@
import { Cause, Exit } from "effect";
export type MetricAttributeValue = string;
export type MetricAttributes = Readonly<Record<string, MetricAttributeValue>>;
export type TraceAttributes = Readonly<Record<string, unknown>>;
export type ObservabilityOutcome = "success" | "failure" | "interrupt";
function isPlainObject(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function markSeen(value: object, seen: WeakSet<object>): boolean {
if (seen.has(value)) {
return true;
}
seen.add(value);
return false;
}
function normalizeJsonValue(value: unknown, seen: WeakSet<object> = new WeakSet()): unknown {
if (
value === null ||
value === undefined ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
) {
return value ?? null;
}
if (typeof value === "bigint") {
return value.toString();
}
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? "Invalid Date" : value.toISOString();
}
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
...(value.stack ? { stack: value.stack } : {}),
};
}
if (Array.isArray(value)) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return value.map((entry) => normalizeJsonValue(entry, seen));
}
if (value instanceof Map) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return Object.fromEntries(
Array.from(value.entries(), ([key, entryValue]) => [
String(key),
normalizeJsonValue(entryValue, seen),
]),
);
}
if (value instanceof Set) {
if (markSeen(value, seen)) {
return "[Circular]";
}
return Array.from(value.values(), (entry) => normalizeJsonValue(entry, seen));
}
if (!isPlainObject(value)) {
return String(value);
}
if (markSeen(value, seen)) {
return "[Circular]";
}
return Object.fromEntries(
Object.entries(value).map(([key, entryValue]) => [key, normalizeJsonValue(entryValue, seen)]),
);
}
export function compactTraceAttributes(
attributes: Readonly<Record<string, unknown>>,
): TraceAttributes {
return Object.fromEntries(
Object.entries(attributes)
.filter(([, value]) => value !== undefined)
.map(([key, value]) => [key, normalizeJsonValue(value)]),
);
}
export function compactMetricAttributes(
attributes: Readonly<Record<string, unknown>>,
): MetricAttributes {
return Object.fromEntries(
Object.entries(attributes).flatMap(([key, value]) => {
if (value === undefined || value === null) {
return [];
}
if (typeof value === "string") {
return [[key, value]];
}
if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
return [[key, String(value)]];
}
return [];
}),
);
}
export function outcomeFromExit(exit: Exit.Exit<unknown, unknown>): ObservabilityOutcome {
if (Exit.isSuccess(exit)) {
return "success";
}
return Cause.hasInterruptsOnly(exit.cause) ? "interrupt" : "failure";
}
export function normalizeModelMetricLabel(model: string | null | undefined): string | undefined {
const normalized = model?.trim().toLowerCase();
if (!normalized) {
return undefined;
}
if (normalized.includes("gpt")) {
return "gpt";
}
if (normalized.includes("claude")) {
return "claude";
}
if (normalized.includes("gemini")) {
return "gemini";
}
return "other";
}
@@ -1,64 +0,0 @@
import { Effect, Layer, References, Tracer } from "effect";
import { OtlpMetrics, OtlpSerialization, OtlpTracer } from "effect/unstable/observability";
import { ServerConfig } from "../../config.ts";
import { ServerLoggerLive } from "../../serverLogger.ts";
import { makeLocalFileTracer } from "../LocalFileTracer.ts";
const otlpSerializationLayer = OtlpSerialization.layerJson;
export const ObservabilityLive = Layer.unwrap(
Effect.gen(function* () {
const config = yield* ServerConfig;
const traceReferencesLayer = Layer.mergeAll(
Layer.succeed(Tracer.MinimumTraceLevel, config.traceMinLevel),
Layer.succeed(References.TracerTimingEnabled, config.traceTimingEnabled),
);
const tracerLayer = Layer.effect(
Tracer.Tracer,
Effect.gen(function* () {
const delegate =
config.otlpTracesUrl === undefined
? undefined
: yield* OtlpTracer.make({
url: config.otlpTracesUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
resource: {
serviceName: config.otlpServiceName,
attributes: {
"service.runtime": "t3-server",
"service.mode": config.mode,
},
},
});
return yield* makeLocalFileTracer({
filePath: config.serverTracePath,
maxBytes: config.traceMaxBytes,
maxFiles: config.traceMaxFiles,
batchWindowMs: config.traceBatchWindowMs,
...(delegate ? { delegate } : {}),
});
}),
).pipe(Layer.provideMerge(otlpSerializationLayer));
const metricsLayer =
config.otlpMetricsUrl === undefined
? Layer.empty
: OtlpMetrics.layer({
url: config.otlpMetricsUrl,
exportInterval: `${config.otlpExportIntervalMs} millis`,
resource: {
serviceName: config.otlpServiceName,
attributes: {
"service.runtime": "t3-server",
"service.mode": config.mode,
},
},
}).pipe(Layer.provideMerge(otlpSerializationLayer));
return Layer.mergeAll(ServerLoggerLive, traceReferencesLayer, tracerLayer, metricsLayer);
}),
);
@@ -1,117 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { Effect, Layer, Logger, References, Tracer } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
import { makeLocalFileTracer } from "./LocalFileTracer.ts";
const makeTestLayer = (tracePath: string) =>
Layer.mergeAll(
Layer.effect(
Tracer.Tracer,
makeLocalFileTracer({
filePath: tracePath,
maxBytes: 1024 * 1024,
maxFiles: 2,
batchWindowMs: 10_000,
}),
),
Logger.layer([Logger.tracerLogger], { mergeWithExisting: false }),
Layer.succeed(References.MinimumLogLevel, "Info"),
);
const readTraceRecords = (tracePath: string): Array<TraceRecord> =>
fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map((line) => JSON.parse(line) as TraceRecord);
describe("LocalFileTracer", () => {
it.effect("writes nested spans to disk and captures log messages as span events", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
yield* Effect.scoped(
Effect.gen(function* () {
const program = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.parent": true,
});
yield* Effect.logInfo("parent event");
yield* Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"demo.child": true,
});
yield* Effect.logInfo("child event");
}).pipe(Effect.withSpan("child-span"));
}).pipe(Effect.withSpan("parent-span"));
yield* program.pipe(Effect.provide(makeTestLayer(tracePath)));
}),
);
const records = readTraceRecords(tracePath);
assert.equal(records.length, 2);
const parent = records.find((record) => record.name === "parent-span");
const child = records.find((record) => record.name === "child-span");
assert.notEqual(parent, undefined);
assert.notEqual(child, undefined);
if (!parent || !child) {
return;
}
assert.equal(child.parentSpanId, parent.spanId);
assert.equal(parent.attributes["demo.parent"], true);
assert.equal(child.attributes["demo.child"], true);
assert.equal(
parent.events.some((event) => event.name === "parent event"),
true,
);
assert.equal(
child.events.some((event) => event.name === "child event"),
true,
);
assert.equal(
child.events.some((event) => event.attributes["effect.logLevel"] === "INFO"),
true,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
it.effect("serializes interrupted spans with an interrupted exit status", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-local-tracer-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
yield* Effect.scoped(
Effect.exit(
Effect.interrupt.pipe(
Effect.withSpan("interrupt-span"),
Effect.provide(makeTestLayer(tracePath)),
),
),
);
const records = readTraceRecords(tracePath);
assert.equal(records.length, 1);
assert.equal(records[0]?.name, "interrupt-span");
assert.equal(records[0]?.exit._tag, "Interrupted");
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
);
});
@@ -1,104 +0,0 @@
import type * as Exit from "effect/Exit";
import { Effect, Option, Tracer } from "effect";
import { spanToTraceRecord } from "./TraceRecord.ts";
import { makeTraceSink } from "./TraceSink.ts";
export interface LocalFileTracerOptions {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly delegate?: Tracer.Tracer;
}
class LocalFileSpan implements Tracer.Span {
readonly _tag = "Span";
readonly name: string;
readonly spanId: string;
readonly traceId: string;
readonly parent: Option.Option<Tracer.AnySpan>;
readonly annotations: Tracer.Span["annotations"];
readonly links: Array<Tracer.SpanLink>;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
status: Tracer.SpanStatus;
attributes: Map<string, unknown>;
events: Array<[name: string, startTime: bigint, attributes: Record<string, unknown>]>;
constructor(
options: Parameters<Tracer.Tracer["span"]>[0],
private readonly delegate: Tracer.Span,
private readonly push: (record: ReturnType<typeof spanToTraceRecord>) => void,
) {
this.name = delegate.name;
this.spanId = delegate.spanId;
this.traceId = delegate.traceId;
this.parent = options.parent;
this.annotations = options.annotations;
this.links = [...options.links];
this.sampled = delegate.sampled;
this.kind = delegate.kind;
this.status = {
_tag: "Started",
startTime: options.startTime,
};
this.attributes = new Map();
this.events = [];
}
end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
this.status = {
_tag: "Ended",
startTime: this.status.startTime,
endTime,
exit,
};
this.delegate.end(endTime, exit);
if (this.sampled) {
this.push(spanToTraceRecord(this));
}
}
attribute(key: string, value: unknown): void {
this.attributes.set(key, value);
this.delegate.attribute(key, value);
}
event(name: string, startTime: bigint, attributes?: Record<string, unknown>): void {
const nextAttributes = attributes ?? {};
this.events.push([name, startTime, nextAttributes]);
this.delegate.event(name, startTime, nextAttributes);
}
addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
this.links.push(...links);
this.delegate.addLinks(links);
}
}
export const makeLocalFileTracer = Effect.fn("makeLocalFileTracer")(function* (
options: LocalFileTracerOptions,
) {
const sink = yield* makeTraceSink({
filePath: options.filePath,
maxBytes: options.maxBytes,
maxFiles: options.maxFiles,
batchWindowMs: options.batchWindowMs,
});
const delegate =
options.delegate ??
Tracer.make({
span: (spanOptions) => new Tracer.NativeSpan(spanOptions),
});
return Tracer.make({
span(spanOptions) {
return new LocalFileSpan(spanOptions, delegate.span(spanOptions), sink.push);
},
...(delegate.context ? { context: delegate.context } : {}),
});
});
@@ -1,111 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Metric } from "effect";
import { withMetrics } from "./Metrics.ts";
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("withMetrics", () => {
it.effect("supports pipe-style usage", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_pipe_total");
const timer = Metric.timer("with_metrics_pipe_duration");
const result = yield* Effect.succeed("ok").pipe(
withMetrics({
counter,
timer,
attributes: {
operation: "pipe",
},
}),
);
assert.equal(result, "ok");
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_pipe_total", {
operation: "pipe",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_pipe_duration", {
operation: "pipe",
}),
true,
);
}),
);
it.effect("supports direct invocation", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_direct_total");
yield* withMetrics(Effect.fail("boom"), {
counter,
attributes: {
operation: "direct",
},
}).pipe(Effect.exit);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_direct_total", {
operation: "direct",
outcome: "failure",
}),
true,
);
}),
);
it.effect("evaluates attributes lazily after the wrapped effect runs", () =>
Effect.gen(function* () {
const counter = Metric.counter("with_metrics_lazy_total");
const timer = Metric.timer("with_metrics_lazy_duration");
let provider = "unknown";
yield* Effect.sync(() => {
provider = "codex";
}).pipe(
withMetrics({
counter,
timer,
attributes: () => ({
provider,
operation: "lazy",
}),
}),
);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_total", {
provider: "codex",
operation: "lazy",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "with_metrics_lazy_duration", {
provider: "codex",
operation: "lazy",
}),
true,
);
}),
);
});
-160
View File
@@ -1,160 +0,0 @@
import { Duration, Effect, Exit, Metric } from "effect";
import { dual } from "effect/Function";
import {
compactMetricAttributes,
normalizeModelMetricLabel,
outcomeFromExit,
} from "./Attributes.ts";
export const rpcRequestsTotal = Metric.counter("t3_rpc_requests_total", {
description: "Total RPC requests handled by the websocket RPC server.",
});
export const rpcRequestDuration = Metric.timer("t3_rpc_request_duration", {
description: "RPC request handling duration.",
});
export const orchestrationCommandsTotal = Metric.counter("t3_orchestration_commands_total", {
description: "Total orchestration commands dispatched.",
});
export const orchestrationCommandDuration = Metric.timer("t3_orchestration_command_duration", {
description: "Orchestration command dispatch duration.",
});
export const orchestrationCommandAckDuration = Metric.timer(
"t3_orchestration_command_ack_duration",
{
description:
"Time from orchestration command dispatch to the first committed domain event emitted for that command.",
},
);
export const orchestrationEventsProcessedTotal = Metric.counter(
"t3_orchestration_events_processed_total",
{
description: "Total orchestration intent events processed by runtime reactors.",
},
);
export const providerSessionsTotal = Metric.counter("t3_provider_sessions_total", {
description: "Total provider session lifecycle operations.",
});
export const providerTurnsTotal = Metric.counter("t3_provider_turns_total", {
description: "Total provider turn lifecycle operations.",
});
export const providerTurnDuration = Metric.timer("t3_provider_turn_duration", {
description: "Provider turn request duration.",
});
export const providerRuntimeEventsTotal = Metric.counter("t3_provider_runtime_events_total", {
description: "Total canonical provider runtime events processed.",
});
export const gitCommandsTotal = Metric.counter("t3_git_commands_total", {
description: "Total git commands executed by the server runtime.",
});
export const gitCommandDuration = Metric.timer("t3_git_command_duration", {
description: "Git command execution duration.",
});
export const terminalSessionsTotal = Metric.counter("t3_terminal_sessions_total", {
description: "Total terminal sessions started.",
});
export const terminalRestartsTotal = Metric.counter("t3_terminal_restarts_total", {
description: "Total terminal restart requests handled.",
});
export const metricAttributes = (
attributes: Readonly<Record<string, unknown>>,
): ReadonlyArray<[string, string]> => Object.entries(compactMetricAttributes(attributes));
export const increment = (
metric: Metric.Metric<number, unknown>,
attributes: Readonly<Record<string, unknown>>,
amount = 1,
) => Metric.update(Metric.withAttributes(metric, metricAttributes(attributes)), amount);
export interface WithMetricsOptions {
readonly counter?: Metric.Metric<number, unknown>;
readonly timer?: Metric.Metric<Duration.Duration, unknown>;
readonly attributes?:
| Readonly<Record<string, unknown>>
| (() => Readonly<Record<string, unknown>>);
readonly outcomeAttributes?: (
outcome: ReturnType<typeof outcomeFromExit>,
) => Readonly<Record<string, unknown>>;
}
const withMetricsImpl = <A, E, R>(
effect: Effect.Effect<A, E, R>,
options: WithMetricsOptions,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
const startedAt = Date.now();
const exit = yield* Effect.exit(effect);
const duration = Duration.millis(Math.max(0, Date.now() - startedAt));
const baseAttributes =
typeof options.attributes === "function" ? options.attributes() : (options.attributes ?? {});
if (options.timer) {
yield* Metric.update(
Metric.withAttributes(options.timer, metricAttributes(baseAttributes)),
duration,
);
}
if (options.counter) {
const outcome = outcomeFromExit(exit);
yield* Metric.update(
Metric.withAttributes(
options.counter,
metricAttributes({
...baseAttributes,
outcome,
...(options.outcomeAttributes ? options.outcomeAttributes(outcome) : {}),
}),
),
1,
);
}
if (Exit.isSuccess(exit)) {
return exit.value;
}
return yield* Effect.failCause(exit.cause);
});
export const withMetrics: {
<A, E, R>(
options: WithMetricsOptions,
): (effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
<A, E, R>(effect: Effect.Effect<A, E, R>, options: WithMetricsOptions): Effect.Effect<A, E, R>;
} = dual(2, withMetricsImpl);
export const providerMetricAttributes = (
provider: string,
extra?: Readonly<Record<string, unknown>>,
) =>
compactMetricAttributes({
provider,
...extra,
});
export const providerTurnMetricAttributes = (input: {
readonly provider: string;
readonly model: string | null | undefined;
readonly extra?: Readonly<Record<string, unknown>>;
}) => {
const modelFamily = normalizeModelMetricLabel(input.model);
return compactMetricAttributes({
provider: input.provider,
...(modelFamily ? { modelFamily } : {}),
...input.extra,
});
};
@@ -1,161 +0,0 @@
import { assert, describe, it } from "@effect/vitest";
import { Effect, Exit, Metric, Stream } from "effect";
import {
observeRpcEffect,
observeRpcStream,
observeRpcStreamEffect,
} from "./RpcInstrumentation.ts";
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("RpcInstrumentation", () => {
it.effect("records success metrics for unary RPC handlers", () =>
Effect.gen(function* () {
yield* observeRpcEffect("rpc.instrumentation.success", Effect.succeed("ok"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.success.span"));
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.success",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.success",
}),
true,
);
}),
);
it.effect("records failure outcomes for unary RPC handlers", () =>
Effect.gen(function* () {
yield* Effect.exit(
observeRpcEffect("rpc.instrumentation.failure", Effect.fail("boom"), {
"rpc.aggregate": "test",
}).pipe(Effect.withSpan("rpc.instrumentation.failure.span")),
);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.failure",
}),
true,
);
}),
);
it.effect("records subscription activation metrics for stream RPC handlers", () =>
Effect.gen(function* () {
const events = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream",
Effect.succeed(Stream.make("a", "b")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.span")),
);
assert.deepStrictEqual(Array.from(events), ["a", "b"]);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream",
outcome: "success",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream",
}),
true,
);
}),
);
it.effect("records failure outcomes for direct stream RPC handlers during consumption", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStream(
"rpc.instrumentation.stream.failure",
Stream.make("a").pipe(Stream.concat(Stream.fail("boom"))),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.failure",
}),
true,
);
}),
);
it.effect("records failure outcomes when a stream RPC effect produces a failing stream", () =>
Effect.gen(function* () {
const exit = yield* Stream.runCollect(
observeRpcStreamEffect(
"rpc.instrumentation.stream.effect.failure",
Effect.succeed(Stream.fail("boom")),
{ "rpc.aggregate": "test" },
).pipe(Stream.withSpan("rpc.instrumentation.stream.effect.failure.span")),
).pipe(Effect.exit);
assert.equal(Exit.isFailure(exit), true);
const snapshots = yield* Metric.snapshot;
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_requests_total", {
method: "rpc.instrumentation.stream.effect.failure",
outcome: "failure",
}),
true,
);
assert.equal(
hasMetricSnapshot(snapshots, "t3_rpc_request_duration", {
method: "rpc.instrumentation.stream.effect.failure",
}),
true,
);
}),
);
});
@@ -1,89 +0,0 @@
import { Duration, Effect, Exit, Metric, Stream } from "effect";
import { outcomeFromExit } from "./Attributes.ts";
import { metricAttributes, rpcRequestDuration, rpcRequestsTotal, withMetrics } from "./Metrics.ts";
const annotateRpcSpan = (
method: string,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<void, never, never> =>
Effect.annotateCurrentSpan({
"rpc.method": method,
...traceAttributes,
});
const recordRpcStreamMetrics = <E>(
method: string,
startedAt: number,
exit: Exit.Exit<unknown, E>,
): Effect.Effect<void, never, never> =>
Effect.gen(function* () {
yield* Metric.update(
Metric.withAttributes(rpcRequestDuration, metricAttributes({ method })),
Duration.millis(Math.max(0, Date.now() - startedAt)),
);
yield* Metric.update(
Metric.withAttributes(
rpcRequestsTotal,
metricAttributes({
method,
outcome: outcomeFromExit(exit),
}),
),
1,
);
});
export const observeRpcEffect = <A, E, R>(
method: string,
effect: Effect.Effect<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Effect.Effect<A, E, R> =>
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
return yield* effect.pipe(
withMetrics({
counter: rpcRequestsTotal,
timer: rpcRequestDuration,
attributes: {
method,
},
}),
);
});
export const observeRpcStream = <A, E, R>(
method: string,
stream: Stream.Stream<A, E, R>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, E, R> =>
Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
return stream.pipe(Stream.onExit((exit) => recordRpcStreamMetrics(method, startedAt, exit)));
}),
);
export const observeRpcStreamEffect = <A, StreamError, StreamContext, EffectError, EffectContext>(
method: string,
effect: Effect.Effect<Stream.Stream<A, StreamError, StreamContext>, EffectError, EffectContext>,
traceAttributes?: Readonly<Record<string, unknown>>,
): Stream.Stream<A, StreamError | EffectError, StreamContext | EffectContext> =>
Stream.unwrap(
Effect.gen(function* () {
yield* annotateRpcSpan(method, traceAttributes);
const startedAt = Date.now();
const exit = yield* Effect.exit(effect);
if (Exit.isFailure(exit)) {
yield* recordRpcStreamMetrics(method, startedAt, exit);
return yield* Effect.failCause(exit.cause);
}
return exit.value.pipe(
Stream.onExit((streamExit) => recordRpcStreamMetrics(method, startedAt, streamExit)),
);
}),
);
@@ -1,100 +0,0 @@
import { Cause, Exit, Option, Tracer } from "effect";
import { compactTraceAttributes } from "./Attributes.ts";
export interface TraceRecord {
readonly type: "effect-span";
readonly name: string;
readonly traceId: string;
readonly spanId: string;
readonly parentSpanId?: string;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
readonly startTimeUnixNano: string;
readonly endTimeUnixNano: string;
readonly durationMs: number;
readonly attributes: Readonly<Record<string, unknown>>;
readonly events: ReadonlyArray<{
readonly name: string;
readonly timeUnixNano: string;
readonly attributes: Readonly<Record<string, unknown>>;
}>;
readonly links: ReadonlyArray<{
readonly traceId: string;
readonly spanId: string;
readonly attributes: Readonly<Record<string, unknown>>;
}>;
readonly exit:
| {
readonly _tag: "Success";
}
| {
readonly _tag: "Interrupted";
readonly cause: string;
}
| {
readonly _tag: "Failure";
readonly cause: string;
};
}
interface SerializableSpan {
readonly name: string;
readonly traceId: string;
readonly spanId: string;
readonly parent: Option.Option<Tracer.AnySpan>;
readonly status: Tracer.SpanStatus;
readonly sampled: boolean;
readonly kind: Tracer.SpanKind;
readonly attributes: ReadonlyMap<string, unknown>;
readonly links: ReadonlyArray<Tracer.SpanLink>;
readonly events: ReadonlyArray<
readonly [name: string, startTime: bigint, attributes: Record<string, unknown>]
>;
}
function formatTraceExit(exit: Exit.Exit<unknown, unknown>): TraceRecord["exit"] {
if (Exit.isSuccess(exit)) {
return { _tag: "Success" };
}
if (Cause.hasInterruptsOnly(exit.cause)) {
return {
_tag: "Interrupted",
cause: Cause.pretty(exit.cause),
};
}
return {
_tag: "Failure",
cause: Cause.pretty(exit.cause),
};
}
export function spanToTraceRecord(span: SerializableSpan): TraceRecord {
const status = span.status as Extract<Tracer.SpanStatus, { _tag: "Ended" }>;
const parentSpanId = Option.getOrUndefined(span.parent)?.spanId;
return {
type: "effect-span",
name: span.name,
traceId: span.traceId,
spanId: span.spanId,
...(parentSpanId ? { parentSpanId } : {}),
sampled: span.sampled,
kind: span.kind,
startTimeUnixNano: String(status.startTime),
endTimeUnixNano: String(status.endTime),
durationMs: Number(status.endTime - status.startTime) / 1_000_000,
attributes: compactTraceAttributes(Object.fromEntries(span.attributes)),
events: span.events.map(([name, startTime, attributes]) => ({
name,
timeUnixNano: String(startTime),
attributes: compactTraceAttributes(attributes),
})),
links: span.links.map((link) => ({
traceId: link.span.traceId,
spanId: link.span.spanId,
attributes: compactTraceAttributes(link.attributes),
})),
exit: formatTraceExit(status.exit),
};
}
@@ -1,152 +0,0 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { assert, describe, it } from "@effect/vitest";
import { Effect } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
import { makeTraceSink } from "./TraceSink.ts";
const makeRecord = (name: string, suffix = ""): TraceRecord => ({
type: "effect-span",
name,
traceId: `trace-${name}-${suffix}`,
spanId: `span-${name}-${suffix}`,
sampled: true,
kind: "internal",
startTimeUnixNano: "1",
endTimeUnixNano: "2",
durationMs: 1,
attributes: {
payload: suffix,
},
events: [],
links: [],
exit: {
_tag: "Success",
},
});
describe("TraceSink", () => {
it.effect("flushes buffered records on close", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
sink.push(makeRecord("alpha"));
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as TraceRecord);
assert.equal(lines.length, 2);
assert.equal(lines[0]?.name, "alpha");
assert.equal(lines[1]?.name, "beta");
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
it.effect("rotates the trace file when the configured max size is exceeded", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 180,
maxFiles: 2,
batchWindowMs: 10_000,
});
for (let index = 0; index < 8; index += 1) {
sink.push(makeRecord("rotate", `${index}-${"x".repeat(48)}`));
yield* sink.flush;
}
yield* sink.close();
const matchingFiles = fs
.readdirSync(tempDir)
.filter(
(entry) =>
entry === "server.trace.ndjson" || entry.startsWith("server.trace.ndjson."),
)
.toSorted();
assert.equal(
matchingFiles.some((entry) => entry === "server.trace.ndjson.1"),
true,
);
assert.equal(
matchingFiles.some((entry) => entry === "server.trace.ndjson.3"),
false,
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
it.effect("drops only the invalid record when serialization fails", () =>
Effect.scoped(
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-trace-sink-"));
const tracePath = path.join(tempDir, "server.trace.ndjson");
try {
const sink = yield* makeTraceSink({
filePath: tracePath,
maxBytes: 1024,
maxFiles: 2,
batchWindowMs: 10_000,
});
const circular: Array<unknown> = [];
circular.push(circular);
sink.push(makeRecord("alpha"));
sink.push({
...makeRecord("invalid"),
attributes: {
circular,
},
} as TraceRecord);
sink.push(makeRecord("beta"));
yield* sink.close();
const lines = fs
.readFileSync(tracePath, "utf8")
.trim()
.split("\n")
.map((line) => JSON.parse(line) as TraceRecord);
assert.deepStrictEqual(
lines.map((line) => line.name),
["alpha", "beta"],
);
} finally {
fs.rmSync(tempDir, { recursive: true, force: true });
}
}),
),
);
});
@@ -1,68 +0,0 @@
import { RotatingFileSink } from "@t3tools/shared/logging";
import { Effect } from "effect";
import type { TraceRecord } from "./TraceRecord.ts";
const FLUSH_BUFFER_THRESHOLD = 32;
export interface TraceSinkOptions {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
}
export interface TraceSink {
readonly filePath: string;
push: (record: TraceRecord) => void;
flush: Effect.Effect<void>;
close: () => Effect.Effect<void>;
}
export const makeTraceSink = Effect.fn("makeTraceSink")(function* (options: TraceSinkOptions) {
const sink = new RotatingFileSink({
filePath: options.filePath,
maxBytes: options.maxBytes,
maxFiles: options.maxFiles,
});
let buffer: Array<string> = [];
const flushUnsafe = () => {
if (buffer.length === 0) {
return;
}
const chunk = buffer.join("");
buffer = [];
try {
sink.write(chunk);
} catch {
buffer.unshift(chunk);
}
};
const flush = Effect.sync(flushUnsafe).pipe(Effect.withTracerEnabled(false));
yield* Effect.addFinalizer(() => flush.pipe(Effect.ignore));
yield* Effect.forkScoped(
Effect.sleep(`${options.batchWindowMs} millis`).pipe(Effect.andThen(flush), Effect.forever),
);
return {
filePath: options.filePath,
push(record) {
try {
buffer.push(`${JSON.stringify(record)}\n`);
if (buffer.length >= FLUSH_BUFFER_THRESHOLD) {
flushUnsafe();
}
} catch {
return;
}
},
flush,
close: () => flush,
} satisfies TraceSink;
});
+2 -57
View File
@@ -31,15 +31,6 @@ 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",
@@ -75,19 +66,10 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "zed",
args: ["/tmp/workspace"],
});
const ideaLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLaunch, {
command: "idea",
args: ["/tmp/workspace"],
});
}),
);
it.effect("applies launch-style-specific navigation arguments", () =>
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
@@ -107,15 +89,6 @@ 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",
@@ -151,33 +124,6 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
const zedLineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineOnly, {
command: "zed",
args: ["/tmp/workspace/AGENTS.md:48"],
});
const ideaLineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineOnly, {
command: "idea",
args: ["--line", "48", "/tmp/workspace/AGENTS.md"],
});
const ideaLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "idea" },
"darwin",
);
assert.deepEqual(ideaLineAndColumn, {
command: "idea",
args: ["--line", "71", "--column", "5", "/tmp/workspace/src/open.ts"],
});
}),
);
@@ -310,7 +256,6 @@ 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");
@@ -318,7 +263,7 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["trae", "vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
+13 -51
View File
@@ -10,14 +10,17 @@ import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, OpenError, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Effect, Layer } from "effect";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { ServiceMap, Schema, Effect, Layer } from "effect";
// ==============================
// Definitions
// ==============================
export { OpenError };
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
}) {}
export interface OpenInEditorInput {
readonly cwd: string;
@@ -34,45 +37,10 @@ interface CommandAvailabilityOptions {
readonly env?: NodeJS.ProcessEnv;
}
const TARGET_WITH_POSITION_PATTERN = /^(.*?):(\d+)(?::(\d+))?$/;
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
function parseTargetPathAndPosition(target: string): {
path: string;
line: string | undefined;
column: string | undefined;
} | null {
const match = TARGET_WITH_POSITION_PATTERN.exec(target);
if (!match?.[1] || !match[2]) {
return null;
}
return {
path: match[1],
line: match[2],
column: match[3],
};
}
function resolveCommandEditorArgs(
editor: (typeof EDITORS)[number],
target: string,
): ReadonlyArray<string> {
const parsedTarget = parseTargetPathAndPosition(target);
switch (editor.launchStyle) {
case "direct-path":
return [target];
case "goto":
return parsedTarget ? ["--goto", target] : [target];
case "line-column": {
if (!parsedTarget) {
return [target];
}
const { path, line, column } = parsedTarget;
return [...(line ? ["--line", line] : []), ...(column ? ["--column", column] : []), path];
}
}
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
@@ -233,25 +201,19 @@ export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fn("resolveEditorLaunch")(function* (
export const resolveEditorLaunch = Effect.fnUntraced(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): Effect.fn.Return<EditorLaunch, OpenError> {
yield* Effect.annotateCurrentSpan({
"open.editor": input.editor,
"open.cwd": input.cwd,
"open.platform": platform,
});
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.command) {
return {
command: editorDef.command,
args: resolveCommandEditorArgs(editorDef, input.cwd),
};
return shouldUseGotoFlag(editorDef, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
}
if (editorDef.id !== "file-manager") {
@@ -23,7 +23,6 @@ import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -39,8 +38,6 @@ import {
} from "../../provider/Services/ProviderService.ts";
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);
@@ -117,7 +114,7 @@ async function waitForThread(
checkpoints: ReadonlyArray<{ checkpointTurnCount: number }>;
activities: ReadonlyArray<{ kind: string }>;
}) => boolean,
timeoutMs = 15_000,
timeoutMs = 5000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<{
@@ -142,7 +139,7 @@ async function waitForThread(
async function waitForEvent(
engine: OrchestrationEngineShape,
predicate: (event: { type: string }) => boolean,
timeoutMs = 15_000,
timeoutMs = 5000,
) {
const deadline = Date.now() + timeoutMs;
const poll = async () => {
@@ -193,7 +190,7 @@ function gitShowFileAtRef(cwd: string, ref: string, filePath: string): string {
return runGit(cwd, ["show", `${ref}:${filePath}`]);
}
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 15_000) {
async function waitForGitRefExists(cwd: string, ref: string, timeoutMs = 5000) {
const deadline = Date.now() + timeoutMs;
const poll = async (): Promise<void> => {
if (gitRefExists(cwd, ref)) {
@@ -250,7 +247,6 @@ describe("CheckpointReactor", () => {
options?.providerName ?? "codex",
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -265,10 +261,7 @@ describe("CheckpointReactor", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(WorkspaceEntriesLive.pipe(Layer.provide(WorkspacePathsLive))),
Layer.provideMerge(WorkspacePathsLive),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(NodeServices.layer),
);
@@ -1011,7 +1004,18 @@ describe("CheckpointReactor", () => {
}),
);
await harness.drain();
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();
expect(harness.provider.rollbackConversation).toHaveBeenCalledTimes(2);
expect(harness.provider.rollbackConversation.mock.calls[0]?.[0]).toEqual({
@@ -16,6 +16,7 @@ import {
checkpointRefForThreadTurn,
resolveThreadWorkspaceCwd,
} from "../../checkpointing/Utils.ts";
import { clearWorkspaceIndexCache } from "../../workspaceEntries.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { CheckpointReactor, type CheckpointReactorShape } from "../Services/CheckpointReactor.ts";
@@ -24,7 +25,10 @@ import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { WorkspaceEntries } from "../../workspace/Services/WorkspaceEntries.ts";
import {
inspectWorkspacePathState,
resolveWorkspaceUnavailableReason,
} from "../../workspacePaths.ts";
type ReactorInput =
| {
@@ -68,7 +72,6 @@ const make = Effect.gen(function* () {
const providerService = yield* ProviderService;
const checkpointStore = yield* CheckpointStore;
const receiptBus = yield* RuntimeReceiptBus;
const workspaceEntries = yield* WorkspaceEntries;
const appendRevertFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -119,7 +122,7 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveSessionRuntimeForThread = Effect.fn("resolveSessionRuntimeForThread")(function* (
const resolveSessionRuntimeForThread = Effect.fnUntraced(function* (
threadId: ThreadId,
): Effect.fn.Return<Option.Option<{ readonly threadId: ThreadId; readonly cwd: string }>> {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -153,9 +156,14 @@ const make = Effect.gen(function* () {
// active provider session CWD and falling back to the thread/project config.
// Returns undefined when no CWD can be determined or the workspace is not
// a git repository.
const resolveCheckpointCwd = Effect.fn("resolveCheckpointCwd")(function* (input: {
const resolveCheckpointCwd = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly thread: { readonly projectId: ProjectId; readonly worktreePath: string | null };
readonly thread: {
readonly projectId: ProjectId;
readonly worktreePath: string | null;
readonly effectiveCwd: string | null;
readonly effectiveCwdState: string;
};
readonly projects: ReadonlyArray<{ readonly id: ProjectId; readonly workspaceRoot: string }>;
readonly preferSessionRuntime: boolean;
}): Effect.fn.Return<string | undefined> {
@@ -176,7 +184,7 @@ const make = Effect.gen(function* () {
onSome: (runtime) => runtime.cwd,
}));
if (!cwd) {
if (input.thread.effectiveCwdState !== "available" || !cwd) {
return undefined;
}
if (!isGitWorkspace(cwd)) {
@@ -188,7 +196,7 @@ const make = Effect.gen(function* () {
// Shared tail for both capture paths: creates the git checkpoint ref, diffs
// it against the previous turn, then dispatches the domain events to update
// the orchestration read model.
const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
const captureAndDispatchCheckpoint = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId;
readonly thread: {
@@ -227,7 +235,7 @@ const make = Effect.gen(function* () {
// Invalidate the workspace entry cache so the @-mention file picker
// reflects files created or deleted during this turn.
yield* workspaceEntries.invalidate(input.cwd);
clearWorkspaceIndexCache(input.cwd);
const files = yield* checkpointStore
.diffCheckpoints({
@@ -321,70 +329,70 @@ const make = Effect.gen(function* () {
});
// Captures a real git checkpoint when a turn completes via a runtime event.
const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const captureCheckpointFromTurnCompletion = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>,
) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
// When a primary turn is active, only that turn may produce completion checkpoints.
if (thread.session?.activeTurnId && !sameId(thread.session.activeTurnId, turnId)) {
return;
}
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
return;
}
// Only skip if a real (non-placeholder) checkpoint already exists for this turn.
// ProviderRuntimeIngestion may insert placeholder entries with status "missing"
// before this reactor runs; those must not prevent real git capture.
if (
thread.checkpoints.some(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
)
) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: true,
});
if (!checkpointCwd) {
return;
}
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
// If a placeholder checkpoint exists for this turn, reuse its turn count
// instead of incrementing past it.
const existingPlaceholder = thread.checkpoints.find(
(checkpoint) => checkpoint.turnId === turnId && checkpoint.status === "missing",
);
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const nextTurnCount = existingPlaceholder
? existingPlaceholder.checkpointTurnCount
: currentTurnCount + 1;
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
},
);
yield* captureAndDispatchCheckpoint({
threadId: thread.id,
turnId,
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
status: checkpointStatusFromRuntime(event.payload.state),
assistantMessageId: undefined,
createdAt: event.createdAt,
});
});
// Captures a real git checkpoint when a placeholder checkpoint (status "missing")
// is detected via a domain event. This replaces the placeholder with a real
@@ -394,7 +402,7 @@ const make = Effect.gen(function* () {
// events from the Codex runtime. This handler fires when the corresponding
// domain event arrives, allowing the reactor to capture the actual filesystem
// state into a git ref and dispatch a replacement checkpoint.
const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
const captureCheckpointFromPlaceholder = Effect.fnUntraced(function* (
event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
) {
const { threadId, turnId, checkpointTurnCount, status } = event.payload;
@@ -448,59 +456,57 @@ const make = Effect.gen(function* () {
});
});
const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const ensurePreTurnBaselineFromTurnStart = Effect.fnUntraced(function* (
event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>,
) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === event.threadId);
if (!thread) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
return;
}
const checkpointCwd = yield* resolveCheckpointCwd({
threadId: thread.id,
thread,
projects: readModel.projects,
preferSessionRuntime: false,
});
if (!checkpointCwd) {
return;
}
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
const baselineExists = yield* checkpointStore.hasCheckpointRef({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
if (baselineExists) {
return;
}
const currentTurnCount = thread.checkpoints.reduce(
(maxTurnCount, checkpoint) => Math.max(maxTurnCount, checkpoint.checkpointTurnCount),
0,
);
const baselineCheckpointRef = checkpointRefForThreadTurn(thread.id, currentTurnCount);
const baselineExists = yield* checkpointStore.hasCheckpointRef({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
if (baselineExists) {
return;
}
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId: thread.id,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.createdAt,
});
},
);
yield* checkpointStore.captureCheckpoint({
cwd: checkpointCwd,
checkpointRef: baselineCheckpointRef,
});
yield* receiptBus.publish({
type: "checkpoint.baseline.captured",
threadId: thread.id,
checkpointTurnCount: currentTurnCount,
checkpointRef: baselineCheckpointRef,
createdAt: event.createdAt,
});
});
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fn(
"ensurePreTurnBaselineFromDomainTurnStart",
)(function* (
const ensurePreTurnBaselineFromDomainTurnStart = Effect.fnUntraced(function* (
event: Extract<
OrchestrationEvent,
{ type: "thread.turn-start-requested" | "thread.message-sent" }
@@ -559,7 +565,7 @@ const make = Effect.gen(function* () {
});
});
const handleRevertRequested = Effect.fn("handleRevertRequested")(function* (
const handleRevertRequested = Effect.fnUntraced(function* (
event: Extract<OrchestrationEvent, { type: "thread.checkpoint-revert-requested" }>,
) {
const now = new Date().toISOString();
@@ -586,6 +592,20 @@ const make = Effect.gen(function* () {
}).pipe(Effect.catch(() => Effect.void));
return;
}
const sessionWorkspaceState = yield* Effect.promise(() =>
inspectWorkspacePathState(sessionRuntime.value.cwd),
);
if (sessionWorkspaceState !== "available") {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
turnCount: event.payload.turnCount,
detail:
resolveWorkspaceUnavailableReason(sessionWorkspaceState) ??
"Workspace folder is unavailable.",
createdAt: now,
}).pipe(Effect.catch(() => Effect.void));
return;
}
if (!isGitWorkspace(sessionRuntime.value.cwd)) {
yield* appendRevertFailureActivity({
threadId: event.payload.threadId,
@@ -645,7 +665,7 @@ const make = Effect.gen(function* () {
// Invalidate the workspace entry cache so the @-mention file picker
// reflects the reverted filesystem state.
yield* workspaceEntries.invalidate(sessionRuntime.value.cwd);
clearWorkspaceIndexCache(sessionRuntime.value.cwd);
const rolledBackTurns = Math.max(0, currentTurnCount - event.payload.turnCount);
if (rolledBackTurns > 0) {
@@ -687,7 +707,7 @@ const make = Effect.gen(function* () {
);
});
const processDomainEvent = Effect.fn("processDomainEvent")(function* (event: OrchestrationEvent) {
const processDomainEvent = Effect.fnUntraced(function* (event: OrchestrationEvent) {
if (event.type === "thread.turn-start-requested" || event.type === "thread.message-sent") {
yield* ensurePreTurnBaselineFromDomainTurnStart(event);
return;
@@ -726,9 +746,7 @@ const make = Effect.gen(function* () {
}
});
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
) {
const processRuntimeEvent = Effect.fnUntraced(function* (event: ProviderRuntimeEvent) {
if (event.type === "turn.started") {
yield* ensurePreTurnBaselineFromTurnStart(event);
return;
@@ -8,7 +8,7 @@ import {
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { Effect, Layer, ManagedRuntime, Metric, Option, Queue, Stream } from "effect";
import { Effect, Layer, ManagedRuntime, Queue, Stream } from "effect";
import { describe, expect, it } from "vitest";
import { PersistenceSqlError } from "../../persistence/Errors.ts";
@@ -21,13 +21,11 @@ import {
} from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
type OrchestrationProjectionPipelineShape,
} from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { ServerConfig } from "../../config.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -41,7 +39,6 @@ async function createOrchestrationSystem() {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -62,117 +59,7 @@ function now() {
return new Date().toISOString();
}
const hasMetricSnapshot = (
snapshots: ReadonlyArray<Metric.Metric.Snapshot>,
id: string,
attributes: Readonly<Record<string, string>>,
) =>
snapshots.some(
(snapshot) =>
snapshot.id === id &&
Object.entries(attributes).every(([key, value]) => snapshot.attributes?.[key] === value),
);
describe("OrchestrationEngine", () => {
it("bootstraps the in-memory read model from persisted projections", async () => {
const failOnHistoricalReplayStore: OrchestrationEventStoreShape = {
append: () =>
Effect.fail(
new PersistenceSqlError({
operation: "test.append",
detail: "append should not be called during bootstrap",
}),
),
readFromSequence: () => Stream.empty,
readAll: () =>
Stream.fail(
new PersistenceSqlError({
operation: "test.readAll",
detail: "historical replay should not be used during bootstrap",
}),
),
};
const projectionSnapshot = {
snapshotSequence: 7,
updatedAt: "2026-03-03T00:00:04.000Z",
projects: [
{
id: asProjectId("project-bootstrap"),
title: "Bootstrap Project",
workspaceRoot: "/tmp/project-bootstrap",
defaultModelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
scripts: [],
createdAt: "2026-03-03T00:00:00.000Z",
updatedAt: "2026-03-03T00:00:01.000Z",
deletedAt: null,
},
],
threads: [
{
id: ThreadId.makeUnsafe("thread-bootstrap"),
projectId: asProjectId("project-bootstrap"),
title: "Bootstrap Thread",
modelSelection: {
provider: "codex" as const,
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access" as const,
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-03-03T00:00:02.000Z",
updatedAt: "2026-03-03T00:00:03.000Z",
archivedAt: null,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
checkpoints: [],
session: null,
},
],
};
const layer = OrchestrationEngineLive.pipe(
Layer.provide(
Layer.succeed(ProjectionSnapshotQuery, {
getSnapshot: () => Effect.succeed(projectionSnapshot),
getCounts: () => Effect.succeed({ projectCount: 1, threadCount: 1 }),
getActiveProjectByWorkspaceRoot: () => Effect.succeed(Option.none()),
getFirstActiveThreadIdByProjectId: () => Effect.succeed(Option.none()),
getThreadCheckpointContext: () => Effect.succeed(Option.none()),
}),
),
Layer.provide(
Layer.succeed(OrchestrationProjectionPipeline, {
bootstrap: Effect.void,
projectEvent: () => Effect.void,
} satisfies OrchestrationProjectionPipelineShape),
),
Layer.provide(Layer.succeed(OrchestrationEventStore, failOnHistoricalReplayStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
);
const runtime = ManagedRuntime.make(layer);
const engine = await runtime.runPromise(Effect.service(OrchestrationEngineService));
const readModel = await runtime.runPromise(engine.getReadModel());
expect(readModel.snapshotSequence).toBe(7);
expect(readModel.projects).toHaveLength(1);
expect(readModel.projects[0]?.title).toBe("Bootstrap Project");
expect(readModel.threads).toHaveLength(1);
expect(readModel.threads[0]?.title).toBe("Bootstrap Thread");
await runtime.dispose();
});
it("returns deterministic read models for repeated reads", async () => {
const createdAt = now();
const system = await createOrchestrationSystem();
@@ -419,95 +306,6 @@ describe("OrchestrationEngine", () => {
await system.dispose();
});
it("records command ack duration using the first committed event type", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await system.run(
engine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe("cmd-project-ack-create"),
projectId: asProjectId("project-ack"),
title: "Ack Project",
workspaceRoot: "/tmp/project-ack",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
createdAt,
}),
);
await system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-ack-create"),
threadId: ThreadId.makeUnsafe("thread-ack"),
projectId: asProjectId("project-ack"),
title: "Ack Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
);
const snapshots = await system.run(Metric.snapshot);
expect(
hasMetricSnapshot(snapshots, "t3_orchestration_command_ack_duration", {
commandType: "thread.create",
aggregateKind: "thread",
ackEventType: "thread.created",
}),
).toBe(true);
await system.dispose();
});
it("records failed command dispatches as metric failures", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
const createdAt = now();
await expect(
system.run(
engine.dispatch({
type: "thread.create",
commandId: CommandId.makeUnsafe("cmd-thread-missing-project"),
threadId: ThreadId.makeUnsafe("thread-missing-project"),
projectId: asProjectId("project-missing"),
title: "Missing Project Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt,
}),
),
).rejects.toThrow("does not exist");
const snapshots = await system.run(Metric.snapshot);
expect(
hasMetricSnapshot(snapshots, "t3_orchestration_commands_total", {
commandType: "thread.create",
aggregateKind: "thread",
outcome: "failure",
}),
).toBe(true);
await system.dispose();
});
it("stores completed checkpoint summaries even when no files changed", async () => {
const system = await createOrchestrationSystem();
const { engine } = system;
@@ -619,7 +417,6 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -715,7 +512,6 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -857,7 +653,6 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -5,28 +5,9 @@ import type {
ThreadId,
} from "@t3tools/contracts";
import { OrchestrationCommand } from "@t3tools/contracts";
import {
Cause,
Deferred,
Duration,
Effect,
Exit,
Layer,
Metric,
Option,
PubSub,
Queue,
Schema,
Stream,
} from "effect";
import { Deferred, Effect, Layer, Option, PubSub, Queue, Schema, Stream } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import {
metricAttributes,
orchestrationCommandAckDuration,
orchestrationCommandsTotal,
orchestrationCommandDuration,
} from "../../observability/Metrics.ts";
import { toPersistenceSqlError } from "../../persistence/Errors.ts";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepository } from "../../persistence/Services/OrchestrationCommandReceipts.ts";
@@ -38,7 +19,6 @@ import {
import { decideOrchestrationCommand } from "../decider.ts";
import { createEmptyReadModel, projectEvent } from "../projector.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
OrchestrationEngineService,
type OrchestrationEngineShape,
@@ -47,7 +27,6 @@ import {
interface CommandEnvelope {
command: OrchestrationCommand;
result: Deferred.Deferred<{ sequence: number }, OrchestrationDispatchError>;
startedAtMs: number;
}
function commandToAggregateRef(command: OrchestrationCommand): {
@@ -75,7 +54,6 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const eventStore = yield* OrchestrationEventStore;
const commandReceiptRepository = yield* OrchestrationCommandReceiptRepository;
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
let readModel = createEmptyReadModel(new Date().toISOString());
@@ -84,12 +62,6 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const processEnvelope = (envelope: CommandEnvelope): Effect.Effect<void> => {
const dispatchStartSequence = readModel.snapshotSequence;
const processingStartedAtMs = Date.now();
const aggregateRef = commandToAggregateRef(envelope.command);
const baseMetricAttributes = {
commandType: envelope.command.type,
aggregateKind: aggregateRef.aggregateKind,
} as const;
const reconcileReadModelAfterDispatchFailure = Effect.gen(function* () {
const persistedEvents = yield* Stream.runCollect(
eventStore.readFromSequence(dispatchStartSequence),
@@ -109,160 +81,113 @@ const makeOrchestrationEngine = Effect.gen(function* () {
}
});
return Effect.exit(
Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({
"orchestration.command_id": envelope.command.commandId,
"orchestration.command_type": envelope.command.type,
"orchestration.aggregate_kind": aggregateRef.aggregateKind,
"orchestration.aggregate_id": aggregateRef.aggregateId,
});
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
commandId: envelope.command.commandId,
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
return {
sequence: existingReceipt.value.resultSequence,
};
}
return yield* new OrchestrationCommandPreviouslyRejectedError({
return Effect.gen(function* () {
const existingReceipt = yield* commandReceiptRepository.getByCommandId({
commandId: envelope.command.commandId,
});
if (Option.isSome(existingReceipt)) {
if (existingReceipt.value.status === "accepted") {
yield* Deferred.succeed(envelope.result, {
sequence: existingReceipt.value.resultSequence,
});
return;
}
yield* Deferred.fail(
envelope.result,
new OrchestrationCommandPreviouslyRejectedError({
commandId: envelope.command.commandId,
detail: existingReceipt.value.error ?? "Previously rejected.",
});
}
}),
);
return;
}
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextReadModel = readModel;
const eventBase = yield* decideOrchestrationCommand({
command: envelope.command,
readModel,
});
const eventBases = Array.isArray(eventBase) ? eventBase : [eventBase];
const committedCommand = yield* sql
.withTransaction(
Effect.gen(function* () {
const committedEvents: OrchestrationEvent[] = [];
let nextReadModel = readModel;
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
for (const nextEvent of eventBases) {
const savedEvent = yield* eventStore.append(nextEvent);
nextReadModel = yield* projectEvent(nextReadModel, savedEvent);
yield* projectionPipeline.projectEvent(savedEvent);
committedEvents.push(savedEvent);
}
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
});
}
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
const lastSavedEvent = committedEvents.at(-1) ?? null;
if (lastSavedEvent === null) {
return yield* new OrchestrationCommandInvariantError({
commandType: envelope.command.type,
detail: "Command produced no events.",
});
}
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
),
yield* commandReceiptRepository.upsert({
commandId: envelope.command.commandId,
aggregateKind: lastSavedEvent.aggregateKind,
aggregateId: lastSavedEvent.aggregateId,
acceptedAt: lastSavedEvent.occurredAt,
resultSequence: lastSavedEvent.sequence,
status: "accepted",
error: null,
});
return {
committedEvents,
lastSequence: lastSavedEvent.sequence,
nextReadModel,
} as const;
}),
)
.pipe(
Effect.catchTag("SqlError", (sqlError) =>
Effect.fail(
toPersistenceSqlError("OrchestrationEngine.processEnvelope:transaction")(sqlError),
),
);
),
);
readModel = committedCommand.nextReadModel;
for (const [index, event] of committedCommand.committedEvents.entries()) {
yield* PubSub.publish(eventPubSub, event);
if (index === 0) {
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandAckDuration,
metricAttributes({
...baseMetricAttributes,
ackEventType: event.type,
readModel = committedCommand.nextReadModel;
for (const event of committedCommand.committedEvents) {
yield* PubSub.publish(eventPubSub, event);
}
yield* Deferred.succeed(envelope.result, { sequence: committedCommand.lastSequence });
}).pipe(
Effect.catch((error) =>
Effect.gen(function* () {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: readModel.snapshotSequence,
}),
),
Duration.millis(Math.max(0, Date.now() - envelope.startedAtMs)),
);
}
}
return { sequence: committedCommand.lastSequence };
}).pipe(Effect.withSpan(`orchestration.command.${envelope.command.type}`)),
).pipe(
Effect.flatMap((exit) =>
Effect.gen(function* () {
const outcome = Exit.isSuccess(exit)
? "success"
: Cause.hasInterruptsOnly(exit.cause)
? "interrupt"
: "failure";
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandDuration,
metricAttributes(baseMetricAttributes),
),
Duration.millis(Math.max(0, Date.now() - processingStartedAtMs)),
);
yield* Metric.update(
Metric.withAttributes(
orchestrationCommandsTotal,
metricAttributes({
...baseMetricAttributes,
outcome,
}),
),
1,
);
if (Exit.isSuccess(exit)) {
yield* Deferred.succeed(envelope.result, exit.value);
return;
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
const aggregateRef = commandToAggregateRef(envelope.command);
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
}
const error = Cause.squash(exit.cause) as OrchestrationDispatchError;
if (!Schema.is(OrchestrationCommandPreviouslyRejectedError)(error)) {
yield* reconcileReadModelAfterDispatchFailure.pipe(
Effect.catch(() =>
Effect.logWarning(
"failed to reconcile orchestration read model after dispatch failure",
).pipe(
Effect.annotateLogs({
commandId: envelope.command.commandId,
snapshotSequence: readModel.snapshotSequence,
}),
),
),
);
if (Schema.is(OrchestrationCommandInvariantError)(error)) {
yield* commandReceiptRepository
.upsert({
commandId: envelope.command.commandId,
aggregateKind: aggregateRef.aggregateKind,
aggregateId: aggregateRef.aggregateId,
acceptedAt: new Date().toISOString(),
resultSequence: readModel.snapshotSequence,
status: "rejected",
error: error.message,
})
.pipe(Effect.catch(() => Effect.void));
}
}
yield* Deferred.fail(envelope.result, error);
}),
),
@@ -270,11 +195,17 @@ const makeOrchestrationEngine = Effect.gen(function* () {
};
yield* projectionPipeline.bootstrap;
readModel = yield* projectionSnapshotQuery.getSnapshot();
// bootstrap in-memory read model from event store
yield* Stream.runForEach(eventStore.readAll(), (event) =>
Effect.gen(function* () {
readModel = yield* projectEvent(readModel, event);
}),
);
const worker = Effect.forever(Queue.take(commandQueue).pipe(Effect.flatMap(processEnvelope)));
yield* Effect.forkScoped(worker);
yield* Effect.logDebug("orchestration engine started").pipe(
yield* Effect.log("orchestration engine started").pipe(
Effect.annotateLogs({ sequence: readModel.snapshotSequence }),
);
@@ -287,7 +218,7 @@ const makeOrchestrationEngine = Effect.gen(function* () {
const dispatch: OrchestrationEngineShape["dispatch"] = (command) =>
Effect.gen(function* () {
const result = yield* Deferred.make<{ sequence: number }, OrchestrationDispatchError>();
yield* Queue.offer(commandQueue, { command, result, startedAtMs: Date.now() });
yield* Queue.offer(commandQueue, { command, result });
return yield* Deferred.await(result);
});
@@ -25,7 +25,6 @@ import {
ORCHESTRATION_PROJECTOR_NAMES,
OrchestrationProjectionPipelineLive,
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -1842,7 +1841,6 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -3,6 +3,7 @@ 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";
@@ -623,28 +624,24 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
)(function* (event, attachmentSideEffects) {
switch (event.type) {
case "thread.message-sent": {
const existingMessage = yield* projectionThreadMessageRepository.getByMessageId({
messageId: event.payload.messageId,
});
const previousMessage = Option.getOrUndefined(existingMessage);
const nextText = Option.match(existingMessage, {
onNone: () => event.payload.text,
onSome: (message) => {
if (event.payload.streaming) {
return `${message.text}${event.payload.text}`;
}
if (event.payload.text.length === 0) {
return message.text;
}
return event.payload.text;
},
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,
})
: previousMessage?.attachments;
: existingMessage?.attachments;
yield* projectionThreadMessageRepository.upsert({
messageId: event.payload.messageId,
threadId: event.payload.threadId,
@@ -653,7 +650,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
text: nextText,
...(nextAttachments !== undefined ? { attachments: [...nextAttachments] } : {}),
isStreaming: event.payload.streaming,
createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
createdAt: existingMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
});
return;
@@ -1274,7 +1271,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
Effect.provideService(ServerConfig, serverConfig),
Effect.asVoid,
Effect.tap(() =>
Effect.logDebug("orchestration projection pipeline bootstrapped").pipe(
Effect.log("orchestration projection pipeline bootstrapped").pipe(
Effect.annotateLogs({ projectors: projectors.length }),
),
),
@@ -1294,6 +1291,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
OrchestrationProjectionPipeline,
makeOrchestrationProjectionPipeline(),
).pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ProjectionProjectRepositoryLive),
Layer.provideMerge(ProjectionThreadRepositoryLive),
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
@@ -1,3 +1,7 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
@@ -23,6 +27,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
const workspaceRoot = fs.mkdtempSync(path.join(os.tmpdir(), "projection-snapshot-"));
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_state`;
@@ -43,7 +48,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
VALUES (
'project-1',
'Project 1',
'/tmp/project-1',
${workspaceRoot},
'{"provider":"codex","model":"gpt-5-codex"}',
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
'2026-02-24T00:00:00.000Z',
@@ -233,7 +238,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
{
id: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
workspaceRoot,
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -265,6 +271,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: workspaceRoot,
effectiveCwdSource: "project",
effectiveCwdState: "available",
latestTurn: {
turnId: asTurnId("turn-1"),
state: "completed",
@@ -338,290 +347,4 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
]);
}),
);
it.effect(
"reads targeted project, thread, and count queries without hydrating the full snapshot",
() =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
(
'project-active',
'Active Project',
'/tmp/workspace',
'{"provider":"codex","model":"gpt-5-codex"}',
'[]',
'2026-03-01T00:00:00.000Z',
'2026-03-01T00:00:01.000Z',
NULL
),
(
'project-deleted',
'Deleted Project',
'/tmp/deleted',
NULL,
'[]',
'2026-03-01T00:00:02.000Z',
'2026-03-01T00:00:03.000Z',
'2026-03-01T00:00:04.000Z'
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES
(
'thread-first',
'project-active',
'First Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:05.000Z',
'2026-03-01T00:00:06.000Z',
NULL,
NULL
),
(
'thread-second',
'project-active',
'Second Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:07.000Z',
'2026-03-01T00:00:08.000Z',
NULL,
NULL
),
(
'thread-deleted',
'project-active',
'Deleted Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
NULL,
NULL,
NULL,
'2026-03-01T00:00:09.000Z',
'2026-03-01T00:00:10.000Z',
NULL,
'2026-03-01T00:00:11.000Z'
)
`;
const counts = yield* snapshotQuery.getCounts();
assert.deepEqual(counts, {
projectCount: 2,
threadCount: 3,
});
const project = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/workspace");
assert.equal(project._tag, "Some");
if (project._tag === "Some") {
assert.equal(project.value.id, asProjectId("project-active"));
}
const missingProject = yield* snapshotQuery.getActiveProjectByWorkspaceRoot("/tmp/missing");
assert.equal(missingProject._tag, "None");
const firstThreadId = yield* snapshotQuery.getFirstActiveThreadIdByProjectId(
asProjectId("project-active"),
);
assert.equal(firstThreadId._tag, "Some");
if (firstThreadId._tag === "Some") {
assert.equal(firstThreadId.value, ThreadId.makeUnsafe("thread-first"));
}
}),
);
it.effect("reads single-thread checkpoint context without hydrating unrelated threads", () =>
Effect.gen(function* () {
const snapshotQuery = yield* ProjectionSnapshotQuery;
const sql = yield* SqlClient.SqlClient;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
'project-context',
'Context Project',
'/tmp/context-workspace',
NULL,
'[]',
'2026-03-02T00:00:00.000Z',
'2026-03-02T00:00:01.000Z',
NULL
)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model_selection_json,
runtime_mode,
interaction_mode,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
archived_at,
deleted_at
)
VALUES (
'thread-context',
'project-context',
'Context Thread',
'{"provider":"codex","model":"gpt-5-codex"}',
'full-access',
'default',
'feature/perf',
'/tmp/context-worktree',
NULL,
'2026-03-02T00:00:02.000Z',
'2026-03-02T00:00:03.000Z',
NULL,
NULL
)
`;
yield* sql`
INSERT INTO projection_turns (
thread_id,
turn_id,
pending_message_id,
source_proposed_plan_thread_id,
source_proposed_plan_id,
assistant_message_id,
state,
requested_at,
started_at,
completed_at,
checkpoint_turn_count,
checkpoint_ref,
checkpoint_status,
checkpoint_files_json
)
VALUES
(
'thread-context',
'turn-1',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
'2026-03-02T00:00:04.000Z',
1,
'checkpoint-a',
'ready',
'[]'
),
(
'thread-context',
'turn-2',
NULL,
NULL,
NULL,
NULL,
'completed',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
'2026-03-02T00:00:05.000Z',
2,
'checkpoint-b',
'ready',
'[]'
)
`;
const context = yield* snapshotQuery.getThreadCheckpointContext(
ThreadId.makeUnsafe("thread-context"),
);
assert.equal(context._tag, "Some");
if (context._tag === "Some") {
assert.deepEqual(context.value, {
threadId: ThreadId.makeUnsafe("thread-context"),
projectId: asProjectId("project-context"),
workspaceRoot: "/tmp/context-workspace",
worktreePath: "/tmp/context-worktree",
checkpoints: [
{
turnId: asTurnId("turn-1"),
checkpointTurnCount: 1,
checkpointRef: asCheckpointRef("checkpoint-a"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:04.000Z",
},
{
turnId: asTurnId("turn-2"),
checkpointTurnCount: 2,
checkpointRef: asCheckpointRef("checkpoint-b"),
status: "ready",
files: [],
assistantMessageId: null,
completedAt: "2026-03-02T00:00:05.000Z",
},
],
});
}
}),
);
});
@@ -7,6 +7,7 @@ import {
OrchestrationProposedPlanId,
OrchestrationReadModel,
ProjectScript,
ThreadId,
TurnId,
type OrchestrationCheckpointSummary,
type OrchestrationLatestTurn,
@@ -17,10 +18,9 @@ import {
type OrchestrationThread,
type OrchestrationThreadActivity,
ModelSelection,
ProjectId,
ThreadId,
type WorkspaceAvailabilityState,
} from "@t3tools/contracts";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
@@ -41,10 +41,9 @@ import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.t
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
ProjectionSnapshotQuery,
type ProjectionSnapshotCounts,
type ProjectionThreadCheckpointContext,
type ProjectionSnapshotQueryShape,
} from "../Services/ProjectionSnapshotQuery.ts";
import { inspectWorkspacePathState } from "../../workspacePaths.ts";
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
@@ -89,29 +88,6 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
});
const ProjectionStateDbRowSchema = ProjectionState;
const ProjectionCountsRowSchema = Schema.Struct({
projectCount: Schema.Number,
threadCount: Schema.Number,
});
const WorkspaceRootLookupInput = Schema.Struct({
workspaceRoot: Schema.String,
});
const ProjectIdLookupInput = Schema.Struct({
projectId: ProjectId,
});
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
});
const ProjectionThreadCheckpointContextThreadRowSchema = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
workspaceRoot: Schema.String,
worktreePath: Schema.NullOr(Schema.String),
});
const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.projects,
@@ -161,6 +137,12 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
: toPersistenceSqlError(sqlOperation)(cause);
}
type EffectiveWorkspaceMetadata = {
readonly effectiveCwd: string | null;
readonly effectiveCwdSource: "project" | "worktree" | null;
readonly effectiveCwdState: WorkspaceAvailabilityState;
};
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -345,94 +327,6 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const readProjectionCounts = SqlSchema.findOne({
Request: Schema.Void,
Result: ProjectionCountsRowSchema,
execute: () =>
sql`
SELECT
(SELECT COUNT(*) FROM projection_projects) AS "projectCount",
(SELECT COUNT(*) FROM projection_threads) AS "threadCount"
`,
});
const getActiveProjectRowByWorkspaceRoot = SqlSchema.findOneOption({
Request: WorkspaceRootLookupInput,
Result: ProjectionProjectLookupRowSchema,
execute: ({ workspaceRoot }) =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
deleted_at AS "deletedAt"
FROM projection_projects
WHERE workspace_root = ${workspaceRoot}
AND deleted_at IS NULL
ORDER BY created_at ASC, project_id ASC
LIMIT 1
`,
});
const getFirstActiveThreadIdByProject = SqlSchema.findOneOption({
Request: ProjectIdLookupInput,
Result: ProjectionThreadIdLookupRowSchema,
execute: ({ projectId }) =>
sql`
SELECT
thread_id AS "threadId"
FROM projection_threads
WHERE project_id = ${projectId}
AND deleted_at IS NULL
ORDER BY created_at ASC, thread_id ASC
LIMIT 1
`,
});
const getThreadCheckpointContextThreadRow = SqlSchema.findOneOption({
Request: ThreadIdLookupInput,
Result: ProjectionThreadCheckpointContextThreadRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
threads.thread_id AS "threadId",
threads.project_id AS "projectId",
projects.workspace_root AS "workspaceRoot",
threads.worktree_path AS "worktreePath"
FROM projection_threads AS threads
INNER JOIN projection_projects AS projects
ON projects.project_id = threads.project_id
WHERE threads.thread_id = ${threadId}
AND threads.deleted_at IS NULL
LIMIT 1
`,
});
const listCheckpointRowsByThread = SqlSchema.findAll({
Request: ThreadIdLookupInput,
Result: ProjectionCheckpointDbRowSchema,
execute: ({ threadId }) =>
sql`
SELECT
thread_id AS "threadId",
turn_id AS "turnId",
checkpoint_turn_count AS "checkpointTurnCount",
checkpoint_ref AS "checkpointRef",
checkpoint_status AS "status",
checkpoint_files_json AS "files",
assistant_message_id AS "assistantMessageId",
completed_at AS "completedAt"
FROM projection_turns
WHERE thread_id = ${threadId}
AND checkpoint_turn_count IS NOT NULL
ORDER BY checkpoint_turn_count ASC
`,
});
const getSnapshot: ProjectionSnapshotQueryShape["getSnapshot"] = () =>
sql
.withTransaction(
@@ -652,10 +546,35 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
}
const workspaceRoots = new Set(projectRows.map((row) => row.workspaceRoot));
const worktreePaths = new Set(
threadRows.flatMap((row) => (row.worktreePath ? [row.worktreePath] : [])),
);
const workspaceStateEntries = yield* Effect.promise(() =>
Promise.all(
[...new Set([...workspaceRoots, ...worktreePaths])].map(async (workspacePath) => {
const workspaceState = await inspectWorkspacePathState(workspacePath);
return [workspacePath, workspaceState] as const;
}),
),
);
const workspaceStates = new Map(workspaceStateEntries);
const projectRowsById = new Map(projectRows.map((row) => [row.projectId, row] as const));
const projectWorkspaceStateById = new Map(
projectRows.map((row) => [
row.projectId,
workspaceStates.get(row.workspaceRoot) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
]),
);
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
workspaceState:
projectWorkspaceStateById.get(row.projectId) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
@@ -663,26 +582,48 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
deletedAt: row.deletedAt,
}));
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => {
const effectiveWorkspace: EffectiveWorkspaceMetadata =
row.worktreePath !== null
? {
effectiveCwd: row.worktreePath,
effectiveCwdSource: "worktree",
effectiveCwdState:
workspaceStates.get(row.worktreePath) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
}
: {
effectiveCwd: projectRowsById.get(row.projectId)?.workspaceRoot ?? null,
effectiveCwdSource: projectRowsById.has(row.projectId) ? "project" : null,
effectiveCwdState:
projectWorkspaceStateById.get(row.projectId) ??
("inaccessible" satisfies WorkspaceAvailabilityState),
};
return {
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
worktreePath: row.worktreePath,
effectiveCwd: effectiveWorkspace.effectiveCwd,
effectiveCwdSource: effectiveWorkspace.effectiveCwdSource,
effectiveCwdState: effectiveWorkspace.effectiveCwdState,
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
archivedAt: row.archivedAt,
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
};
});
const snapshot = {
snapshotSequence: computeSnapshotSequence(stateRows),
@@ -707,109 +648,8 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
}),
);
const getCounts: ProjectionSnapshotQueryShape["getCounts"] = () =>
readProjectionCounts(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getCounts:query",
"ProjectionSnapshotQuery.getCounts:decodeRow",
),
),
Effect.map(
(row): ProjectionSnapshotCounts => ({
projectCount: row.projectCount,
threadCount: row.threadCount,
}),
),
);
const getActiveProjectByWorkspaceRoot: ProjectionSnapshotQueryShape["getActiveProjectByWorkspaceRoot"] =
(workspaceRoot) =>
getActiveProjectRowByWorkspaceRoot({ workspaceRoot }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:query",
"ProjectionSnapshotQuery.getActiveProjectByWorkspaceRoot:decodeRow",
),
),
Effect.map(
Option.map(
(row): OrchestrationProject => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}),
),
),
);
const getFirstActiveThreadIdByProjectId: ProjectionSnapshotQueryShape["getFirstActiveThreadIdByProjectId"] =
(projectId) =>
getFirstActiveThreadIdByProject({ projectId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:query",
"ProjectionSnapshotQuery.getFirstActiveThreadIdByProjectId:decodeRow",
),
),
Effect.map(Option.map((row) => row.threadId)),
);
const getThreadCheckpointContext: ProjectionSnapshotQueryShape["getThreadCheckpointContext"] = (
threadId,
) =>
Effect.gen(function* () {
const threadRow = yield* getThreadCheckpointContextThreadRow({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:query",
"ProjectionSnapshotQuery.getThreadCheckpointContext:getThread:decodeRow",
),
),
);
if (Option.isNone(threadRow)) {
return Option.none<ProjectionThreadCheckpointContext>();
}
const checkpointRows = yield* listCheckpointRowsByThread({ threadId }).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:query",
"ProjectionSnapshotQuery.getThreadCheckpointContext:listCheckpoints:decodeRows",
),
),
);
return Option.some({
threadId: threadRow.value.threadId,
projectId: threadRow.value.projectId,
workspaceRoot: threadRow.value.workspaceRoot,
worktreePath: threadRow.value.worktreePath,
checkpoints: checkpointRows.map(
(row): OrchestrationCheckpointSummary => ({
turnId: row.turnId,
checkpointTurnCount: row.checkpointTurnCount,
checkpointRef: row.checkpointRef,
status: row.status,
files: row.files,
assistantMessageId: row.assistantMessageId,
completedAt: row.completedAt,
}),
),
});
});
return {
getSnapshot,
getCounts,
getActiveProjectByWorkspaceRoot,
getFirstActiveThreadIdByProjectId,
getThreadCheckpointContext,
} satisfies ProjectionSnapshotQueryShape;
});
@@ -17,7 +17,7 @@ import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effe
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { TextGenerationError } from "@t3tools/contracts";
import { TextGenerationError } from "../../git/Errors.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -30,7 +30,6 @@ import { GitCore, type GitCoreShape } from "../../git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../../git/Services/TextGeneration.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
@@ -46,6 +45,8 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const deriveServerPathsSync = (baseDir: string, devUrl: URL | undefined) =>
Effect.runSync(deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)));
fs.mkdirSync("/tmp/provider-project", { recursive: true });
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
@@ -212,7 +213,6 @@ describe("ProviderCommandReactor", () => {
};
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -16,7 +16,6 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { increment, orchestrationEventsProcessedTotal } from "../../observability/Metrics.ts";
import { ProviderAdapterRequestError, ProviderServiceError } from "../../provider/Errors.ts";
import { TextGeneration } from "../../git/Services/TextGeneration.ts";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
@@ -26,6 +25,7 @@ import {
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { assertWorkspaceDirectory } from "../../workspacePaths.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -213,12 +213,12 @@ const make = Effect.gen(function* () {
createdAt: input.createdAt,
});
const resolveThread = Effect.fn("resolveThread")(function* (threadId: ThreadId) {
const resolveThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
return readModel.threads.find((entry) => entry.id === threadId);
});
const ensureSessionForThread = Effect.fn("ensureSessionForThread")(function* (
const ensureSessionForThread = Effect.fnUntraced(function* (
threadId: ThreadId,
createdAt: string,
options?: {
@@ -255,6 +255,12 @@ const make = Effect.gen(function* () {
thread,
projects: readModel.projects,
});
if (effectiveCwd) {
yield* assertWorkspaceDirectory(
effectiveCwd,
"ProviderCommandReactor.ensureSessionForThread",
);
}
const resolveActiveSession = (threadId: ThreadId) =>
providerService
@@ -358,7 +364,7 @@ const make = Effect.gen(function* () {
return startedSession.threadId;
});
const sendTurnForThread = Effect.fn("sendTurnForThread")(function* (input: {
const sendTurnForThread = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
@@ -410,9 +416,7 @@ const make = Effect.gen(function* () {
});
});
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fn(
"maybeGenerateAndRenameWorktreeBranchForFirstTurn",
)(function* (input: {
const maybeGenerateAndRenameWorktreeBranchForFirstTurn = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly branch: string | null;
readonly worktreePath: string | null;
@@ -464,52 +468,50 @@ const make = Effect.gen(function* () {
);
});
const maybeGenerateThreadTitleForFirstTurn = Effect.fn("maybeGenerateThreadTitleForFirstTurn")(
function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly titleSeed?: string;
}) {
const attachments = input.attachments ?? [];
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const maybeGenerateThreadTitleForFirstTurn = Effect.fnUntraced(function* (input: {
readonly threadId: ThreadId;
readonly cwd: string;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly titleSeed?: string;
}) {
const attachments = input.attachments ?? [];
yield* Effect.gen(function* () {
const { textGenerationModelSelection: modelSelection } =
yield* serverSettingsService.getSettings;
const generated = yield* textGeneration.generateThreadTitle({
cwd: input.cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
});
if (!generated) return;
const generated = yield* textGeneration.generateThreadTitle({
cwd: input.cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
});
if (!generated) return;
const thread = yield* resolveThread(input.threadId);
if (!thread) return;
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
return;
}
const thread = yield* resolveThread(input.threadId);
if (!thread) return;
if (!canReplaceThreadTitle(thread.title, input.titleSeed)) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
yield* orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("thread-title-rename"),
threadId: input.threadId,
title: generated.title,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
threadId: input.threadId,
title: generated.title,
});
}).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename thread title", {
threadId: input.threadId,
cwd: input.cwd,
cause: Cause.pretty(cause),
}),
),
);
},
);
cwd: input.cwd,
cause: Cause.pretty(cause),
}),
),
);
});
const processTurnStartRequested = Effect.fn("processTurnStartRequested")(function* (
const processTurnStartRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.turn-start-requested" }>,
) {
const key = turnStartKeyForEvent(event);
@@ -588,7 +590,7 @@ const make = Effect.gen(function* () {
);
});
const processTurnInterruptRequested = Effect.fn("processTurnInterruptRequested")(function* (
const processTurnInterruptRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.turn-interrupt-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -611,7 +613,7 @@ const make = Effect.gen(function* () {
yield* providerService.interruptTurn({ threadId: event.payload.threadId });
});
const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* (
const processApprovalResponseRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.approval-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -658,52 +660,50 @@ const make = Effect.gen(function* () {
);
});
const processUserInputResponseRequested = Effect.fn("processUserInputResponseRequested")(
function* (
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}
const processUserInputResponseRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.user-input-response-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread) {
return;
}
const hasSession = thread.session && thread.session.status !== "stopped";
if (!hasSession) {
return yield* appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: "No active provider session is bound to this thread.",
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
});
}
yield* providerService
.respondToUserInput({
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
})
.pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
},
);
yield* providerService
.respondToUserInput({
threadId: event.payload.threadId,
requestId: event.payload.requestId,
answers: event.payload.answers,
})
.pipe(
Effect.catchCause((cause) =>
appendProviderFailureActivity({
threadId: event.payload.threadId,
kind: "provider.user-input.respond.failed",
summary: "Provider user input response failed",
detail: isUnknownPendingUserInputRequestError(cause)
? stalePendingRequestDetail("user-input", event.payload.requestId)
: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
}),
),
);
});
const processSessionStopRequested = Effect.fn("processSessionStopRequested")(function* (
const processSessionStopRequested = Effect.fnUntraced(function* (
event: Extract<ProviderIntentEvent, { type: "thread.session-stop-requested" }>,
) {
const thread = yield* resolveThread(event.payload.threadId);
@@ -731,48 +731,39 @@ const make = Effect.gen(function* () {
});
});
const processDomainEvent = Effect.fn("processDomainEvent")(function* (
event: ProviderIntentEvent,
) {
yield* Effect.annotateCurrentSpan({
"orchestration.event_type": event.type,
"orchestration.thread_id": event.payload.threadId,
...(event.commandId ? { "orchestration.command_id": event.commandId } : {}),
});
yield* increment(orchestrationEventsProcessedTotal, {
eventType: event.type,
});
switch (event.type) {
case "thread.runtime-mode-set": {
const thread = yield* resolveThread(event.payload.threadId);
if (!thread?.session || thread.session.status === "stopped") {
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 } : {},
);
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;
}
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(
@@ -31,7 +31,6 @@ import {
} from "../../provider/Services/ProviderService.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import {
OrchestrationEngineService,
@@ -198,7 +197,6 @@ describe("ProviderRuntimeIngestion", () => {
fs.mkdirSync(path.join(workspaceRoot, ".git"));
const provider = createProviderServiceHarness();
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -524,7 +524,7 @@ const make = Effect.fn("make")(function* () {
lookup: () => Effect.succeed({ text: "", createdAt: "" }),
});
const isGitRepoForThread = Effect.fn("isGitRepoForThread")(function* (threadId: ThreadId) {
const isGitRepoForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const readModel = yield* orchestrationEngine.getReadModel();
const thread = readModel.threads.find((entry) => entry.id === threadId);
if (!thread) {
@@ -796,9 +796,9 @@ const make = Effect.fn("make")(function* () {
).pipe(Effect.asVoid);
});
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fn(
"getSourceProposedPlanReferenceForPendingTurnStart",
)(function* (threadId: ThreadId) {
const getSourceProposedPlanReferenceForPendingTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
) {
const pendingTurnStart = yield* projectionTurnRepository.getPendingTurnStartByThreadId({
threadId,
});
@@ -818,17 +818,16 @@ const make = Effect.fn("make")(function* () {
} as const;
});
const getExpectedProviderTurnIdForThread = Effect.fn("getExpectedProviderTurnIdForThread")(
function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
},
);
const getExpectedProviderTurnIdForThread = Effect.fnUntraced(function* (threadId: ThreadId) {
const sessions = yield* providerService.listSessions();
const session = sessions.find((entry) => entry.threadId === threadId);
return session?.activeTurnId;
});
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fn(
"getSourceProposedPlanReferenceForAcceptedTurnStart",
)(function* (threadId: ThreadId, eventTurnId: TurnId | undefined) {
const getSourceProposedPlanReferenceForAcceptedTurnStart = Effect.fnUntraced(function* (
threadId: ThreadId,
eventTurnId: TurnId | undefined,
) {
if (eventTurnId === undefined) {
return null;
}
@@ -841,36 +840,34 @@ const make = Effect.fn("make")(function* () {
return yield* getSourceProposedPlanReferenceForPendingTurnStart(threadId);
});
const markSourceProposedPlanImplemented = Effect.fn("markSourceProposedPlanImplemented")(
function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
const markSourceProposedPlanImplemented = Effect.fnUntraced(function* (
sourceThreadId: ThreadId,
sourcePlanId: OrchestrationProposedPlanId,
implementationThreadId: ThreadId,
implementedAt: string,
) {
const readModel = yield* orchestrationEngine.getReadModel();
const sourceThread = readModel.threads.find((entry) => entry.id === sourceThreadId);
const sourcePlan = sourceThread?.proposedPlans.find((entry) => entry.id === sourcePlanId);
if (!sourceThread || !sourcePlan || sourcePlan.implementedAt !== null) {
return;
}
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
},
);
yield* orchestrationEngine.dispatch({
type: "thread.proposed-plan.upsert",
commandId: CommandId.makeUnsafe(
`provider:source-proposed-plan-implemented:${implementationThreadId}:${crypto.randomUUID()}`,
),
threadId: sourceThread.id,
proposedPlan: {
...sourcePlan,
implementedAt,
implementationThreadId,
updatedAt: implementedAt,
},
createdAt: implementedAt,
});
});
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
event: ProviderRuntimeEvent,
-121
View File
@@ -1,121 +0,0 @@
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;
});
@@ -6,32 +6,12 @@
*
* @module ProjectionSnapshotQuery
*/
import type {
OrchestrationCheckpointSummary,
OrchestrationProject,
OrchestrationReadModel,
ProjectId,
ThreadId,
} from "@t3tools/contracts";
import type { OrchestrationReadModel } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../../persistence/Errors.ts";
export interface ProjectionSnapshotCounts {
readonly projectCount: number;
readonly threadCount: number;
}
export interface ProjectionThreadCheckpointContext {
readonly threadId: ThreadId;
readonly projectId: ProjectId;
readonly workspaceRoot: string;
readonly worktreePath: string | null;
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
}
/**
* ProjectionSnapshotQueryShape - Service API for read-model snapshots.
*/
@@ -43,32 +23,6 @@ export interface ProjectionSnapshotQueryShape {
* projector cursor state.
*/
readonly getSnapshot: () => Effect.Effect<OrchestrationReadModel, ProjectionRepositoryError>;
/**
* Read aggregate projection counts without hydrating the full read model.
*/
readonly getCounts: () => Effect.Effect<ProjectionSnapshotCounts, ProjectionRepositoryError>;
/**
* Read the active project for an exact workspace root match.
*/
readonly getActiveProjectByWorkspaceRoot: (
workspaceRoot: string,
) => Effect.Effect<Option.Option<OrchestrationProject>, ProjectionRepositoryError>;
/**
* Read the earliest active thread for a project.
*/
readonly getFirstActiveThreadIdByProjectId: (
projectId: ProjectId,
) => Effect.Effect<Option.Option<ThreadId>, ProjectionRepositoryError>;
/**
* Read the checkpoint context needed to resolve a single thread diff.
*/
readonly getThreadCheckpointContext: (
threadId: ThreadId,
) => Effect.Effect<Option.Option<ProjectionThreadCheckpointContext>, ProjectionRepositoryError>;
}
/**
@@ -28,6 +28,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -41,6 +42,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
workspaceState: "available",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
@@ -64,6 +66,9 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project-a",
effectiveCwdSource: "project",
effectiveCwdState: "available",
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -87,6 +92,9 @@ const readModel: OrchestrationReadModel = {
runtimeMode: "full-access",
branch: null,
worktreePath: null,
effectiveCwd: "/tmp/project-b",
effectiveCwdSource: "project",
effectiveCwdState: "available",
createdAt: now,
updatedAt: now,
archivedAt: null,
@@ -183,6 +183,7 @@ export function projectEvent(
id: payload.projectId,
title: payload.title,
workspaceRoot: payload.workspaceRoot,
workspaceState: "available" as const,
defaultModelSelection: payload.defaultModelSelection,
scripts: payload.scripts,
createdAt: payload.createdAt,
@@ -55,13 +55,6 @@ layer("ProjectionThreadMessageRepository", (it) => {
assert.equal(rows.length, 1);
assert.equal(rows[0]?.text, "updated");
assert.deepEqual(rows[0]?.attachments, persistedAttachments);
const rowById = yield* repository.getByMessageId({ messageId });
assert.equal(rowById._tag, "Some");
if (rowById._tag === "Some") {
assert.equal(rowById.value.text, "updated");
assert.deepEqual(rowById.value.attachments, persistedAttachments);
}
}),
);
@@ -1,11 +1,10 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { Effect, Layer, Schema, Struct } from "effect";
import { ChatAttachment } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
GetProjectionThreadMessageInput,
ProjectionThreadMessageRepository,
type ProjectionThreadMessageRepositoryShape,
DeleteProjectionThreadMessagesInput,
@@ -20,22 +19,6 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
}),
);
function toProjectionThreadMessage(
row: Schema.Schema.Type<typeof ProjectionThreadMessageDbRowSchema>,
): ProjectionThreadMessage {
return {
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;
@@ -91,27 +74,6 @@ 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}
LIMIT 1
`,
});
const listProjectionThreadMessageRows = SqlSchema.findAll({
Request: ListProjectionThreadMessagesInput,
Result: ProjectionThreadMessageDbRowSchema,
@@ -147,20 +109,24 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
Effect.mapError(toPersistenceSqlError("ProjectionThreadMessageRepository.upsert:query")),
);
const getByMessageId: ProjectionThreadMessageRepositoryShape["getByMessageId"] = (input) =>
getProjectionThreadMessageRow(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.getByMessageId:query"),
),
Effect.map(Option.map(toProjectionThreadMessage)),
);
const listByThreadId: ProjectionThreadMessageRepositoryShape["listByThreadId"] = (input) =>
listProjectionThreadMessageRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadMessageRepository.listByThreadId:query"),
),
Effect.map((rows) => rows.map(toProjectionThreadMessage)),
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 } : {}),
})),
),
);
const deleteByThreadId: ProjectionThreadMessageRepositoryShape["deleteByThreadId"] = (input) =>
@@ -172,7 +138,6 @@ const makeProjectionThreadMessageRepository = Effect.gen(function* () {
return {
upsert,
getByMessageId,
listByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadMessageRepositoryShape;
+15 -25
View File
@@ -6,7 +6,6 @@ import { ServerConfig } from "../../config.ts";
type RuntimeSqliteLayerConfig = {
readonly filename: string;
readonly spanAttributes?: Record<string, unknown>;
};
type Loader = {
@@ -17,14 +16,15 @@ const defaultSqliteClientLoaders = {
node: () => import("../NodeSqliteClient.ts"),
} satisfies Record<string, () => Promise<Loader>>;
const makeRuntimeSqliteLayer = Effect.fn("makeRuntimeSqliteLayer")(function* (
const makeRuntimeSqliteLayer = (
config: RuntimeSqliteLayerConfig,
) {
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);
): 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 setup = Layer.effectDiscard(
Effect.gen(function* () {
@@ -35,24 +35,14 @@ const setup = Layer.effectDiscard(
}),
);
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 });
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 });
return Layer.provideMerge(
setup,
makeRuntimeSqliteLayer({
filename: dbPath,
spanAttributes: {
"db.name": path.basename(dbPath),
"service.name": "t3-server",
},
}),
);
}, Layer.unwrap);
return Layer.provideMerge(setup, makeRuntimeSqliteLayer({ filename: dbPath }));
}).pipe(Layer.unwrap);
export const SqlitePersistenceMemory = Layer.provideMerge(
setup,
+13 -16
View File
@@ -31,7 +31,6 @@ import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0017 from "./Migrations/017_ProjectionThreadsArchivedAt.ts";
import Migration0018 from "./Migrations/018_ProjectionThreadsArchivedAtIndex.ts";
import Migration0019 from "./Migrations/019_ProjectionSnapshotLookupIndexes.ts";
/**
* Migration loader with all migrations defined inline.
@@ -62,7 +61,6 @@ export const migrationEntries = [
[16, "CanonicalizeModelSelections", Migration0016],
[17, "ProjectionThreadsArchivedAt", Migration0017],
[18, "ProjectionThreadsArchivedAtIndex", Migration0018],
[19, "ProjectionSnapshotLookupIndexes", Migration0019],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -94,20 +92,19 @@ export interface RunMigrationsOptions {
*
* @returns Effect containing array of executed migrations
*/
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;
});
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;
});
/**
* Layer that runs migrations when the layer is built.
@@ -1,73 +0,0 @@
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { runMigrations } from "../Migrations.ts";
import * as NodeSqliteClient from "../NodeSqliteClient.ts";
const layer = it.layer(Layer.mergeAll(NodeSqliteClient.layerMemory()));
layer("019_ProjectionSnapshotLookupIndexes", (it) => {
it.effect("creates indexes for targeted projection lookup filters", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* runMigrations({ toMigrationInclusive: 18 });
yield* runMigrations({ toMigrationInclusive: 19 });
const projectIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_projects)
`;
assert.ok(
projectIndexes.some(
(index) => index.name === "idx_projection_projects_workspace_root_deleted_at",
),
);
const projectIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_projects_workspace_root_deleted_at')
`;
assert.deepStrictEqual(
projectIndexColumns.map((column) => column.name),
["workspace_root", "deleted_at"],
);
const threadIndexes = yield* sql<{
readonly seq: number;
readonly name: string;
readonly unique: number;
readonly origin: string;
readonly partial: number;
}>`
PRAGMA index_list(projection_threads)
`;
assert.ok(
threadIndexes.some(
(index) => index.name === "idx_projection_threads_project_deleted_created",
),
);
const threadIndexColumns = yield* sql<{
readonly seqno: number;
readonly cid: number;
readonly name: string;
}>`
PRAGMA index_info('idx_projection_threads_project_deleted_created')
`;
assert.deepStrictEqual(
threadIndexColumns.map((column) => column.name),
["project_id", "deleted_at", "created_at"],
);
}),
);
});
@@ -1,16 +0,0 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_projects_workspace_root_deleted_at
ON projection_projects(workspace_root, deleted_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_threads_project_deleted_created
ON projection_threads(project_id, deleted_at, created_at)
`;
});
+136 -129
View File
@@ -72,153 +72,160 @@ const checkNodeSqliteCompat = () => {
return Effect.void;
};
const makeWithDatabase = Effect.fn("makeWithDatabase")(function* (
const makeWithDatabase = (
options: SqliteClientConfig,
openDatabase: () => DatabaseSync,
): Effect.fn.Return<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> {
yield* checkNodeSqliteCompat();
): Effect.Effect<Client.SqlClient, never, Scope.Scope | Reactivity.Reactivity> =>
Effect.gen(function* () {
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 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 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 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) =>
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",
}),
}),
}),
(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 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,
);
});
return yield* Client.make({
acquirer,
compiler,
transactionAcquirer,
spanAttributes: [
...(options.spanAttributes ? Object.entries(options.spanAttributes) : []),
[ATTR_DB_SYSTEM_NAME, "sqlite"],
],
transformRows,
});
});
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> =>
@@ -8,14 +8,13 @@
*/
import {
ChatAttachment,
MessageId,
OrchestrationMessageRole,
MessageId,
ThreadId,
TurnId,
IsoDateTime,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Option } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
@@ -38,11 +37,6 @@ export const ListProjectionThreadMessagesInput = Schema.Struct({
});
export type ListProjectionThreadMessagesInput = typeof ListProjectionThreadMessagesInput.Type;
export const GetProjectionThreadMessageInput = Schema.Struct({
messageId: MessageId,
});
export type GetProjectionThreadMessageInput = typeof GetProjectionThreadMessageInput.Type;
export const DeleteProjectionThreadMessagesInput = Schema.Struct({
threadId: ThreadId,
});
@@ -61,13 +55,6 @@ export interface ProjectionThreadMessageRepositoryShape {
message: ProjectionThreadMessage,
) => Effect.Effect<void, ProjectionRepositoryError>;
/**
* Read a projected thread message by id.
*/
readonly getByMessageId: (
input: GetProjectionThreadMessageInput,
) => Effect.Effect<Option.Option<ProjectionThreadMessage>, ProjectionRepositoryError>;
/**
* List projected thread messages for a thread.
*
@@ -1,74 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, describe, expect } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { ProjectFaviconResolver } from "../Services/ProjectFaviconResolver.ts";
import { ProjectFaviconResolverLive } from "./ProjectFaviconResolver.ts";
const TestLayer = Layer.empty.pipe(
Layer.provideMerge(ProjectFaviconResolverLive),
Layer.provideMerge(NodeServices.layer),
);
const makeTempDir = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
return yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3code-project-favicon-",
});
});
const writeTextFile = Effect.fn("writeTextFile")(function* (
cwd: string,
relativePath: string,
contents: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const absolutePath = path.join(cwd, relativePath);
yield* fileSystem
.makeDirectory(path.dirname(absolutePath), { recursive: true })
.pipe(Effect.orDie);
yield* fileSystem.writeFileString(absolutePath, contents).pipe(Effect.orDie);
});
it.layer(TestLayer)("ProjectFaviconResolverLive", (it) => {
describe("resolvePath", () => {
it.effect("prefers well-known favicon files", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "favicon.svg", "<svg>favicon</svg>");
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).not.toBeNull();
expect(resolved).toContain("favicon.svg");
}),
);
it.effect("resolves icon hrefs from project source files", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver;
const cwd = yield* makeTempDir;
yield* writeTextFile(cwd, "index.html", '<link rel="icon" href="/brand/logo.svg">');
yield* writeTextFile(cwd, "public/brand/logo.svg", "<svg>brand</svg>");
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).not.toBeNull();
expect(resolved).toContain("public/brand/logo.svg");
}),
);
it.effect("returns null when no icon is present", () =>
Effect.gen(function* () {
const resolver = yield* ProjectFaviconResolver;
const cwd = yield* makeTempDir;
const resolved = yield* resolver.resolvePath(cwd);
expect(resolved).toBeNull();
}),
);
});
});
@@ -1,129 +0,0 @@
import { Effect, FileSystem, Layer, Path } from "effect";
import {
ProjectFaviconResolver,
type ProjectFaviconResolverShape,
} from "../Services/ProjectFaviconResolver.ts";
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
"favicon.svg",
"favicon.ico",
"favicon.png",
"public/favicon.svg",
"public/favicon.ico",
"public/favicon.png",
"app/favicon.ico",
"app/favicon.png",
"app/icon.svg",
"app/icon.png",
"app/icon.ico",
"src/favicon.ico",
"src/favicon.svg",
"src/app/favicon.ico",
"src/app/icon.svg",
"src/app/icon.png",
"assets/icon.svg",
"assets/icon.png",
"assets/logo.svg",
"assets/logo.png",
] as const;
// Files that may contain a <link rel="icon"> or icon metadata declaration.
const ICON_SOURCE_FILES = [
"index.html",
"public/index.html",
"app/routes/__root.tsx",
"src/routes/__root.tsx",
"app/root.tsx",
"src/root.tsx",
"src/index.html",
] as const;
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
const LINK_ICON_HTML_RE =
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
const LINK_ICON_OBJ_RE =
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
function extractIconHref(source: string): string | null {
const htmlMatch = source.match(LINK_ICON_HTML_RE);
if (htmlMatch?.[1]) return htmlMatch[1];
const objMatch = source.match(LINK_ICON_OBJ_RE);
if (objMatch?.[1]) return objMatch[1];
return null;
}
export const makeProjectFaviconResolver = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const resolveIconHref = (projectCwd: string, href: string): string[] => {
const clean = href.replace(/^\//, "");
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
};
const isPathWithinProject = (projectCwd: string, candidatePath: string): boolean => {
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
};
const findExistingFile = Effect.fn("ProjectFaviconResolver.findExistingFile")(function* (
projectCwd: string,
candidates: ReadonlyArray<string>,
): Effect.fn.Return<string | null> {
for (const candidate of candidates) {
if (!isPathWithinProject(projectCwd, candidate)) {
continue;
}
const stats = yield* fileSystem
.stat(candidate)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (stats?.type === "File") {
return candidate;
}
}
return null;
});
const resolvePath: ProjectFaviconResolverShape["resolvePath"] = Effect.fn(
"ProjectFaviconResolver.resolvePath",
)(function* (cwd: string): Effect.fn.Return<string | null> {
for (const candidate of FAVICON_CANDIDATES) {
const resolved = path.join(cwd, candidate);
const existing = yield* findExistingFile(cwd, [resolved]);
if (existing) {
return existing;
}
}
for (const sourceFile of ICON_SOURCE_FILES) {
const sourcePath = path.join(cwd, sourceFile);
const source = yield* fileSystem
.readFileString(sourcePath)
.pipe(Effect.catch(() => Effect.succeed(null)));
if (!source) {
continue;
}
const href = extractIconHref(source);
if (!href) {
continue;
}
const existing = yield* findExistingFile(cwd, resolveIconHref(cwd, href));
if (existing) {
return existing;
}
}
return null;
});
return {
resolvePath,
} satisfies ProjectFaviconResolverShape;
});
export const ProjectFaviconResolverLive = Layer.effect(
ProjectFaviconResolver,
makeProjectFaviconResolver,
);
@@ -1,166 +0,0 @@
import { Effect, Layer, Stream } from "effect";
import { describe, expect, it, vi } from "vitest";
import type { OrchestrationReadModel } from "@t3tools/contracts";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import { ProjectSetupScriptRunner } from "../Services/ProjectSetupScriptRunner.ts";
import { ProjectSetupScriptRunnerLive } from "./ProjectSetupScriptRunner.ts";
const emptySnapshot = (
scripts: OrchestrationReadModel["projects"][number]["scripts"],
): OrchestrationReadModel =>
({
snapshotSequence: 1,
updatedAt: "2026-01-01T00:00:00.000Z",
projects: [
{
id: "project-1",
title: "Project",
workspaceRoot: "/repo/project",
defaultModelSelection: null,
scripts,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
deletedAt: null,
},
],
threads: [],
providerSessions: [],
providerStatuses: [],
pendingApprovals: [],
latestTurnByThreadId: {},
}) as unknown as OrchestrationReadModel;
describe("ProjectSetupScriptRunner", () => {
it("returns no-script when no setup script exists", async () => {
const open = vi.fn();
const write = vi.fn();
const runner = await Effect.runPromise(
Effect.service(ProjectSetupScriptRunner).pipe(
Effect.provide(
ProjectSetupScriptRunnerLive.pipe(
Layer.provideMerge(
Layer.succeed(OrchestrationEngineService, {
getReadModel: () => Effect.succeed(emptySnapshot([])),
readEvents: () => Stream.empty,
dispatch: () => Effect.die(new Error("unused")),
streamDomainEvents: Stream.empty,
}),
),
Layer.provideMerge(
Layer.succeed(TerminalManager, {
open,
write,
resize: () => Effect.void,
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
close: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
}),
),
),
),
),
);
const result = await Effect.runPromise(
runner.runForThread({
threadId: "thread-1",
projectId: "project-1",
worktreePath: "/repo/worktrees/a",
}),
);
expect(result).toEqual({ status: "no-script" });
expect(open).not.toHaveBeenCalled();
expect(write).not.toHaveBeenCalled();
});
it("opens the deterministic setup terminal with worktree env and writes the command", async () => {
const open = vi.fn(() =>
Effect.succeed({
threadId: "thread-1",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
worktreePath: "/repo/worktrees/a",
status: "running" as const,
pid: 123,
history: "",
exitCode: null,
exitSignal: null,
updatedAt: "2026-01-01T00:00:00.000Z",
}),
);
const write = vi.fn(() => Effect.void);
const runner = await Effect.runPromise(
Effect.service(ProjectSetupScriptRunner).pipe(
Effect.provide(
ProjectSetupScriptRunnerLive.pipe(
Layer.provideMerge(
Layer.succeed(OrchestrationEngineService, {
getReadModel: () =>
Effect.succeed(
emptySnapshot([
{
id: "setup",
name: "Setup",
command: "bun install",
icon: "configure",
runOnWorktreeCreate: true,
},
]),
),
readEvents: () => Stream.empty,
dispatch: () => Effect.die(new Error("unused")),
streamDomainEvents: Stream.empty,
}),
),
Layer.provideMerge(
Layer.succeed(TerminalManager, {
open,
write,
resize: () => Effect.void,
clear: () => Effect.void,
restart: () => Effect.die(new Error("unused")),
close: () => Effect.void,
subscribe: () => Effect.succeed(() => undefined),
}),
),
),
),
),
);
const result = await Effect.runPromise(
runner.runForThread({
threadId: "thread-1",
projectCwd: "/repo/project",
worktreePath: "/repo/worktrees/a",
}),
);
expect(result).toEqual({
status: "started",
scriptId: "setup",
scriptName: "Setup",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
});
expect(open).toHaveBeenCalledWith({
threadId: "thread-1",
terminalId: "setup-setup",
cwd: "/repo/worktrees/a",
worktreePath: "/repo/worktrees/a",
env: {
T3CODE_PROJECT_ROOT: "/repo/project",
T3CODE_WORKTREE_PATH: "/repo/worktrees/a",
},
});
expect(write).toHaveBeenCalledWith({
threadId: "thread-1",
terminalId: "setup-setup",
data: "bun install\r",
});
});
});
@@ -1,75 +0,0 @@
import { projectScriptRuntimeEnv, setupProjectScript } from "@t3tools/shared/projectScripts";
import { Effect, Layer } from "effect";
import { OrchestrationEngineService } from "../../orchestration/Services/OrchestrationEngine.ts";
import { TerminalManager } from "../../terminal/Services/Manager.ts";
import {
type ProjectSetupScriptRunnerShape,
ProjectSetupScriptRunner,
} from "../Services/ProjectSetupScriptRunner.ts";
const makeProjectSetupScriptRunner = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const terminalManager = yield* TerminalManager;
const runForThread: ProjectSetupScriptRunnerShape["runForThread"] = (input) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
const project =
(input.projectId
? readModel.projects.find((entry) => entry.id === input.projectId)
: null) ??
(input.projectCwd
? readModel.projects.find((entry) => entry.workspaceRoot === input.projectCwd)
: null) ??
null;
if (!project) {
return yield* Effect.fail(new Error("Project was not found for setup script execution."));
}
const script = setupProjectScript(project.scripts);
if (!script) {
return {
status: "no-script",
} as const;
}
const terminalId = input.preferredTerminalId ?? `setup-${script.id}`;
const cwd = input.worktreePath;
const env = projectScriptRuntimeEnv({
project: { cwd: project.workspaceRoot },
worktreePath: input.worktreePath,
});
yield* terminalManager.open({
threadId: input.threadId,
terminalId,
cwd,
worktreePath: input.worktreePath,
env,
});
yield* terminalManager.write({
threadId: input.threadId,
terminalId,
data: `${script.command}\r`,
});
return {
status: "started",
scriptId: script.id,
scriptName: script.name,
terminalId,
cwd,
} as const;
});
return {
runForThread,
} satisfies ProjectSetupScriptRunnerShape;
});
export const ProjectSetupScriptRunnerLive = Layer.effect(
ProjectSetupScriptRunner,
makeProjectSetupScriptRunner,
);
@@ -1,30 +0,0 @@
/**
* ProjectFaviconResolver - Effect service contract for project icon discovery.
*
* Resolves a representative favicon or app icon file for a workspace by
* checking common file locations and project source metadata.
*
* @module ProjectFaviconResolver
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
/**
* ProjectFaviconResolverShape - Service API for project favicon lookup.
*/
export interface ProjectFaviconResolverShape {
/**
* Resolve a favicon or icon file path for the provided workspace root.
*
* Returns `null` when no candidate icon file can be found.
*/
readonly resolvePath: (cwd: string) => Effect.Effect<string | null>;
}
/**
* ProjectFaviconResolver - Service tag for project favicon resolution.
*/
export class ProjectFaviconResolver extends ServiceMap.Service<
ProjectFaviconResolver,
ProjectFaviconResolverShape
>()("t3/project/Services/ProjectFaviconResolver") {}
@@ -1,37 +0,0 @@
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ProjectSetupScriptRunnerResultNoScript {
readonly status: "no-script";
}
export interface ProjectSetupScriptRunnerResultStarted {
readonly status: "started";
readonly scriptId: string;
readonly scriptName: string;
readonly terminalId: string;
readonly cwd: string;
}
export type ProjectSetupScriptRunnerResult =
| ProjectSetupScriptRunnerResultNoScript
| ProjectSetupScriptRunnerResultStarted;
export interface ProjectSetupScriptRunnerInput {
readonly threadId: string;
readonly projectId?: string;
readonly projectCwd?: string;
readonly worktreePath: string;
readonly preferredTerminalId?: string;
}
export interface ProjectSetupScriptRunnerShape {
readonly runForThread: (
input: ProjectSetupScriptRunnerInput,
) => Effect.Effect<ProjectSetupScriptRunnerResult, Error>;
}
export class ProjectSetupScriptRunner extends ServiceMap.Service<
ProjectSetupScriptRunner,
ProjectSetupScriptRunnerShape
>()("t3/project/ProjectSetupScriptRunner") {}
+171
View File
@@ -0,0 +1,171 @@
import fs from "node:fs";
import http from "node:http";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
interface HttpResponse {
statusCode: number;
contentType: string | null;
body: string;
}
const tempDirs: string[] = [];
function makeTempDir(prefix: string): string {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix));
tempDirs.push(dir);
return dir;
}
async function withRouteServer(run: (baseUrl: string) => Promise<void>): Promise<void> {
const server = http.createServer((req, res) => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
if (tryHandleProjectFaviconRequest(url, res)) {
return;
}
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("Not Found");
});
await new Promise<void>((resolve, reject) => {
server.listen(0, "127.0.0.1", (error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
const address = server.address();
if (typeof address !== "object" || address === null) {
throw new Error("Expected server address to be an object");
}
const baseUrl = `http://127.0.0.1:${address.port}`;
try {
await run(baseUrl);
} finally {
await new Promise<void>((resolve, reject) => {
server.close((error?: Error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
}
async function request(baseUrl: string, pathname: string): Promise<HttpResponse> {
const response = await fetch(`${baseUrl}${pathname}`);
return {
statusCode: response.status,
contentType: response.headers.get("content-type"),
body: await response.text(),
};
}
describe("tryHandleProjectFaviconRequest", () => {
afterEach(() => {
for (const dir of tempDirs.splice(0, tempDirs.length)) {
fs.rmSync(dir, { recursive: true, force: true });
}
});
it("returns 400 when cwd is missing", async () => {
await withRouteServer(async (baseUrl) => {
const response = await request(baseUrl, "/api/project-favicon");
expect(response.statusCode).toBe(400);
expect(response.body).toBe("Missing cwd parameter");
});
});
it("serves a well-known favicon file from the project root", async () => {
const projectDir = makeTempDir("t3code-favicon-route-root-");
fs.writeFileSync(path.join(projectDir, "favicon.svg"), "<svg>favicon</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>favicon</svg>");
});
});
it("resolves icon href from source files when no well-known favicon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-source-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(
path.join(projectDir, "index.html"),
'<link rel="icon" href="/brand/logo.svg">',
);
fs.writeFileSync(iconPath, "<svg>brand</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand</svg>");
});
});
it("resolves icon link when href appears before rel in HTML", async () => {
const projectDir = makeTempDir("t3code-favicon-route-html-order-");
const iconPath = path.join(projectDir, "public", "brand", "logo.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.writeFileSync(
path.join(projectDir, "index.html"),
'<link href="/brand/logo.svg" rel="icon">',
);
fs.writeFileSync(iconPath, "<svg>brand-html-order</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand-html-order</svg>");
});
});
it("resolves object-style icon metadata when href appears before rel", async () => {
const projectDir = makeTempDir("t3code-favicon-route-obj-order-");
const iconPath = path.join(projectDir, "public", "brand", "obj.svg");
fs.mkdirSync(path.dirname(iconPath), { recursive: true });
fs.mkdirSync(path.join(projectDir, "src"), { recursive: true });
fs.writeFileSync(
path.join(projectDir, "src", "root.tsx"),
'const links = [{ href: "/brand/obj.svg", rel: "icon" }];',
"utf8",
);
fs.writeFileSync(iconPath, "<svg>brand-obj-order</svg>", "utf8");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toBe("<svg>brand-obj-order</svg>");
});
});
it("serves a fallback favicon when no icon exists", async () => {
const projectDir = makeTempDir("t3code-favicon-route-fallback-");
await withRouteServer(async (baseUrl) => {
const pathname = `/api/project-favicon?cwd=${encodeURIComponent(projectDir)}`;
const response = await request(baseUrl, pathname);
expect(response.statusCode).toBe(200);
expect(response.contentType).toContain("image/svg+xml");
expect(response.body).toContain('data-fallback="project-favicon"');
});
});
});
+171
View File
@@ -0,0 +1,171 @@
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
const FAVICON_MIME_TYPES: Record<string, string> = {
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ico": "image/x-icon",
};
const FALLBACK_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>`;
// Well-known favicon paths checked in order.
const FAVICON_CANDIDATES = [
"favicon.svg",
"favicon.ico",
"favicon.png",
"public/favicon.svg",
"public/favicon.ico",
"public/favicon.png",
"app/favicon.ico",
"app/favicon.png",
"app/icon.svg",
"app/icon.png",
"app/icon.ico",
"src/favicon.ico",
"src/favicon.svg",
"src/app/favicon.ico",
"src/app/icon.svg",
"src/app/icon.png",
"assets/icon.svg",
"assets/icon.png",
"assets/logo.svg",
"assets/logo.png",
];
// Files that may contain a <link rel="icon"> or icon metadata declaration.
const ICON_SOURCE_FILES = [
"index.html",
"public/index.html",
"app/routes/__root.tsx",
"src/routes/__root.tsx",
"app/root.tsx",
"src/root.tsx",
"src/index.html",
];
// Matches <link ...> tags or object-like icon metadata where rel/href can appear in any order.
const LINK_ICON_HTML_RE =
/<link\b(?=[^>]*\brel=["'](?:icon|shortcut icon)["'])(?=[^>]*\bhref=["']([^"'?]+))[^>]*>/i;
const LINK_ICON_OBJ_RE =
/(?=[^}]*\brel\s*:\s*["'](?:icon|shortcut icon)["'])(?=[^}]*\bhref\s*:\s*["']([^"'?]+))[^}]*/i;
function extractIconHref(source: string): string | null {
const htmlMatch = source.match(LINK_ICON_HTML_RE);
if (htmlMatch?.[1]) return htmlMatch[1];
const objMatch = source.match(LINK_ICON_OBJ_RE);
if (objMatch?.[1]) return objMatch[1];
return null;
}
function resolveIconHref(projectCwd: string, href: string): string[] {
const clean = href.replace(/^\//, "");
return [path.join(projectCwd, "public", clean), path.join(projectCwd, clean)];
}
function isPathWithinProject(projectCwd: string, candidatePath: string): boolean {
const relative = path.relative(path.resolve(projectCwd), path.resolve(candidatePath));
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
}
function serveFaviconFile(filePath: string, res: http.ServerResponse): void {
const ext = path.extname(filePath).toLowerCase();
const contentType = FAVICON_MIME_TYPES[ext] ?? "application/octet-stream";
fs.readFile(filePath, (readErr, data) => {
if (readErr) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("Read error");
return;
}
res.writeHead(200, {
"Content-Type": contentType,
"Cache-Control": "public, max-age=3600",
});
res.end(data);
});
}
function serveFallbackFavicon(res: http.ServerResponse): void {
res.writeHead(200, {
"Content-Type": "image/svg+xml",
"Cache-Control": "public, max-age=3600",
});
res.end(FALLBACK_FAVICON_SVG);
}
export function tryHandleProjectFaviconRequest(url: URL, res: http.ServerResponse): boolean {
if (url.pathname !== "/api/project-favicon") {
return false;
}
const projectCwd = url.searchParams.get("cwd");
if (!projectCwd) {
res.writeHead(400, { "Content-Type": "text/plain" });
res.end("Missing cwd parameter");
return true;
}
const tryResolvedPaths = (paths: string[], index: number, onExhausted: () => void): void => {
if (index >= paths.length) {
onExhausted();
return;
}
const candidate = paths[index]!;
if (!isPathWithinProject(projectCwd, candidate)) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryResolvedPaths(paths, index + 1, onExhausted);
return;
}
serveFaviconFile(candidate, res);
});
};
const trySourceFiles = (index: number): void => {
if (index >= ICON_SOURCE_FILES.length) {
serveFallbackFavicon(res);
return;
}
const sourceFile = path.join(projectCwd, ICON_SOURCE_FILES[index]!);
fs.readFile(sourceFile, "utf8", (err, content) => {
if (err) {
trySourceFiles(index + 1);
return;
}
const href = extractIconHref(content);
if (!href) {
trySourceFiles(index + 1);
return;
}
const candidates = resolveIconHref(projectCwd, href);
tryResolvedPaths(candidates, 0, () => trySourceFiles(index + 1));
});
};
const tryCandidates = (index: number): void => {
if (index >= FAVICON_CANDIDATES.length) {
trySourceFiles(0);
return;
}
const candidate = path.join(projectCwd, FAVICON_CANDIDATES[index]!);
if (!isPathWithinProject(projectCwd, candidate)) {
tryCandidates(index + 1);
return;
}
fs.stat(candidate, (err, stats) => {
if (err || !stats?.isFile()) {
tryCandidates(index + 1);
return;
}
serveFaviconFile(candidate, res);
});
};
tryCandidates(0);
return true;
}
@@ -208,9 +208,6 @@ async function readFirstPromptText(
if (next.done) {
return undefined;
}
if (typeof next.value.message.content === "string") {
return next.value.message.content;
}
const content = next.value.message.content[0];
if (!content || content.type !== "text") {
return undefined;
@@ -533,7 +533,7 @@ function buildUserMessage(input: {
parent_tool_use_id: null,
message: {
role: "user",
content: input.sdkContent as unknown as SDKUserMessage["message"]["content"],
content: input.sdkContent,
},
} as SDKUserMessage;
}
+181 -443
View File
@@ -1,15 +1,15 @@
import type {
ClaudeSettings,
ClaudeModelOptions,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -24,8 +24,7 @@ import {
} from "../providerSnapshot";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import { ServerSettingsService } from "../../serverSettings";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
const PROVIDER = "claudeAgent" as const;
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
@@ -44,8 +43,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -64,8 +63,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -97,9 +96,28 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
);
}
export function normalizeClaudeModelOptions(
model: string | null | undefined,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const caps = getClaudeModelCapabilities(model);
const effort = resolveEffort(caps, modelOptions?.effort);
const thinking =
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
const nextOptions: ClaudeModelOptions = {
...(thinking === false ? { thinking: false } : {}),
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
...(fastMode ? { fastMode: true } : {}),
...(contextWindow ? { contextWindow } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -111,7 +129,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
@@ -126,7 +144,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
@@ -147,372 +165,187 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
// ── Subscription type detection ─────────────────────────────────────
//
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
// This walker is a best-effort fallback for the `claude auth status`
// JSON output whose shape is not guaranteed.
/** Keys that directly hold a subscription/plan identifier. */
const SUBSCRIPTION_TYPE_KEYS = [
"subscriptionType",
"subscription_type",
"plan",
"tier",
"planType",
"plan_type",
] as const;
/** Keys whose value may be a nested object containing subscription info. */
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
const asNonEmptyString = (v: unknown): Option.Option<string> =>
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
? Option.some(v as Record<string, unknown>)
: Option.none();
/**
* Walk an unknown parsed JSON value looking for a subscription/plan
* identifier, returning the first match as an `Option`.
*/
function findSubscriptionType(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findSubscriptionType));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
),
);
}),
);
}
function findAuthMethod(value: unknown): Option.Option<string> {
if (globalThis.Array.isArray(value)) {
return Option.firstSomeOf(value.map(findAuthMethod));
}
return asRecord(value).pipe(
Option.flatMap((record) => {
const direct = Option.firstSomeOf(
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
);
if (Option.isSome(direct)) return direct;
return Option.firstSomeOf(
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
),
);
}),
);
}
/**
* Try to extract a subscription type from the `claude auth status` JSON
* output. This is a zero-cost operation on data we already have.
*/
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findSubscriptionType(parsed.success));
}
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
const parsed = decodeUnknownJson(result.stdout.trim());
if (Result.isFailure(parsed)) return undefined;
return Option.getOrUndefined(findAuthMethod(parsed.success));
}
// ── Dynamic model capability adjustment ─────────────────────────────
/** Subscription types where the 1M context window is included in the plan. */
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
"max",
"maxplan",
"max5",
"max20",
"enterprise",
"team",
]);
function toTitleCaseWords(value: string): string {
return value
.split(/[\s_-]+/g)
.filter(Boolean)
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
.join(" ");
}
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
switch (normalized) {
case "max":
case "maxplan":
case "max5":
case "max20":
return "Max";
case "enterprise":
return "Enterprise";
case "team":
return "Team";
case "pro":
return "Pro";
case "free":
return "Free";
default:
return toTitleCaseWords(subscriptionType!);
}
}
function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized) return undefined;
if (normalized === "apikey") return "apiKey";
return undefined;
}
function claudeAuthMetadata(input: {
readonly subscriptionType: string | undefined;
readonly authMethod: string | undefined;
}): { readonly type: string; readonly label: string } | undefined {
if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
return {
type: "apiKey",
label: "Claude API Key",
};
}
if (input.subscriptionType) {
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
return {
type: input.subscriptionType,
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
};
}
return undefined;
}
/**
* Adjust the built-in model list based on the user's detected subscription.
*
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
* - Other tiers (Pro, free, unknown): 200k context stays the default;
* 1M remains available as a manual option so users can still enable it.
*/
export function adjustModelsForSubscription(
baseModels: ReadonlyArray<ServerProviderModel>,
subscriptionType: string | undefined,
): ReadonlyArray<ServerProviderModel> {
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
return baseModels;
}
// Flip 1M to be the default for premium users
return baseModels.map((model) => {
const caps = model.capabilities;
if (!caps || caps.contextWindowOptions.length === 0) return model;
return {
...model,
capabilities: {
...caps,
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
opt.value === "1m"
? { value: opt.value, label: opt.label, isDefault: true as const }
: { value: opt.value, label: opt.label },
),
},
};
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
shell: process.platform === "win32",
});
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
}
// ── SDK capability probe ────────────────────────────────────────────
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
);
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Claude is disabled in T3 Code settings.",
},
});
}
/**
* Probe account information by spawning a lightweight Claude Agent SDK
* session and reading the initialization result.
*
* The prompt is never sent to the Anthropic API — we abort immediately
* after the local initialization phase completes. This gives us the
* user's subscription type without incurring any token cost.
*
* This is used as a fallback when `claude auth status` does not include
* subscription type information.
*/
const probeClaudeCapabilities = (binaryPath: string) => {
const abort = new AbortController();
return Effect.tryPromise(async () => {
const q = claudeQuery({
prompt: ".",
options: {
persistSession: false,
pathToClaudeCodeExecutable: binaryPath,
abortController: abort,
maxTurns: 0,
settingSources: [],
allowedTools: [],
stderr: () => {},
},
});
const init = await q.initializationResult();
return { subscriptionType: init.account?.subscriptionType };
}).pipe(
Effect.ensuring(
Effect.sync(() => {
if (!abort.signal.aborted) abort.abort();
}),
),
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
};
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const runClaudeCommand = Effect.fn("runClaudeCommand")(function* (args: ReadonlyArray<string>) {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
shell: process.platform === "win32",
});
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, claudeSettings.customModels);
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Claude is disabled in T3 Code settings.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
}
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
@@ -521,99 +354,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
}
// ── Auth check + subscription detection ────────────────────────────
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
// Determine subscription type from multiple sources (cheapest first):
// 1. `claude auth status` JSON output (may or may not contain it)
// 2. Cached SDK probe (spawns a Claude process on miss, reads
// `initializationResult()` for account metadata, then aborts
// immediately — no API tokens are consumed)
let subscriptionType: string | undefined;
let authMethod: string | undefined;
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
}
if (!subscriptionType && resolveSubscriptionType) {
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
}
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
// ── Handle auth results (same logic as before, adjusted models) ──
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authMetadata ? authMetadata : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
},
);
export const ClaudeProviderLive = Layer.effect(
ClaudeProvider,
@@ -621,16 +368,7 @@ export const ClaudeProviderLive = Layer.effect(
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const subscriptionProbeCache = yield* Cache.make({
capacity: 1,
timeToLive: Duration.minutes(5),
lookup: (binaryPath: string) =>
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
});
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
Cache.get(subscriptionProbeCache, binaryPath),
).pipe(
const checkProvider = checkClaudeProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
@@ -508,42 +508,6 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
}),
);
it.effect("maps fatal websocket stderr notifications to runtime.error", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-process-stderr-websocket"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
createdAt: new Date().toISOString(),
method: "process/stderr",
turnId: asTurnId("turn-1"),
message:
"2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses",
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "runtime.error");
if (firstEvent.value.type !== "runtime.error") {
return;
}
assert.equal(firstEvent.value.turnId, "turn-1");
assert.equal(firstEvent.value.payload.class, "provider_error");
assert.equal(
firstEvent.value.payload.message,
"2026-03-31T18:14:06.833399Z ERROR codex_api::endpoint::responses_websocket: failed to connect to websocket: HTTP error: 503 Service Unavailable, url: wss://chatgpt.com/backend-api/codex/responses",
);
}),
);
it.effect("preserves request type when mapping serverRequest/resolved", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
@@ -112,13 +112,6 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
const FATAL_CODEX_STDERR_SNIPPETS = ["failed to connect to websocket"];
function isFatalCodexProcessStderrMessage(message: string): boolean {
const normalized = message.toLowerCase();
return FATAL_CODEX_STDERR_SNIPPETS.some((snippet) => normalized.includes(snippet));
}
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
const usage = asObject(value);
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
@@ -1276,27 +1269,15 @@ function mapToRuntimeEvents(
}
if (event.method === "process/stderr") {
const message = event.message ?? "Codex process stderr";
const isFatal = isFatalCodexProcessStderrMessage(message);
return [
isFatal
? {
type: "runtime.error",
...runtimeEventBase(event, canonicalThreadId),
payload: {
message,
class: "provider_error" as const,
...(event.payload !== undefined ? { detail: event.payload } : {}),
},
}
: {
type: "runtime.warning",
...runtimeEventBase(event, canonicalThreadId),
payload: {
message,
...(event.payload !== undefined ? { detail: event.payload } : {}),
},
},
{
type: "runtime.warning",
...runtimeEventBase(event, canonicalThreadId),
payload: {
message: event.message ?? "Codex process stderr",
...(event.payload !== undefined ? { detail: event.payload } : {}),
},
},
];
}
+217 -257
View File
@@ -1,25 +1,16 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexModelOptions,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import {
Cache,
Duration,
Effect,
Equal,
FileSystem,
Layer,
Option,
Path,
Result,
Stream,
} from "effect";
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -38,16 +29,8 @@ import {
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion";
import {
adjustCodexModelsForAccount,
codexAuthSubLabel,
codexAuthSubType,
type CodexAccountSnapshot,
} from "../codexAccount";
import { probeCodexAccount } from "../codexAppServer";
import { CodexProvider } from "../Services/CodexProvider";
import { ServerSettingsService } from "../../serverSettings";
import { ServerSettingsError } from "@t3tools/contracts";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
const PROVIDER = "codex" as const;
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
@@ -169,9 +152,25 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
);
}
export function normalizeCodexModelOptions(
model: string | null | undefined,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const caps = getCodexModelCapabilities(model);
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly auth: Pick<ServerProviderAuth, "status">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -183,7 +182,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
@@ -197,7 +196,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
@@ -218,31 +217,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
@@ -291,118 +290,195 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
Effect.orElseSucceed(() => false),
);
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
const probeCodexCapabilities = (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) =>
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
Effect.result,
Effect.map((result) => {
if (Result.isFailure(result)) return undefined;
return Option.isSome(result.success) ? result.success.value : undefined;
}),
);
const runCodexCommand = Effect.fn("runCodexCommand")(function* (args: ReadonlyArray<string>) {
const settingsService = yield* ServerSettingsService;
const codexSettings = yield* settingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
);
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
shell: process.platform === "win32",
env: {
...process.env,
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const settingsService = yield* ServerSettingsService;
const codexSettings = yield* settingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
);
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
shell: process.platform === "win32",
env: {
...process.env,
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
});
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
resolveAccount?: (input: {
readonly binaryPath: string;
readonly homePath?: string;
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "unknown" },
message: "Codex is disabled in T3 Code settings.",
},
});
}
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Codex is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
auth: { status: "unknown" },
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "unknown" },
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
authStatus: "unknown",
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
@@ -411,116 +487,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
auth: { status: "unknown" },
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
const account = resolveAccount
? yield* resolveAccount({
binaryPath: codexSettings.binaryPath,
homePath: codexSettings.homePath,
})
: undefined;
const resolvedModels = adjustCodexModelsForAccount(models, account);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
auth: { status: "unknown" },
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
const authType = codexAuthSubType(account);
const authLabel = codexAuthSubLabel(account);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models: resolvedModels,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
auth: {
...parsed.auth,
...(authType ? { type: authType } : {}),
...(authLabel ? { label: authLabel } : {}),
},
...(parsed.message ? { message: parsed.message } : {}),
},
});
});
},
);
export const CodexProviderLive = Layer.effect(
CodexProvider,
@@ -529,21 +502,8 @@ export const CodexProviderLive = Layer.effect(
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const accountProbeCache = yield* Cache.make({
capacity: 4,
timeToLive: Duration.minutes(5),
lookup: (key: string) => {
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
return probeCodexCapabilities({
binaryPath,
...(homePath ? { homePath } : {}),
});
},
});
const checkProvider = checkCodexProviderStatus((input) =>
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
).pipe(
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -74,180 +74,184 @@ function resolveStreamLabel(stream: EventNdjsonStream): string {
}
}
const toLogMessage = Effect.fn("toLogMessage")(function* (
event: unknown,
): Effect.fn.Return<string | undefined> {
const serialized = yield* Effect.sync(() => {
try {
return { ok: true as const, value: JSON.stringify(event) };
} catch (error) {
return { ok: false as const, error };
}
});
if (!serialized.ok) {
yield* logWarning("failed to serialize provider event log record", {
error: serialized.error,
function toLogMessage(event: unknown): Effect.Effect<string | undefined> {
return Effect.gen(function* () {
const serialized = yield* Effect.sync(() => {
try {
return { ok: true as const, value: JSON.stringify(event) };
} catch (error) {
return { ok: false as const, error };
}
});
return undefined;
}
if (typeof serialized.value !== "string") {
return undefined;
}
if (!serialized.ok) {
yield* logWarning("failed to serialize provider event log record", {
error: serialized.error,
});
return undefined;
}
return serialized.value;
});
if (typeof serialized.value !== "string") {
return undefined;
}
const makeThreadWriter = Effect.fn("makeThreadWriter")(function* (input: {
return serialized.value;
});
}
function makeThreadWriter(input: {
readonly filePath: string;
readonly maxBytes: number;
readonly maxFiles: number;
readonly batchWindowMs: number;
readonly streamLabel: string;
}): Effect.fn.Return<ThreadWriter | undefined> {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
};
} catch (error) {
return { ok: false as const, error };
}
});
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
});
return undefined;
}
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: Effect.fn("makeThreadWriter.flush")(function* (messages) {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
});
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
});
}): Effect.Effect<ThreadWriter | undefined> {
return Effect.gen(function* () {
const sinkResult = yield* Effect.sync(() => {
try {
return {
ok: true as const,
sink: new RotatingFileSink({
filePath: input.filePath,
maxBytes: input.maxBytes,
maxFiles: input.maxFiles,
throwOnError: true,
}),
};
} catch (error) {
return { ok: false as const, error };
}
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
});
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
if (!sinkResult.ok) {
yield* logWarning("failed to initialize provider thread log file", {
filePath: input.filePath,
error: sinkResult.error,
});
return undefined;
}
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
});
const sink = sinkResult.sink;
const scope = yield* Scope.make();
const lineLogger = makeLineLogger(input.streamLabel);
const batchedLogger = yield* Logger.batched(lineLogger, {
window: input.batchWindowMs,
flush: (messages) =>
Effect.gen(function* () {
const flushResult = yield* Effect.sync(() => {
try {
for (const message of messages) {
sink.write(message);
}
return { ok: true as const };
} catch (error) {
return { ok: false as const, error };
}
});
export const makeEventNdjsonLogger = Effect.fn("makeEventNdjsonLogger")(function* (
if (!flushResult.ok) {
yield* logWarning("provider event log batch flush failed", {
filePath: input.filePath,
error: flushResult.error,
});
}
}),
}).pipe(Effect.provideService(Scope.Scope, scope));
const loggerLayer = Logger.layer([batchedLogger], { mergeWithExisting: false });
return {
writeMessage(message: string) {
return Effect.log(message).pipe(Effect.provide(loggerLayer));
},
close() {
return Scope.close(scope, Exit.void);
},
} satisfies ThreadWriter;
});
}
export function makeEventNdjsonLogger(
filePath: string,
options: EventNdjsonLoggerOptions,
): Effect.fn.Return<EventNdjsonLogger | undefined> {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
): Effect.Effect<EventNdjsonLogger | undefined> {
return Effect.gen(function* () {
const maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
const maxFiles = options.maxFiles ?? DEFAULT_MAX_FILES;
const batchWindowMs = options.batchWindowMs ?? DEFAULT_BATCH_WINDOW_MS;
const streamLabel = resolveStreamLabel(options.stream);
const directoryReady = yield* Effect.sync(() => {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
const directoryReady = yield* Effect.sync(() => {
try {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
return true;
} catch (error) {
return { ok: false as const, error };
}
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
filePath,
error: directoryReady.error,
});
return undefined;
}
});
if (directoryReady !== true) {
yield* logWarning("failed to create provider event log directory", {
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const resolveThreadWriter = (threadSegment: string): Effect.Effect<ThreadWriter | undefined> =>
Effect.gen(function* () {
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
threadWriters.set(threadSegment, writer);
return writer;
});
return {
filePath,
error: directoryReady.error,
});
return undefined;
}
write(event: unknown, threadId: ThreadId | null) {
return Effect.gen(function* () {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const threadWriters = new Map<string, ThreadWriter>();
const failedSegments = new Set<string>();
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
const resolveThreadWriter = Effect.fn("resolveThreadWriter")(function* (
threadSegment: string,
): Effect.fn.Return<ThreadWriter | undefined> {
if (failedSegments.has(threadSegment)) {
return undefined;
}
const existing = threadWriters.get(threadSegment);
if (existing) {
return existing;
}
const writer = yield* makeThreadWriter({
filePath: path.join(path.dirname(filePath), `${threadSegment}.log`),
maxBytes,
maxFiles,
batchWindowMs,
streamLabel,
});
if (!writer) {
failedSegments.add(threadSegment);
return undefined;
}
threadWriters.set(threadSegment, writer);
return writer;
yield* writer.writeMessage(message);
});
},
close() {
return Effect.gen(function* () {
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
});
},
} satisfies EventNdjsonLogger;
});
const write = Effect.fn("write")(function* (event: unknown, threadId: ThreadId | null) {
const threadSegment = resolveThreadSegment(threadId);
const message = yield* toLogMessage(event);
if (!message) {
return;
}
const writer = yield* resolveThreadWriter(threadSegment);
if (!writer) {
return;
}
yield* writer.writeMessage(message);
});
const close = Effect.fn("close")(function* () {
for (const writer of threadWriters.values()) {
yield* writer.close();
}
threadWriters.clear();
});
return {
filePath,
write,
close,
} satisfies EventNdjsonLogger;
});
}
@@ -22,31 +22,30 @@ export interface ProviderAdapterRegistryLiveOptions {
readonly adapters?: ReadonlyArray<ProviderAdapterShape<ProviderAdapterError>>;
}
const makeProviderAdapterRegistry = Effect.fn("makeProviderAdapterRegistry")(function* (
options?: ProviderAdapterRegistryLiveOptions,
) {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const makeProviderAdapterRegistry = (options?: ProviderAdapterRegistryLiveOptions) =>
Effect.gen(function* () {
const adapters =
options?.adapters !== undefined
? options.adapters
: [yield* CodexAdapter, yield* ClaudeAdapter];
const byProvider = new Map(adapters.map((adapter) => [adapter.provider, adapter]));
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
const adapter = byProvider.get(provider);
if (!adapter) {
return Effect.fail(new ProviderUnsupportedError({ provider }));
}
return Effect.succeed(adapter);
};
const getByProvider: ProviderAdapterRegistryShape["getByProvider"] = (provider) => {
const adapter = byProvider.get(provider);
if (!adapter) {
return Effect.fail(new ProviderUnsupportedError({ provider }));
}
return Effect.succeed(adapter);
};
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
Effect.sync(() => Array.from(byProvider.keys()));
const listProviders: ProviderAdapterRegistryShape["listProviders"] = () =>
Effect.sync(() => Array.from(byProvider.keys()));
return {
getByProvider,
listProviders,
} satisfies ProviderAdapterRegistryShape;
});
return {
getByProvider,
listProviders,
} satisfies ProviderAdapterRegistryShape;
});
export const ProviderAdapterRegistryLive = Layer.effect(
ProviderAdapterRegistry,
Loaded 100 of 280 files, more files were not shown because too many files have changed in this diff. Show more