Compare commits

..
Author SHA1 Message Date
Julius Marmingeandcodex e6d856b93e Add subagent work units across providers
Co-authored-by: codex <[email protected]>
2026-03-18 15:54:55 -07:00
Julius Marminge ef843d400e maybe fix codex subturns 2026-03-18 15:47:34 -07:00
Julius Marminge 654ca0da91 Backfill missing app settings defaults during decode
- add decoding defaults in `AppSettingsSchema` so older persisted settings load safely
- export shared `Schema.Literals` types for `EnvMode` and `TimestampFormat`
- add a regression test covering pre-new-key settings hydration
2026-03-18 14:17:23 -07:00
Julius Marminge aa66e08034 update adapter 2026-03-18 13:26:12 -07:00
Julius Marmingeandcodex 268d4f7cf8 Merge main and use source proposed plans in the sidebar
Co-authored-by: codex <[email protected]>
2026-03-18 13:25:17 -07:00
Julius Marminge 321251907a refactor storage 2026-03-18 11:00:07 -07:00
Julius Marminge d5c86c9af6 Merge branch 'main' into split-stack/claude-sibling 2026-03-18 10:18:13 -07:00
Julius Marminge a75a9b427f Split Codex and Claude traits handling by model capabilities
- Add dedicated Claude traits picker with model-aware effort, thinking, and fast mode controls
- Treat Claude Ultrathink as a prompt keyword instead of session effort
- Normalize provider model options in composer flow and adapter, with tests for unsupported effort/thinking cases
2026-03-17 16:56:59 -07:00
Julius Marminge f98679d217 Add Claude fast mode support across adapter and composer controls
- support `claudeAgent.fastMode` in shared/contracts, provider dispatch, and Claude adapter SDK settings
- gate fast mode to supported Claude models and restart/forward options in orchestration
- unify draft/UI fast mode state (not Codex-only) and add browser/server tests plus SDK probe
2026-03-17 14:36:35 -07:00
Julius Marminge 5c9cfcd4c3 Remove Ultrathink pill from composer header
- keep Ultrathink frame styling without extra wrapper padding toggles
- drop the inline Ultrathink badge row in ChatView
- clean up stray whitespace in ProviderService test
2026-03-17 14:11:26 -07:00
JustYanniccandClaude Opus 4.6 e6254a8451 feat: claude effort controls, ultrathink UI, and adapter robustness (#1146)
Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
2026-03-17 13:23:07 -07:00
Julius Marminge b04132d8c8 Use provider default model in orchestration integration seed
- derive `defaultModel` from `DEFAULT_MODEL_BY_PROVIDER` using harness provider
- replace hardcoded `gpt-5-codex` in seeded project and thread setup
2026-03-16 17:36:56 -07:00
Julius Marminge b577cb5326 Fix locked-thread model selection and provider fallback
- Use thread provider as the preferred provider during command handling
- Update `ProviderModelPicker` to show direct model choices when provider is locked
- Add browser tests for locked/unlocked picker behavior and widen browser test glob
2026-03-16 17:26:50 -07:00
Julius Marminge fc9660f238 Enforce provider-model consistency for thread turn starts
- Reject turn starts that request a provider switch from the thread-bound provider
- Reject models that do not belong to the thread provider and log start failures
- Add shared `inferProviderForModel` helper and tests; reuse it in web store inference
2026-03-16 17:09:38 -07:00
Julius Marminge b403ca3183 dont provide generated orchestration ids to native providerRefs 2026-03-16 16:09:50 -07:00
Julius Marminge f34dd0a91f Schema.is 2026-03-16 15:48:28 -07:00
Julius Marminge 33791cdfe5 align branding guide lines 2026-03-16 15:41:12 -07:00
Julius Marminge fdcb05d3f6 replace ad-hoc union for contract type 2026-03-16 12:16:24 -07:00
Julius Marmingeandcodex 2121682546 Improve Claude adapter tool streaming and health checks
- Map Claude reasoning deltas, streamed tool input JSON, and tool results into runtime item/content events
- Classify Agent/read-only Claude tools for correct approval request types
- Add Claude CLI provider health checks and auth-status parsing coverage

Co-authored-by: codex <[email protected]>
2026-03-16 12:14:27 -07:00
Julius Marminge d2b00e6550 Show Claude Code in provider picker and add Cursor placeholder
- Include Claude Code in available provider options in the picker
- Add Cursor as a disabled placeholder provider with icon mapping
- Update session-logic tests to assert provider availability and ordering
2026-03-16 11:11:57 -07:00
Julius Marminge e0facb03bd fix circular import 2026-03-16 11:06:26 -07:00
Julius Marminge 73152abe81 fmt 2026-03-16 11:03:31 -07:00
Julius Marminge c5bfff1583 unify start option union 2026-03-16 10:41:05 -07:00
Julius Marminge 040011dbc7 Remove Cursor provider support across server and web
- drop `cursor` from provider/model contracts and runtime validation
- remove Cursor-specific UI options, settings, and model normalization paths
- update server/web tests and fixtures to cover Codex + Claude Code only
2026-03-16 10:35:53 -07:00
Julius Marminge 858116d836 fmt 2026-03-16 10:28:36 -07:00
Julius Marminge ff34d2c708 lock 2026-03-16 10:28:24 -07:00
Julius Marmingeandcodex 99cd1c560e Fix post-rebase provider integration
Co-authored-by: codex <[email protected]>
2026-03-16 10:24:55 -07:00
Julius Marmingeandcodex 01f01c5e6b build: sync Claude SDK lockfile on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:18:03 -07:00
Julius Marmingeandcodex de7cfba261 split: restore Claude SDK manifest and plan doc
Co-authored-by: codex <[email protected]>
2026-03-16 10:17:45 -07:00
Julius Marmingeandcodex 1da30f776e split: restore Claude provider surface on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:17:45 -07:00
Julius Marmingeandcodex 11aca1fcc6 model: restore Claude catalogs on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:12:33 -07:00
Julius Marmingeandcodex 95c50053bc contracts: restore Claude schemas on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:09:06 -07:00
Julius Marmingeandcodex da9cbcc98c test: restore Claude coverage on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:08:09 -07:00
Julius Marmingeandcodex b9ea1487b3 Restore Claude adapter on sibling stack
Co-authored-by: codex <[email protected]>
2026-03-16 10:07:39 -07:00
176 changed files with 8870 additions and 17435 deletions

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
- `bun run dev:web` — Starts just the Vite dev server for the web app.
- Dev commands default `T3CODE_STATE_DIR` to `~/.t3/dev` to keep dev state isolated from desktop/prod state.
- Override server CLI-equivalent flags from root dev commands with `--`, for example:
`bun run dev -- --base-dir ~/.t3-2`
`bun run dev -- --state-dir ~/.t3/another-dev-state`
- `bun run start` — Runs the production server (serves built web app as static files).
- `bun run build` — Builds contracts, web app, and server through Turbo.
- `bun run typecheck` — Strict TypeScript checks for all packages.
+11 -64
View File
@@ -24,32 +24,32 @@ jobs:
{
name: "size:XS",
color: "0e8a16",
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
description: "0-9 changed lines (additions + deletions).",
},
{
name: "size:S",
color: "5ebd3e",
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
description: "10-29 changed lines (additions + deletions).",
},
{
name: "size:M",
color: "fbca04",
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
description: "30-99 changed lines (additions + deletions).",
},
{
name: "size:L",
color: "fe7d37",
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
description: "100-499 changed lines (additions + deletions).",
},
{
name: "size:XL",
color: "d93f0b",
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
description: "500-999 changed lines (additions + deletions).",
},
{
name: "size:XXL",
color: "b60205",
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
description: "1,000+ changed lines (additions + deletions).",
},
];
@@ -131,18 +131,12 @@ jobs:
with:
script: |
const issueNumber = context.payload.pull_request.number;
const additions = context.payload.pull_request.additions ?? 0;
const deletions = context.payload.pull_request.deletions ?? 0;
const changedLines = additions + deletions;
const managedLabels = JSON.parse(process.env.PR_SIZE_LABELS_JSON ?? "[]");
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
// Keep this aligned with the repo's test entrypoints and test-only support files.
const testFilePatterns = [
/(^|\/)__tests__(\/|$)/,
/(^|\/)tests?(\/|$)/,
/^apps\/server\/integration\//,
/\.(test|spec|browser|integration)\.[^.\/]+$/,
];
const isTestFile = (filename) =>
testFilePatterns.some((pattern) => pattern.test(filename));
const managedLabelNames = new Set(managedLabels.map((label) => label.name));
const resolveSizeLabel = (totalChangedLines) => {
if (totalChangedLines < 10) {
@@ -168,42 +162,6 @@ jobs:
return "size:XXL";
};
const files = await github.paginate(
github.rest.pulls.listFiles,
{
owner: context.repo.owner,
repo: context.repo.repo,
pull_number: issueNumber,
per_page: 100,
},
(response) => response.data,
);
if (files.length >= 3000) {
core.warning(
"The GitHub pull request files API may truncate results at 3,000 files; PR size may be undercounted.",
);
}
let testChangedLines = 0;
let nonTestChangedLines = 0;
for (const file of files) {
const changedLinesForFile = (file.additions ?? 0) + (file.deletions ?? 0);
if (changedLinesForFile === 0) {
continue;
}
if (isTestFile(file.filename)) {
testChangedLines += changedLinesForFile;
continue;
}
nonTestChangedLines += changedLinesForFile;
}
const changedLines = nonTestChangedLines === 0 ? testChangedLines : nonTestChangedLines;
const nextLabelName = resolveSizeLabel(changedLines);
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
@@ -241,15 +199,4 @@ jobs:
});
}
const classification =
nonTestChangedLines === 0
? testChangedLines > 0
? "test-only PR"
: "no line changes"
: testChangedLines > 0
? "test lines excluded"
: "all non-test changes";
core.info(
`PR #${issueNumber}: ${nonTestChangedLines} non-test lines, ${testChangedLines} test lines, ${changedLines} effective lines -> ${nextLabelName} (${classification})`,
);
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
+1 -1
View File
@@ -312,7 +312,7 @@ jobs:
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
app-id: ${{ vars.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
+1 -3
View File
@@ -17,6 +17,4 @@ release/
apps/web/.playwright
apps/web/playwright-report
apps/web/src/components/__screenshots__
.vitest-*
__screenshots__/
.tanstack
.vitest-*
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+9 -12
View File
@@ -6,24 +6,21 @@ Use this when you want to open T3 Code from another device (phone, tablet, anoth
The T3 Code CLI accepts the following configuration options, available either as CLI flags or environment variables:
| CLI flag | Env var | Notes |
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------ |
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--base-dir <path>` | `T3CODE_HOME` | Base directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. Use this for standard CLI and remote-server flows. |
| `--bootstrap-fd <fd>` | `T3CODE_BOOTSTRAP_FD` | Read a one-shot bootstrap envelope from an inherited file descriptor during startup. |
| CLI flag | Env var | Notes |
| ----------------------- | --------------------- | ---------------------------------- |
| `--mode <web\|desktop>` | `T3CODE_MODE` | Runtime mode. |
| `--port <number>` | `T3CODE_PORT` | HTTP/WebSocket port. |
| `--host <address>` | `T3CODE_HOST` | Bind interface/address. |
| `--state-dir <path>` | `T3CODE_STATE_DIR` | State directory. |
| `--dev-url <url>` | `VITE_DEV_SERVER_URL` | Dev web URL redirect/proxy target. |
| `--no-browser` | `T3CODE_NO_BROWSER` | Disable auto-open browser. |
| `--auth-token <token>` | `T3CODE_AUTH_TOKEN` | WebSocket auth token. |
> TIP: Use the `--help` flag to see all available options and their descriptions.
## Security First
- Always set `--auth-token` before exposing the server outside localhost.
- When you control the process launcher, prefer sending the auth token in a JSON envelope via `--bootstrap-fd <fd>`.
With `--bootstrap-fd <fd>`, the launcher starts the server first, then sends a one-shot JSON envelope over the inherited file descriptor. This allows the auth token to be delivered without putting it in process environment or command line arguments.
- Treat the token like a password.
- Prefer binding to trusted interfaces (LAN IP or Tailnet IP) instead of opening all interfaces unless needed.
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.14",
"version": "0.0.10",
"private": true,
"main": "dist-electron/main.js",
"scripts": {
+19 -44
View File
@@ -56,9 +56,8 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
const BASE_DIR = process.env.T3CODE_HOME?.trim() || Path.join(OS.homedir(), ".t3");
const STATE_DIR = Path.join(BASE_DIR, "userdata");
const STATE_DIR =
process.env.T3CODE_STATE_DIR?.trim() || Path.join(OS.homedir(), ".t3", "userdata");
const DESKTOP_SCHEME = "t3";
const ROOT_DIR = Path.resolve(__dirname, "../../..");
const isDevelopment = Boolean(process.env.VITE_DEV_SERVER_URL);
@@ -114,17 +113,6 @@ function sanitizeLogValue(value: string): string {
return value.replace(/\s+/g, " ").trim();
}
function backendChildEnv(): NodeJS.ProcessEnv {
const env = { ...process.env };
delete env.T3CODE_PORT;
delete env.T3CODE_AUTH_TOKEN;
delete env.T3CODE_MODE;
delete env.T3CODE_NO_BROWSER;
delete env.T3CODE_HOST;
delete env.T3CODE_DESKTOP_WS_URL;
return env;
}
function writeDesktopLogHeader(message: string): void {
if (!desktopLogSink) return;
desktopLogSink.write(`[${logTimestamp()}] [${logScope("desktop")}] ${message}\n`);
@@ -930,6 +918,17 @@ function configureAutoUpdater(): void {
}, AUTO_UPDATE_POLL_INTERVAL_MS);
updatePollTimer.unref();
}
function backendEnv(): NodeJS.ProcessEnv {
return {
...process.env,
T3CODE_MODE: "desktop",
T3CODE_NO_BROWSER: "1",
T3CODE_PORT: String(backendPort),
T3CODE_STATE_DIR: STATE_DIR,
T3CODE_AUTH_TOKEN: backendAuthToken,
};
}
function scheduleBackendRestart(reason: string): void {
if (isQuitting || restartTimer) return;
@@ -953,35 +952,16 @@ function startBackend(): void {
}
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
cwd: resolveBackendCwd(),
// In Electron main, process.execPath points to the Electron binary.
// Run the child in Node mode so this backend process does not become a GUI app instance.
env: {
...backendChildEnv(),
...backendEnv(),
ELECTRON_RUN_AS_NODE: "1",
},
stdio: captureBackendLogs
? ["ignore", "pipe", "pipe", "pipe"]
: ["ignore", "inherit", "inherit", "pipe"],
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
});
const bootstrapStream = child.stdio[3];
if (bootstrapStream && "write" in bootstrapStream) {
bootstrapStream.write(
`${JSON.stringify({
mode: "desktop",
noBrowser: true,
port: backendPort,
t3Home: BASE_DIR,
authToken: backendAuthToken,
})}\n`,
);
bootstrapStream.end();
} else {
child.kill("SIGTERM");
scheduleBackendRestart("missing desktop bootstrap pipe");
return;
}
backendProcess = child;
let backendSessionClosed = false;
const closeBackendSession = (details: string) => {
@@ -1092,11 +1072,6 @@ async function stopBackendAndWaitForExit(timeoutMs = 5_000): Promise<void> {
}
function registerIpcHandlers(): void {
ipcMain.removeAllListeners(GET_WS_URL_CHANNEL);
ipcMain.on(GET_WS_URL_CHANNEL, (event) => {
event.returnValue = backendWsUrl;
});
ipcMain.removeHandler(PICK_FOLDER_CHANNEL);
ipcMain.handle(PICK_FOLDER_CHANNEL, async () => {
const owner = BrowserWindow.getFocusedWindow() ?? mainWindow;
@@ -1345,9 +1320,9 @@ async function bootstrap(): Promise<void> {
);
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
backendAuthToken = Crypto.randomBytes(24).toString("hex");
const baseUrl = `ws://127.0.0.1:${backendPort}`;
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
registerIpcHandlers();
writeDesktopLogHeader("bootstrap ipc handlers registered");
+2 -5
View File
@@ -11,13 +11,10 @@ const UPDATE_STATE_CHANNEL = "desktop:update-state";
const UPDATE_GET_STATE_CHANNEL = "desktop:update-get-state";
const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
const wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
contextBridge.exposeInMainWorld("desktopBridge", {
getWsUrl: () => {
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
return typeof result === "string" ? result : null;
},
getWsUrl: () => wsUrl,
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
@@ -1,3 +1,6 @@
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
@@ -10,11 +13,9 @@ import {
import {
Effect,
Exit,
FileSystem,
Layer,
ManagedRuntime,
Option,
Path,
Ref,
Schedule,
Schema,
@@ -24,7 +25,6 @@ import {
import { CheckpointStoreLive } from "../src/checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../src/checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../src/git/Layers/GitCore.ts";
import { GitCore, type GitCoreShape } from "../src/git/Services/GitCore.ts";
import { TextGeneration, type TextGenerationShape } from "../src/git/Services/TextGeneration.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../src/persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -66,8 +66,7 @@ import {
makeTestProviderAdapterHarness,
type TestProviderAdapterHarness,
} from "./TestProviderAdapter.integration.ts";
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { ServerConfig } from "../src/config.ts";
function runGit(cwd: string, args: ReadonlyArray<string>) {
return execFileSync("git", args, {
@@ -77,16 +76,14 @@ function runGit(cwd: string, args: ReadonlyArray<string>) {
});
}
const initializeGitWorkspace = Effect.fn(function* (cwd: string) {
function initializeGitWorkspace(cwd: string) {
runGit(cwd, ["init", "--initial-branch=main"]);
runGit(cwd, ["config", "user.email", "[email protected]"]);
runGit(cwd, ["config", "user.name", "Test User"]);
const fileSystem = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
yield* fileSystem.writeFileString(join(cwd, "README.md"), "v1\n");
fs.writeFileSync(path.join(cwd, "README.md"), "v1\n", "utf8");
runGit(cwd, ["add", "."]);
runGit(cwd, ["commit", "-m", "Initial"]);
});
}
export function gitRefExists(cwd: string, ref: string): boolean {
try {
@@ -217,9 +214,7 @@ export const makeOrchestrationIntegrationHarness = (
options?: MakeOrchestrationIntegrationHarnessOptions,
) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const fileSystem = yield* FileSystem.FileSystem;
const sleep = (ms: number) => Effect.sleep(ms);
const provider = options?.provider ?? "codex";
const useRealCodex = options?.realCodex === true;
const adapterHarness = useRealCodex
@@ -236,16 +231,13 @@ export const makeOrchestrationIntegrationHarness = (
listProviders: () => Effect.succeed([adapterHarness.provider]),
} as typeof ProviderAdapterRegistry.Service)
: null;
const rootDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-orchestration-integration-",
});
const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-orchestration-integration-"));
const workspaceDir = path.join(rootDir, "workspace");
const { stateDir, dbPath } = yield* deriveServerPaths(rootDir, undefined).pipe(
Effect.provideService(Path.Path, path),
);
yield* fileSystem.makeDirectory(workspaceDir, { recursive: true });
yield* fileSystem.makeDirectory(stateDir, { recursive: true });
yield* initializeGitWorkspace(workspaceDir);
const stateDir = path.join(rootDir, "state");
const dbPath = path.join(stateDir, "state.sqlite");
fs.mkdirSync(workspaceDir, { recursive: true });
fs.mkdirSync(stateDir, { recursive: true });
initializeGitWorkspace(workspaceDir);
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const orchestrationLayer = OrchestrationEngineLive.pipe(
@@ -270,7 +262,7 @@ export const makeOrchestrationIntegrationHarness = (
}),
).pipe(
Layer.provide(makeCodexAdapterLive()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(providerSessionDirectoryLayer),
);
@@ -286,20 +278,17 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provide(AnalyticsService.layerTest),
);
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
ProjectionCheckpointRepositoryLive,
ProjectionPendingApprovalRepositoryLive,
checkpointStoreLayer,
CheckpointStoreLive,
providerLayer,
RuntimeReceiptBusLive,
);
const serverSettingsLayer = ServerSettingsService.layerTest();
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(serverSettingsLayer),
);
const gitCoreLayer = Layer.succeed(GitCore, {
renameBranch: (input: Parameters<GitCoreShape["renameBranch"]>[0]) =>
@@ -312,7 +301,6 @@ export const makeOrchestrationIntegrationHarness = (
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
Layer.provideMerge(serverSettingsLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
@@ -324,7 +312,7 @@ export const makeOrchestrationIntegrationHarness = (
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, stateDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -364,7 +352,7 @@ export const makeOrchestrationIntegrationHarness = (
yield* Stream.runForEach(runtimeReceiptBus.stream, (receipt) =>
Ref.update(receiptHistory, (history) => [...history, receipt]).pipe(Effect.asVoid),
).pipe(Effect.forkIn(scope));
yield* Effect.sleep(10);
yield* sleep(10);
const waitForThread: OrchestrationIntegrationHarness["waitForThread"] = (
threadId,
@@ -481,7 +469,13 @@ export const makeOrchestrationIntegrationHarness = (
}
});
yield* shutdown;
yield* shutdown.pipe(
Effect.ensuring(
Effect.sync(() => {
fs.rmSync(rootDir, { recursive: true, force: true });
}),
),
);
});
return {
@@ -11,7 +11,6 @@ import {
ProjectId,
ProviderKind,
ThreadId,
ModelSelection,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Option, Schema } from "effect";
@@ -28,7 +27,6 @@ import type {
CheckpointDiffFinalizedReceipt,
TurnProcessingQuiescedReceipt,
} from "../src/orchestration/Services/RuntimeReceiptBus.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
@@ -53,6 +51,8 @@ class IntegrationWaitTimeoutError extends Schema.TaggedErrorClass<IntegrationWai
},
) {}
const sleep = (ms: number) => Effect.sleep(ms);
function waitForSync<A>(
read: () => A,
predicate: (value: A) => boolean,
@@ -70,7 +70,7 @@ function waitForSync<A>(
if (Date.now() >= deadline) {
return yield* Effect.die(new IntegrationWaitTimeoutError({ description }));
}
yield* Effect.sleep(10);
yield* sleep(10);
}
});
}
@@ -91,7 +91,7 @@ function withHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
function withRealCodexHarness<A, E>(
@@ -101,7 +101,7 @@ function withRealCodexHarness<A, E>(
makeOrchestrationIntegrationHarness({ provider: "codex", realCodex: true }),
use,
(harness) => harness.dispose,
).pipe(Effect.provide(NodeServices.layer));
);
}
const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
@@ -116,10 +116,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider,
model: defaultModel,
},
defaultModel,
createdAt,
});
@@ -129,10 +126,7 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider,
model: defaultModel,
},
model: defaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -146,7 +140,7 @@ const startTurn = (input: {
readonly commandId: string;
readonly messageId: string;
readonly text: string;
readonly modelSelection?: ModelSelection;
readonly provider?: IntegrationProvider;
}) =>
input.harness.engine.dispatch({
type: "thread.turn.start",
@@ -158,11 +152,7 @@ const startTurn = (input: {
text: input.text,
attachments: [],
},
...(input.modelSelection !== undefined
? {
modelSelection: input.modelSelection,
}
: {}),
...(input.provider !== undefined ? { provider: input.provider } : {}),
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: nowIso(),
@@ -265,10 +255,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
projectId: PROJECT_ID,
title: "Integration Project",
workspaceRoot: harness.workspaceDir,
defaultModelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
defaultModel: "gpt-5.3-codex",
createdAt,
});
@@ -278,10 +265,7 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
threadId: THREAD_ID,
projectId: PROJECT_ID,
title: "Integration Thread",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -939,10 +923,7 @@ it.live("starts a claudeAgent session on first turn when provider is requested",
commandId: "cmd-turn-start-claude-initial",
messageId: "msg-user-claude-initial",
text: "Use Claude",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
@@ -996,10 +977,7 @@ it.live("recovers claudeAgent sessions after provider stopAll using persisted re
commandId: "cmd-turn-start-claude-recover-1",
messageId: "msg-user-claude-recover-1",
text: "Before restart",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
provider: "claudeAgent",
});
yield* harness.waitForThread(
@@ -1106,10 +1084,7 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
commandId: "cmd-turn-start-claude-approval",
messageId: "msg-user-claude-approval",
text: "Need approval",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
@@ -1178,10 +1153,7 @@ it.live("forwards thread.turn.interrupt to claudeAgent provider sessions", () =>
commandId: "cmd-turn-start-claude-interrupt",
messageId: "msg-user-claude-interrupt",
text: "Start long turn",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
provider: "claudeAgent",
});
const thread = yield* harness.waitForThread(
@@ -1251,10 +1223,7 @@ it.live("reverts claudeAgent turns and rolls back provider conversation state",
commandId: "cmd-turn-start-claude-revert-1",
messageId: "msg-user-claude-revert-1",
text: "First Claude edit",
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
},
provider: "claudeAgent",
});
yield* harness.waitForThread(
+1 -2
View File
@@ -1,7 +1,6 @@
{
"name": "t3",
"version": "0.0.14",
"license": "MIT",
"version": "0.0.10",
"repository": {
"type": "git",
"url": "https://github.com/pingdotgg/t3code",
+2 -2
View File
@@ -11,7 +11,7 @@ export function normalizeAttachmentRelativePath(rawRelativePath: string): string
}
export function resolveAttachmentRelativePath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly relativePath: string;
}): string | null {
const normalizedRelativePath = normalizeAttachmentRelativePath(input.relativePath);
@@ -19,7 +19,7 @@ export function resolveAttachmentRelativePath(input: {
return null;
}
const attachmentsRoot = path.resolve(input.attachmentsDir);
const attachmentsRoot = path.resolve(path.join(input.stateDir, "attachments"));
const filePath = path.resolve(path.join(attachmentsRoot, normalizedRelativePath));
if (!filePath.startsWith(`${attachmentsRoot}${path.sep}`)) {
return null;
+8 -6
View File
@@ -44,32 +44,34 @@ describe("attachmentStore", () => {
});
it("resolves attachment path by id using the extension that exists on disk", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const attachmentId = "thread-1-attachment";
const attachmentsDir = path.join(stateDir, "attachments");
fs.mkdirSync(attachmentsDir, { recursive: true });
const pngPath = path.join(attachmentsDir, `${attachmentId}.png`);
fs.writeFileSync(pngPath, Buffer.from("hello"));
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId,
});
expect(resolved).toBe(pngPath);
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
it("returns null when no attachment file exists for the id", () => {
const attachmentsDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3code-attachment-store-"));
try {
const resolved = resolveAttachmentPathById({
attachmentsDir,
stateDir,
attachmentId: "thread-1-missing",
});
expect(resolved).toBeNull();
} finally {
fs.rmSync(attachmentsDir, { recursive: true, force: true });
fs.rmSync(stateDir, { recursive: true, force: true });
}
});
});
+4 -4
View File
@@ -66,17 +66,17 @@ export function attachmentRelativePath(attachment: ChatAttachment): string {
}
export function resolveAttachmentPath(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachment: ChatAttachment;
}): string | null {
return resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: attachmentRelativePath(input.attachment),
});
}
export function resolveAttachmentPathById(input: {
readonly attachmentsDir: string;
readonly stateDir: string;
readonly attachmentId: string;
}): string | null {
const normalizedId = normalizeAttachmentRelativePath(input.attachmentId);
@@ -85,7 +85,7 @@ export function resolveAttachmentPathById(input: {
}
for (const extension of ATTACHMENT_FILENAME_EXTENSIONS) {
const maybePath = resolveAttachmentRelativePath({
attachmentsDir: input.attachmentsDir,
stateDir: input.stateDir,
relativePath: `${normalizedId}${extension}`,
});
if (maybePath && existsSync(maybePath)) {
-96
View File
@@ -1,96 +0,0 @@
import * as NFS from "node:fs";
import * as path from "node:path";
import { execFileSync, spawn } from "node:child_process";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { FileSystem, Schema } from "effect";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import { TestClock } from "effect/testing";
import { readBootstrapEnvelope, resolveFdPath } from "./bootstrap";
import { assertNone, assertSome } from "@effect/vitest/utils";
const TestEnvelopeSchema = Schema.Struct({ mode: Schema.String });
it.layer(NodeServices.layer)("readBootstrapEnvelope", (it) => {
it.effect("uses platform-specific fd paths", () =>
Effect.sync(() => {
assert.equal(resolveFdPath(3, "linux"), "/proc/self/fd/3");
assert.equal(resolveFdPath(3, "darwin"), "/dev/fd/3");
assert.equal(resolveFdPath(3, "win32"), undefined);
}),
);
it.effect("reads a bootstrap envelope from a provided fd", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(
filePath,
`${yield* Schema.encodeEffect(Schema.fromJsonString(TestEnvelopeSchema))({
mode: "desktop",
})}\n`,
);
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NFS.openSync(filePath, "r")),
(fd) => Effect.sync(() => NFS.closeSync(fd)),
);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertSome(payload, {
mode: "desktop",
});
}),
);
it.effect("returns none when the fd is unavailable", () =>
Effect.gen(function* () {
const fd = NFS.openSync("/dev/null", "r");
NFS.closeSync(fd);
const payload = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, { timeoutMs: 100 });
assertNone(payload);
}),
);
it.effect("returns none when the bootstrap read times out before any value arrives", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-bootstrap-" });
const fifoPath = path.join(tempDir, "bootstrap.pipe");
yield* Effect.sync(() => execFileSync("mkfifo", [fifoPath]));
const _writer = yield* Effect.acquireRelease(
Effect.sync(() =>
spawn("sh", ["-c", 'exec 3>"$1"; sleep 60', "sh", fifoPath], {
stdio: ["ignore", "ignore", "ignore"],
}),
),
(writer) =>
Effect.sync(() => {
writer.kill("SIGKILL");
}),
);
const fd = yield* Effect.acquireRelease(
Effect.sync(() => NFS.openSync(fifoPath, "r")),
(fd) => Effect.sync(() => NFS.closeSync(fd)),
);
const fiber = yield* readBootstrapEnvelope(TestEnvelopeSchema, fd, {
timeoutMs: 100,
}).pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* TestClock.adjust(Duration.millis(100));
const payload = yield* Fiber.join(fiber);
assertNone(payload);
}).pipe(Effect.provide(TestClock.layer())),
);
});
-145
View File
@@ -1,145 +0,0 @@
import * as NFS from "node:fs";
import * as Net from "node:net";
import * as readline from "node:readline";
import type { Readable } from "node:stream";
import { Data, Effect, Option, Predicate, Result, Schema } from "effect";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
class BootstrapError extends Data.TaggedError("BootstrapError")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export const readBootstrapEnvelope = Effect.fn("readBootstrapEnvelope")(function* <A, I>(
schema: Schema.Codec<A, I>,
fd: number,
options?: {
timeoutMs?: number;
},
): Effect.fn.Return<Option.Option<A>, BootstrapError> {
const fdReady = yield* isFdReady(fd);
if (!fdReady) return Option.none();
const stream = yield* makeBootstrapInputStream(fd);
const timeoutMs = options?.timeoutMs ?? 1000;
return yield* Effect.callback<Option.Option<A>, BootstrapError>((resume) => {
const input = readline.createInterface({
input: stream,
crlfDelay: Infinity,
});
const cleanup = () => {
stream.removeListener("error", handleError);
input.removeListener("line", handleLine);
input.removeListener("close", handleClose);
input.close();
stream.destroy();
};
const handleError = (error: Error) => {
if (isUnavailableBootstrapFdError(error)) {
resume(Effect.succeedNone);
return;
}
resume(
Effect.fail(
new BootstrapError({
message: "Failed to read bootstrap envelope.",
cause: error,
}),
),
);
};
const handleLine = (line: string) => {
const parsed = decodeJsonResult(schema)(line);
if (Result.isSuccess(parsed)) {
resume(Effect.succeedSome(parsed.success));
} else {
resume(
Effect.fail(
new BootstrapError({
message: "Failed to decode bootstrap envelope.",
cause: parsed.failure,
}),
),
);
}
};
const handleClose = () => {
resume(Effect.succeedNone);
};
stream.once("error", handleError);
input.once("line", handleLine);
input.once("close", handleClose);
return Effect.sync(cleanup);
}).pipe(Effect.timeoutOption(timeoutMs), Effect.map(Option.flatten));
});
const isUnavailableBootstrapFdError = Predicate.compose(
Predicate.hasProperty("code"),
(_) => _.code === "EBADF" || _.code === "ENOENT",
);
const isFdReady = (fd: number) =>
Effect.try({
try: () => NFS.fstatSync(fd),
catch: (error) =>
new BootstrapError({
message: "Failed to stat bootstrap fd.",
cause: error,
}),
}).pipe(
Effect.as(true),
Effect.catchIf(
(error) => isUnavailableBootstrapFdError(error.cause),
() => Effect.succeed(false),
),
);
const makeBootstrapInputStream = (fd: number) =>
Effect.try<Readable, BootstrapError>({
try: () => {
const fdPath = resolveFdPath(fd);
if (fdPath === undefined) {
const stream = new Net.Socket({
fd,
readable: true,
writable: false,
});
stream.setEncoding("utf8");
return stream;
}
const streamFd = NFS.openSync(fdPath, "r");
return NFS.createReadStream("", {
fd: streamFd,
encoding: "utf8",
autoClose: true,
});
},
catch: (error) =>
new BootstrapError({
message: "Failed to duplicate bootstrap fd.",
cause: error,
}),
});
export function resolveFdPath(
fd: number,
platform: NodeJS.Platform = process.platform,
): string | undefined {
if (platform === "linux") {
return `/proc/self/fd/${fd}`;
}
if (platform === "win32") {
return undefined;
}
return `/dev/fd/${fd}`;
}
@@ -31,7 +31,7 @@ function makeSnapshot(input: {
id: input.projectId,
title: "Project",
workspaceRoot: input.workspaceRoot,
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
@@ -43,10 +43,7 @@ function makeSnapshot(input: {
id: input.threadId,
projectId: input.projectId,
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -65,6 +62,7 @@ function makeSnapshot(input: {
messages: [],
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [
{
turnId: TurnId.makeUnsafe("turn-1"),
@@ -15,14 +15,15 @@ import { Effect, Layer, FileSystem, Path } from "effect";
import { CheckpointInvariantError } from "../Errors.ts";
import { GitCommandError } from "../../git/Errors.ts";
import { GitCore } from "../../git/Services/GitCore.ts";
import { GitServiceLive } from "../../git/Layers/GitService.ts";
import { GitService } from "../../git/Services/GitService.ts";
import { CheckpointStore, type CheckpointStoreShape } from "../Services/CheckpointStore.ts";
import { CheckpointRef } from "@t3tools/contracts";
const makeCheckpointStore = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const git = yield* GitCore;
const git = yield* GitService;
const resolveHeadCommit = (cwd: string): Effect.Effect<string | null, GitCommandError> =>
git
@@ -276,4 +277,6 @@ const makeCheckpointStore = Effect.gen(function* () {
} satisfies CheckpointStoreShape;
});
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore);
export const CheckpointStoreLive = Layer.effect(CheckpointStore, makeCheckpointStore).pipe(
Layer.provideMerge(GitServiceLive),
);
@@ -38,6 +38,7 @@ function createSendTurnHarness() {
sparkEnabled: true,
},
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -77,6 +78,7 @@ function createThreadControlHarness() {
updatedAt: "2026-02-10T00:00:00.000Z",
},
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -120,6 +122,7 @@ function createPendingUserInputHarness() {
],
]),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
const requireSession = vi
@@ -161,6 +164,7 @@ function createCollabNotificationHarness() {
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map<string, string>(),
collabReceiverItems: new Map<string, string>(),
nextRequestId: 1,
stopping: false,
};
@@ -762,6 +766,7 @@ describe("respondToUserInput", () => {
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
};
type ApprovalRequestContext = {
session: typeof context.session;
@@ -933,6 +938,51 @@ describe("collab child conversation routing", () => {
}),
);
});
it("rewrites child task notifications onto the parent collab item when no child item id exists", () => {
const { manager, context, emitEvent } = createCollabNotificationHarness();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "item/completed",
params: {
item: {
type: "collabAgentToolCall",
id: "call_collab_1",
receiverThreadIds: ["child_provider_1"],
},
threadId: "provider_parent",
turnId: "turn_parent",
},
});
emitEvent.mockClear();
(
manager as unknown as {
handleServerNotification: (context: unknown, notification: Record<string, unknown>) => void;
}
).handleServerNotification(context, {
method: "codex/event/task_started",
params: {
threadId: "child_provider_1",
msg: {
type: "task_started",
turn_id: "turn_child_1",
},
},
});
expect(emitEvent).toHaveBeenCalledWith(
expect.objectContaining({
method: "codex/event/task_started",
turnId: "turn_parent",
itemId: "call_collab_1",
}),
);
});
});
describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume", () => {
+27 -4
View File
@@ -71,6 +71,7 @@ interface CodexSessionContext {
pendingApprovals: Map<ApprovalRequestId, PendingApprovalRequest>;
pendingUserInputs: Map<ApprovalRequestId, PendingUserInputRequest>;
collabReceiverTurns: Map<string, TurnId>;
collabReceiverItems: Map<string, ProviderItemId>;
nextRequestId: number;
stopping: boolean;
}
@@ -573,6 +574,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
pendingApprovals: new Map(),
pendingUserInputs: new Map(),
collabReceiverTurns: new Map(),
collabReceiverItems: new Map(),
nextRequestId: 1,
stopping: false,
};
@@ -735,6 +737,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
async sendTurn(input: CodexAppServerSendTurnInput): Promise<ProviderTurnStartResult> {
const context = this.requireSession(input.threadId);
context.collabReceiverTurns.clear();
context.collabReceiverItems.clear();
const turnInput: Array<
{ type: "text"; text: string; text_elements: [] } | { type: "image"; url: string }
@@ -1127,7 +1130,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
const rawRoute = this.readRouteFields(notification.params);
this.rememberCollabReceiverTurns(context, notification.params, rawRoute.turnId);
const childParentTurnId = this.readChildParentTurnId(context, notification.params);
const childParentItemId = this.readChildParentItemId(context, notification.params);
const isChildConversation = childParentTurnId !== undefined;
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
if (
isChildConversation &&
this.shouldSuppressChildConversationNotification(notification.method)
@@ -1149,7 +1154,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
...((childParentTurnId ?? rawRoute.turnId)
? { turnId: childParentTurnId ?? rawRoute.turnId }
: {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
textDelta,
payload: notification.params,
});
@@ -1181,6 +1186,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return;
}
context.collabReceiverTurns.clear();
context.collabReceiverItems.clear();
const turn = this.readObject(notification.params, "turn");
const status = this.readString(turn, "status");
const errorMessage = this.readString(this.readObject(turn, "error"), "message");
@@ -1209,7 +1215,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
private handleServerRequest(context: CodexSessionContext, request: JsonRpcRequest): void {
const rawRoute = this.readRouteFields(request.params);
const childParentTurnId = this.readChildParentTurnId(context, request.params);
const childParentItemId = this.readChildParentItemId(context, request.params);
const effectiveTurnId = childParentTurnId ?? rawRoute.turnId;
const effectiveItemId = rawRoute.itemId ?? childParentItemId;
const requestKind = this.requestKindForMethod(request.method);
let requestId: ApprovalRequestId | undefined;
if (requestKind) {
@@ -1226,7 +1234,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
requestKind,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
};
context.pendingApprovals.set(requestId, pendingRequest);
}
@@ -1238,7 +1246,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
jsonRpcId: request.id,
threadId: context.session.threadId,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
});
}
@@ -1250,7 +1258,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
createdAt: new Date().toISOString(),
method: request.method,
...(effectiveTurnId ? { turnId: effectiveTurnId } : {}),
...(rawRoute.itemId ? { itemId: rawRoute.itemId } : {}),
...(effectiveItemId ? { itemId: effectiveItemId } : {}),
requestId,
requestKind,
payload: request.params,
@@ -1493,6 +1501,17 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
return context.collabReceiverTurns.get(providerConversationId);
}
private readChildParentItemId(
context: CodexSessionContext,
params: unknown,
): ProviderItemId | undefined {
const providerConversationId = this.readProviderConversationId(params);
if (!providerConversationId) {
return undefined;
}
return context.collabReceiverItems.get(providerConversationId);
}
private rememberCollabReceiverTurns(
context: CodexSessionContext,
params: unknown,
@@ -1507,6 +1526,7 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
if (itemType !== "collabAgentToolCall") {
return;
}
const parentItemId = toProviderItemId(this.readString(item, "id"));
const receiverThreadIds =
this.readArray(item, "receiverThreadIds")
@@ -1514,6 +1534,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
.filter((value): value is string => value !== null) ?? [];
for (const receiverThreadId of receiverThreadIds) {
context.collabReceiverTurns.set(receiverThreadId, parentTurnId);
if (parentItemId) {
context.collabReceiverItems.set(receiverThreadId, parentItemId);
}
}
}
+9 -64
View File
@@ -12,33 +12,16 @@ export const DEFAULT_PORT = 3773;
export type RuntimeMode = "web" | "desktop";
/**
* ServerDerivedPaths - Derived paths from the base directory.
*/
export interface ServerDerivedPaths {
readonly stateDir: string;
readonly dbPath: string;
readonly keybindingsConfigPath: string;
readonly settingsPath: string;
readonly worktreesDir: string;
readonly attachmentsDir: string;
readonly logsDir: string;
readonly serverLogPath: string;
readonly providerLogsDir: string;
readonly providerEventLogPath: string;
readonly terminalLogsDir: string;
readonly anonymousIdPath: string;
}
/**
* ServerConfigShape - Process/runtime configuration required by the server.
*/
export interface ServerConfigShape extends ServerDerivedPaths {
export interface ServerConfigShape {
readonly mode: RuntimeMode;
readonly port: number;
readonly host: string | undefined;
readonly cwd: string;
readonly baseDir: string;
readonly keybindingsConfigPath: string;
readonly stateDir: string;
readonly staticDir: string | undefined;
readonly devUrl: URL | undefined;
readonly noBrowser: boolean;
@@ -47,69 +30,31 @@ export interface ServerConfigShape extends ServerDerivedPaths {
readonly logWebSocketEvents: boolean;
}
export const deriveServerPaths = Effect.fn(function* (
baseDir: ServerConfigShape["baseDir"],
devUrl: ServerConfigShape["devUrl"],
): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
const { join } = yield* Path.Path;
const stateDir = join(baseDir, devUrl !== undefined ? "dev" : "userdata");
const dbPath = join(stateDir, "state.sqlite");
const attachmentsDir = join(stateDir, "attachments");
const logsDir = join(stateDir, "logs");
const providerLogsDir = join(logsDir, "provider");
return {
stateDir,
dbPath,
keybindingsConfigPath: join(stateDir, "keybindings.json"),
settingsPath: join(stateDir, "settings.json"),
worktreesDir: join(baseDir, "worktrees"),
attachmentsDir,
logsDir,
serverLogPath: join(logsDir, "server.log"),
providerLogsDir,
providerEventLogPath: join(providerLogsDir, "events.log"),
terminalLogsDir: join(logsDir, "terminals"),
anonymousIdPath: join(stateDir, "anonymous-id"),
};
});
/**
* ServerConfig - Service tag for server runtime configuration.
*/
export class ServerConfig extends ServiceMap.Service<ServerConfig, ServerConfigShape>()(
"t3/config/ServerConfig",
) {
static readonly layerTest = (cwd: string, baseDirOrPrefix: string | { prefix: string }) =>
static readonly layerTest = (cwd: string, statedir: string) =>
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const devUrl = undefined;
const fs = yield* FileSystem.FileSystem;
const baseDir =
typeof baseDirOrPrefix === "string"
? baseDirOrPrefix
: yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
yield* fs.makeDirectory(derivedPaths.stateDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.logsDir, { recursive: true });
yield* fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true });
const path = yield* Path.Path;
return {
cwd,
baseDir,
...derivedPaths,
stateDir: statedir,
mode: "web",
autoBootstrapProjectFromCwd: false,
logWebSocketEvents: false,
port: 0,
host: undefined,
authToken: undefined,
keybindingsConfigPath: path.join(statedir, "keybindings.json"),
staticDir: undefined,
devUrl,
devUrl: undefined,
noBrowser: false,
} satisfies ServerConfigShape;
};
}),
);
}
@@ -1,250 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const ClaudeTextGenerationTestLayer = ClaudeTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-claude-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeClaudeBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = path.join(dir, "bin");
const claudePath = path.join(binDir, "claude");
yield* fs.makeDirectory(binDir, { recursive: true });
yield* fs.writeFileString(
claudePath,
[
"#!/bin/sh",
'args="$*"',
'stdin_content="$(cat)"',
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" ]; then',
' printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "args missing expected content" >&2',
" exit 2",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$args" | grep -F -- "$T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "args contained forbidden content" >&2',
" exit 3",
" fi",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
" exit 4",
" }",
"fi",
'if [ -n "$T3_FAKE_CLAUDE_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CLAUDE_STDERR" >&2',
"fi",
'printf "%s" "$T3_FAKE_CLAUDE_OUTPUT"',
'exit "${T3_FAKE_CLAUDE_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(claudePath, 0o755);
return binDir;
});
}
function withFakeClaudeEnv<A, E, R>(
input: {
output: string;
exitCode?: number;
stderr?: string;
argsMustContain?: string;
argsMustNotContain?: string;
stdinMustContain?: string;
},
effect: Effect.Effect<A, E, R>,
) {
return Effect.acquireUseRelease(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-claude-text-" });
const binDir = yield* makeFakeClaudeBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CLAUDE_OUTPUT;
const previousExitCode = process.env.T3_FAKE_CLAUDE_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CLAUDE_STDERR;
const previousArgsMustContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
const previousArgsMustNotContain = process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
const previousStdinMustContain = process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CLAUDE_OUTPUT = input.output;
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CLAUDE_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CLAUDE_STDERR;
}
if (input.argsMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = input.argsMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
}
if (input.argsMustNotContain !== undefined) {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = input.argsMustNotContain;
} else {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
}
});
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousArgsMustContain,
previousArgsMustNotContain,
previousStdinMustContain,
};
}),
() => effect,
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CLAUDE_OUTPUT;
} else {
process.env.T3_FAKE_CLAUDE_OUTPUT = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CLAUDE_EXIT_CODE;
} else {
process.env.T3_FAKE_CLAUDE_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDERR;
} else {
process.env.T3_FAKE_CLAUDE_STDERR = previous.previousStderr;
}
if (previous.previousArgsMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_CONTAIN = previous.previousArgsMustContain;
}
if (previous.previousArgsMustNotContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_ARGS_MUST_NOT_CONTAIN = previous.previousArgsMustNotContain;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN;
} else {
process.env.T3_FAKE_CLAUDE_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
}),
);
}
it.layer(ClaudeTextGenerationTestLayer)("ClaudeTextGenerationLive", (it) => {
it.effect("forwards Claude thinking settings for Haiku without passing effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
subject: "Add important change",
body: "",
},
}),
argsMustContain: '--settings {"alwaysThinkingEnabled":false}',
argsMustNotContain: "--effort",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/claude-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
effort: "high",
},
},
});
expect(generated.subject).toBe("Add important change");
}),
),
);
it.effect("forwards Claude fast mode and supported effort", () =>
withFakeClaudeEnv(
{
output: JSON.stringify({
structured_output: {
title: "Improve orchestration flow",
body: "Body",
},
}),
argsMustContain: '--effort max --settings {"fastMode":true}',
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generatePrContent({
cwd: process.cwd(),
baseBranch: "main",
headBranch: "feature/claude-effect",
commitSummary: "Improve orchestration",
diffSummary: "1 file changed",
diffPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
fastMode: true,
},
},
});
expect(generated.title).toBe("Improve orchestration flow");
}),
),
);
});
@@ -1,308 +0,0 @@
/**
* ClaudeTextGeneration – Text generation layer using the Claude CLI.
*
* Implements the same TextGenerationShape contract as CodexTextGeneration but
* delegates to the `claude` CLI (`claude -p`) with structured JSON output
* instead of the `codex exec` CLI.
*
* @module ClaudeTextGeneration
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ClaudeModelSelection } from "@t3tools/contracts";
import { normalizeClaudeModelOptions } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { TextGenerationError } from "../Errors.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
/**
* Schema for the wrapper JSON returned by `claude -p --output-format json`.
* We only care about `structured_output`.
*/
const ClaudeOutputEnvelope = Schema.Struct({
structured_output: Schema.Unknown,
});
const makeClaudeTextGeneration = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverSettingsService = yield* Effect.service(ServerSettingsService);
const readStreamAsString = <E>(
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to collect process output"),
),
);
/**
* Spawn the Claude CLI with structured JSON output and return the parsed,
* schema-validated result.
*/
const runClaudeJson = <S extends Schema.Top>({
operation,
cwd,
prompt,
outputSchemaJson,
modelSelection,
}: {
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
prompt: string;
outputSchemaJson: S;
modelSelection: ClaudeModelSelection;
}): 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 claudeSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.claude,
).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",
modelSelection.model,
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
"--dangerously-skip-permissions",
],
{
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
},
},
);
const child = yield* commandSpawner
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("claude", operation, cause, "Failed to spawn Claude CLI process"),
),
);
const [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),
}),
),
);
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
// ---------------------------------------------------------------------------
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"ClaudeTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"ClaudeTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"ClaudeTextGeneration.generateBranchName",
)(function* (input) {
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
if (input.modelSelection.provider !== "claudeAgent") {
return yield* new TextGenerationError({
operation: "generateBranchName",
detail: "Invalid model selection.",
});
}
const generated = yield* runClaudeJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
return {
generateCommitMessage,
generatePrContent,
generateBranchName,
} satisfies TextGenerationShape;
});
export const ClaudeTextGenerationLive = Layer.effect(TextGeneration, makeClaudeTextGeneration);
@@ -1,28 +1,18 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Result } from "effect";
import { Effect, FileSystem, Layer, Path } from "effect";
import { expect } from "vitest";
import { ServerConfig } from "../../config.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { TextGenerationError } from "../Errors.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "codex" as const,
model: "gpt-5.4-mini",
};
const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-codex-text-generation-test-",
}),
),
Layer.provideMerge(NodeServices.layer),
);
const makeCodexTextGenerationTestLayer = (stateDir: string) =>
CodexTextGenerationLive.pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(dir: string) {
return Effect.gen(function* () {
@@ -45,18 +35,6 @@ function makeFakeCodexBinary(dir: string) {
" fi",
" continue",
" fi",
' if [ "$1" = "--config" ]; then',
" shift",
' if [ "$1" = "service_tier=\\"fast\\"" ]; then',
' seen_fast_service_tier="1"',
" fi",
' case "$1" in',
" model_reasoning_effort=*)",
' seen_reasoning_effort="$1"',
" ;;",
" esac",
" continue",
" fi",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
@@ -68,18 +46,6 @@ function makeFakeCodexBinary(dir: string) {
' printf "%s\\n" "missing --image input" >&2',
" exit 2",
"fi",
'if [ "$T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER" = "1" ] && [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
" exit 5",
"fi",
'if [ -n "$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT" ] && [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT\\"" ]; then',
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
" exit 6",
"fi",
'if [ "$T3_FAKE_CODEX_FORBID_REASONING_EFFORT" = "1" ] && [ -n "$seen_reasoning_effort" ]; then',
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
" exit 7",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
' printf "%s\\n" "stdin missing expected content" >&2',
@@ -113,9 +79,6 @@ function withFakeCodexEnv<A, E, R>(
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
@@ -131,9 +94,6 @@ function withFakeCodexEnv<A, E, R>(
const previousExitCode = process.env.T3_FAKE_CODEX_EXIT_CODE;
const previousStderr = process.env.T3_FAKE_CODEX_STDERR;
const previousRequireImage = process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
const previousRequireFastServiceTier = process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
const previousRequireReasoningEffort = process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
const previousForbidReasoningEffort = process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
const previousStdinMustContain = process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
const previousStdinMustNotContain = process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
@@ -159,24 +119,6 @@ function withFakeCodexEnv<A, E, R>(
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
}
if (input.requireFastServiceTier) {
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER = "1";
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
}
if (input.requireReasoningEffort !== undefined) {
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT = input.requireReasoningEffort;
} else {
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
}
if (input.forbidReasoningEffort) {
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT = "1";
} else {
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
}
if (input.stdinMustContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = input.stdinMustContain;
} else {
@@ -196,9 +138,6 @@ function withFakeCodexEnv<A, E, R>(
previousExitCode,
previousStderr,
previousRequireImage,
previousRequireFastServiceTier,
previousRequireReasoningEffort,
previousForbidReasoningEffort,
previousStdinMustContain,
previousStdinMustNotContain,
};
@@ -232,27 +171,6 @@ function withFakeCodexEnv<A, E, R>(
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = previous.previousRequireImage;
}
if (previous.previousRequireFastServiceTier === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER =
previous.previousRequireFastServiceTier;
}
if (previous.previousRequireReasoningEffort === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT;
} else {
process.env.T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT =
previous.previousRequireReasoningEffort;
}
if (previous.previousForbidReasoningEffort === undefined) {
delete process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT;
} else {
process.env.T3_FAKE_CODEX_FORBID_REASONING_EFFORT =
previous.previousForbidReasoningEffort;
}
if (previous.previousStdinMustContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
} else {
@@ -268,6 +186,8 @@ function withFakeCodexEnv<A, E, R>(
);
}
const CodexTextGenerationTestLayer = makeCodexTextGenerationTestLayer(process.cwd());
it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
it.effect("generates and sanitizes commit messages without branch by default", () =>
withFakeCodexEnv(
@@ -287,7 +207,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject.length).toBeLessThanOrEqual(72);
@@ -298,63 +217,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
),
);
it.effect(
"forwards codex fast mode and non-default reasoning effort into codex exec config",
() =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
requireFastServiceTier: true,
requireReasoningEffort: "xhigh",
stdinMustNotContain: "branch must be a short semantic git branch fragment",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
reasoningEffort: "xhigh",
fastMode: true,
},
},
});
}),
),
);
it.effect("defaults git text generation codex effort to low", () =>
withFakeCodexEnv(
{
output: JSON.stringify({
subject: "Add important change",
body: "",
}),
requireReasoningEffort: "low",
},
Effect.gen(function* () {
const textGeneration = yield* TextGeneration;
yield* textGeneration.generateCommitMessage({
cwd: process.cwd(),
branch: "feature/codex-effect",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
}),
),
);
it.effect("generates commit message with branch when includeBranch is true", () =>
withFakeCodexEnv(
{
@@ -374,7 +236,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
includeBranch: true,
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.subject).toBe("Add important change");
@@ -401,7 +262,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
commitSummary: "feat: improve orchestration flow",
diffSummary: "2 files changed",
diffPatch: "diff --git a/a.ts b/a.ts",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.title).toBe("Improve orchestration flow");
@@ -425,7 +285,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Please update session handling.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("feat/session");
@@ -447,7 +306,6 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
const generated = yield* textGeneration.generateBranchName({
cwd: process.cwd(),
message: "Fix timeout behavior.",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
});
expect(generated.branch).toBe("fix/session-timeout");
@@ -467,27 +325,27 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-branch-image-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const attachmentPath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const attachmentPath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
});
const generated = yield* textGeneration
.generateBranchName({
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
{
type: "image",
id: attachmentId,
name: "bug.png",
mimeType: "image/png",
sizeBytes: 5,
},
],
})
.pipe(Effect.ensuring(fs.remove(attachmentPath).pipe(Effect.catch(() => Effect.void))));
expect(generated.branch).toBe("fix/ui-regression");
}),
@@ -505,16 +363,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const attachmentId = `thread-1-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const imagePath = path.join(attachmentsDir, `${attachmentId}.png`);
yield* fs.makeDirectory(attachmentsDir, { recursive: true });
const imagePath = path.join(process.cwd(), "attachments", `${attachmentId}.png`);
yield* fs.makeDirectory(path.join(process.cwd(), "attachments"), { recursive: true });
yield* fs.writeFile(imagePath, Buffer.from("hello"));
const textGeneration = yield* TextGeneration;
const generated = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
@@ -554,15 +410,13 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const { attachmentsDir } = yield* ServerConfig;
const missingAttachmentId = `thread-missing-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
const missingPath = path.join(attachmentsDir, `${missingAttachmentId}.png`);
const missingPath = path.join(process.cwd(), "attachments", `${missingAttachmentId}.png`);
yield* fs.remove(missingPath).pipe(Effect.catch(() => Effect.void));
const textGeneration = yield* TextGeneration;
const result = yield* textGeneration
.generateBranchName({
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
cwd: process.cwd(),
message: "Fix layout bug from screenshot.",
attachments: [
@@ -575,12 +429,17 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
},
],
})
.pipe(Effect.result);
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("missing --image input");
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("missing --image input");
}
}),
),
@@ -602,14 +461,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
.generateBranchName({
cwd: process.cwd(),
message: "Fix websocket reconnect flake",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain("Codex returned invalid structured output");
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("Codex returned invalid structured output");
}
}),
),
@@ -631,16 +494,18 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
branch: "feature/codex-error",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
})
.pipe(Effect.result);
expect(Result.isFailure(result)).toBe(true);
if (Result.isFailure(result)) {
expect(result.failure).toBeInstanceOf(TextGenerationError);
expect(result.failure.message).toContain(
"Codex CLI command failed: codex execution failed",
.pipe(
Effect.match({
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
}),
);
expect(result._tag).toBe("Left");
if (result._tag === "Left") {
expect(result.left).toBeInstanceOf(TextGenerationError);
expect(result.left.message).toContain("Codex CLI command failed: codex execution failed");
}
}),
),
+250 -148
View File
@@ -1,10 +1,9 @@
import { randomUUID } from "node:crypto";
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { normalizeCodexModelOptions } from "@t3tools/shared/model";
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -12,31 +11,95 @@ import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../Errors.ts";
import {
type BranchNameGenerationInput,
type BranchNameGenerationResult,
type CommitMessageGenerationResult,
type PrContentGenerationResult,
type TextGenerationShape,
TextGeneration,
} from "../Services/TextGeneration.ts";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
} from "../Prompts.ts";
import {
normalizeCliError,
sanitizeCommitSubject,
sanitizePrTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
const CODEX_REASONING_EFFORT = "low";
const CODEX_TIMEOUT_MS = 180_000;
function toCodexOutputJsonSchema(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return {
...document.schema,
$defs: document.definitions,
};
}
return document.schema;
}
function normalizeCodexError(
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes("Command not found: codex") ||
lower.includes("spawn codex") ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: "Codex CLI (`codex`) is required but not available on PATH.",
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
const makeCodexTextGeneration = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const serverConfig = yield* Effect.service(ServerConfig);
const serverSettingsService = yield* Effect.service(ServerSettingsService);
type MaterializedImageAttachments = {
readonly imagePaths: ReadonlyArray<string>;
@@ -46,37 +109,39 @@ const makeCodexTextGeneration = Effect.gen(function* () {
operation: string,
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, TextGenerationError> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to collect process output"),
),
);
Effect.gen(function* () {
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.sync(() => {
text += Buffer.from(chunk).toString("utf8");
}),
).pipe(
Effect.mapError((cause) =>
normalizeCodexError(operation, cause, "Failed to collect process output"),
),
);
return text;
});
const tempDir = process.env.TMPDIR ?? process.env.TEMP ?? process.env.TMP ?? "/tmp";
const writeTempFile = (
operation: string,
prefix: string,
content: string,
): Effect.Effect<string, TextGenerationError, Scope.Scope> => {
return fileSystem
.makeTempFileScoped({
prefix: `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`,
})
.pipe(
Effect.tap((filePath) => fileSystem.writeFileString(filePath, content)),
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file`,
cause,
}),
),
);
): Effect.Effect<string, TextGenerationError> => {
const filePath = path.join(tempDir, `t3code-${prefix}-${process.pid}-${randomUUID()}.tmp`);
return fileSystem.writeFileString(filePath, content).pipe(
Effect.mapError(
(cause) =>
new TextGenerationError({
operation,
detail: `Failed to write temp file at ${filePath}.`,
cause,
}),
),
Effect.as(filePath),
);
};
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
@@ -98,7 +163,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
}
const resolvedPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment,
});
if (!resolvedPath || !path.isAbsolute(resolvedPath)) {
@@ -122,7 +187,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
outputSchemaJson,
imagePaths = [],
cleanupPaths = [],
modelSelection,
model,
}: {
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
cwd: string;
@@ -130,40 +195,28 @@ const makeCodexTextGeneration = Effect.gen(function* () {
outputSchemaJson: S;
imagePaths?: ReadonlyArray<string>;
cleanupPaths?: ReadonlyArray<string>;
modelSelection: CodexModelSelection;
model?: string;
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const schemaPath = yield* writeTempFile(
operation,
"codex-schema",
JSON.stringify(toJsonSchemaObject(outputSchemaJson)),
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
);
const outputPath = yield* writeTempFile(operation, "codex-output", "");
const codexSettings = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.codex,
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptions(
modelSelection.model,
modelSelection.options,
);
const reasoningEffort =
modelSelection.options?.reasoningEffort ?? CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT;
const command = ChildProcess.make(
codexSettings?.binaryPath || "codex",
"codex",
[
"exec",
"--ephemeral",
"-s",
"read-only",
"--model",
modelSelection.model,
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
"--config",
`model_reasoning_effort="${reasoningEffort}"`,
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
"--output-schema",
schemaPath,
"--output-last-message",
@@ -172,11 +225,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
"-",
],
{
env: codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {},
cwd,
shell: process.platform === "win32",
stdin: {
stream: Stream.encodeText(Stream.make(prompt)),
stream: Stream.make(new TextEncoder().encode(prompt)),
},
},
);
@@ -185,7 +237,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
.spawn(command)
.pipe(
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
),
);
@@ -194,8 +246,9 @@ const makeCodexTextGeneration = Effect.gen(function* () {
readStreamAsString(operation, child.stdout),
readStreamAsString(operation, child.stderr),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError((cause) =>
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
),
),
],
@@ -261,104 +314,153 @@ const makeCodexTextGeneration = Effect.gen(function* () {
}).pipe(Effect.ensuring(cleanup));
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = Effect.fn(
"CodexTextGeneration.generateCommitMessage",
)(function* (input) {
const { prompt, outputSchema } = buildCommitMessagePrompt({
branch: input.branch,
stagedSummary: input.stagedSummary,
stagedPatch: input.stagedPatch,
includeBranch: input.includeBranch === true,
});
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
const wantsBranch = input.includeBranch === true;
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generateCommitMessage",
detail: "Invalid model selection.",
});
}
const prompt = [
"You write concise git commit messages.",
wantsBranch
? "Return a JSON object with keys: subject, body, branch."
: "Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
...(wantsBranch
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
const generated = yield* runCodexJson({
const outputSchemaJson = wantsBranch
? Schema.Struct({
subject: Schema.String,
body: Schema.String,
branch: Schema.String,
})
: Schema.Struct({
subject: Schema.String,
body: Schema.String,
});
return runCodexJson({
operation: "generateCommitMessage",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
outputSchemaJson,
...(input.model ? { model: input.model } : {}),
}).pipe(
Effect.map(
(generated) =>
({
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
}) satisfies CommitMessageGenerationResult,
),
);
};
return {
subject: sanitizeCommitSubject(generated.subject),
body: generated.body.trim(),
...("branch" in generated && typeof generated.branch === "string"
? { branch: sanitizeFeatureBranchName(generated.branch) }
: {}),
};
});
const generatePrContent: TextGenerationShape["generatePrContent"] = (input) => {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const generatePrContent: TextGenerationShape["generatePrContent"] = Effect.fn(
"CodexTextGeneration.generatePrContent",
)(function* (input) {
const { prompt, outputSchema } = buildPrContentPrompt({
baseBranch: input.baseBranch,
headBranch: input.headBranch,
commitSummary: input.commitSummary,
diffSummary: input.diffSummary,
diffPatch: input.diffPatch,
});
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
operation: "generatePrContent",
detail: "Invalid model selection.",
});
}
const generated = yield* runCodexJson({
return runCodexJson({
operation: "generatePrContent",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
modelSelection: input.modelSelection,
});
return {
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
};
});
const generateBranchName: TextGenerationShape["generateBranchName"] = Effect.fn(
"CodexTextGeneration.generateBranchName",
)(function* (input) {
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
outputSchemaJson: Schema.Struct({
title: Schema.String,
body: Schema.String,
}),
...(input.model ? { model: input.model } : {}),
}).pipe(
Effect.map(
(generated) =>
({
title: sanitizePrTitle(generated.title),
body: generated.body.trim(),
}) satisfies PrContentGenerationResult,
),
);
const { prompt, outputSchema } = buildBranchNamePrompt({
message: input.message,
attachments: input.attachments,
});
};
if (input.modelSelection.provider !== "codex") {
return yield* new TextGenerationError({
const generateBranchName: TextGenerationShape["generateBranchName"] = (input) => {
return Effect.gen(function* () {
const { imagePaths } = yield* materializeImageAttachments(
"generateBranchName",
input.attachments,
);
const attachmentLines = (input.attachments ?? []).map(
(attachment) =>
`- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
const promptSections = [
"You generate concise git branch names.",
"Return a JSON object with key: branch.",
"Rules:",
"- Branch should describe the requested work from the user message.",
"- Keep it short and specific (2-6 words).",
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
"- If images are attached, use them as primary context for visual/UI issues.",
"",
"User message:",
limitSection(input.message, 8_000),
];
if (attachmentLines.length > 0) {
promptSections.push(
"",
"Attachment metadata:",
limitSection(attachmentLines.join("\n"), 4_000),
);
}
const prompt = promptSections.join("\n");
const generated = yield* runCodexJson({
operation: "generateBranchName",
detail: "Invalid model selection.",
cwd: input.cwd,
prompt,
outputSchemaJson: Schema.Struct({
branch: Schema.String,
}),
imagePaths,
...(input.model ? { model: input.model } : {}),
});
}
const generated = yield* runCodexJson({
operation: "generateBranchName",
cwd: input.cwd,
prompt,
outputSchemaJson: outputSchema,
imagePaths,
modelSelection: input.modelSelection,
return {
branch: sanitizeBranchFragment(generated.branch),
} satisfies BranchNameGenerationResult;
});
return {
branch: sanitizeBranchFragment(generated.branch),
};
});
};
return {
generateCommitMessage,
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+12 -145
View File
@@ -6,7 +6,6 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { Effect, FileSystem, Layer, PlatformError, Scope } from "effect";
import { expect } from "vitest";
import type { GitActionProgressEvent } from "@t3tools/contracts";
import { GitCommandError, GitHubCliError, TextGenerationError } from "../Errors.ts";
import { type GitManagerShape } from "../Services/GitManager.ts";
@@ -16,15 +15,10 @@ import {
GitHubCli,
} from "../Services/GitHubCli.ts";
import { type TextGenerationShape, TextGeneration } from "../Services/TextGeneration.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
import { GitCoreLive } from "./GitCore.ts";
import { GitCore } from "../Services/GitCore.ts";
import { makeGitManager } from "./GitManager.ts";
import { ServerConfig } from "../../config.ts";
const DEFAULT_TEST_MODEL_SELECTION = {
provider: "codex",
model: "gpt-5.4-mini",
} as const;
interface FakeGhScenario {
prListSequence?: string[];
@@ -112,11 +106,11 @@ function runGit(
): Effect.Effect<
{ readonly code: number; readonly stdout: string; readonly stderr: string },
GitCommandError,
GitCore
GitService
> {
return Effect.gen(function* () {
const gitCore = yield* GitCore;
return yield* gitCore.execute({
const gitService = yield* GitService;
return yield* gitService.execute({
operation: "GitManager.test.runGit",
cwd,
args,
@@ -130,7 +124,7 @@ function initRepo(
): Effect.Effect<
void,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -146,7 +140,7 @@ function initRepo(
function createBareRemote(): Effect.Effect<
string,
PlatformError.PlatformError | GitCommandError,
FileSystem.FileSystem | Scope.Scope | GitCore
FileSystem.FileSystem | Scope.Scope | GitService
> {
return Effect.gen(function* () {
const remoteDir = yield* makeTempDir("t3code-git-remote-");
@@ -455,21 +449,12 @@ function runStackedAction(
input: {
cwd: string;
action: "commit" | "commit_push" | "commit_push_pr";
actionId?: string;
commitMessage?: string;
featureBranch?: boolean;
filePaths?: readonly string[];
},
options?: Parameters<GitManagerShape["runStackedAction"]>[1],
) {
return manager.runStackedAction(
{
...input,
actionId: input.actionId ?? "test-action-id",
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
},
options,
);
return manager.runStackedAction(input);
}
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
@@ -489,20 +474,18 @@ function makeManager(input?: {
}) {
const { service: gitHubCli, ghCalls } = createGitHubCliWithFakeGh(input?.ghScenario);
const textGeneration = createTextGeneration(input?.textGeneration);
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-git-manager-test-",
});
const gitCoreLayer = GitCoreLive.pipe(
Layer.provideMerge(GitServiceLive),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(ServerConfigLayer),
);
const managerLayer = Layer.mergeAll(
Layer.succeed(GitHubCli, gitHubCli),
Layer.succeed(TextGeneration, textGeneration),
gitCoreLayer,
).pipe(Layer.provideMerge(NodeServices.layer));
NodeServices.layer,
);
return makeGitManager.pipe(
Effect.provide(managerLayer),
@@ -510,10 +493,7 @@ function makeManager(input?: {
);
}
const GitManagerTestLayer = GitCoreLive.pipe(
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-git-manager-test-" })),
Layer.provideMerge(NodeServices.layer),
);
const GitManagerTestLayer = Layer.provideMerge(GitServiceLive, NodeServices.layer);
it.layer(GitManagerTestLayer)("GitManager", (it) => {
it.effect("status includes PR metadata when branch already has an open PR", () =>
@@ -1956,117 +1936,4 @@ it.layer(GitManagerTestLayer)("GitManager", (it) => {
expect(errorMessage).toContain("already checked out in the main repo");
}),
);
it.effect("emits ordered progress events for commit hooks", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hooked.txt"), "hooked\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: start" >&2\nsleep 1\necho "hook: end" >&2\n',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const result = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-1",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
);
expect(result.commit.status).toBe("created");
expect(events.map((event) => event.kind)).toContain("action_started");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "phase_started",
phase: "commit",
}),
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: start",
}),
expect.objectContaining({
kind: "hook_output",
text: "hook: end",
}),
expect.objectContaining({
kind: "hook_finished",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_finished",
}),
]),
);
}),
);
it.effect("emits action_failed when a commit hook rejects", () =>
Effect.gen(function* () {
const repoDir = yield* makeTempDir("t3code-git-manager-");
yield* initRepo(repoDir);
fs.writeFileSync(path.join(repoDir, "hook-failure.txt"), "broken\n");
fs.writeFileSync(
path.join(repoDir, ".git", "hooks", "pre-commit"),
'#!/bin/sh\necho "hook: fail" >&2\nexit 1\n',
{ mode: 0o755 },
);
const { manager } = yield* makeManager();
const events: GitActionProgressEvent[] = [];
const errorMessage = yield* runStackedAction(
manager,
{
cwd: repoDir,
action: "commit",
},
{
actionId: "action-2",
progressReporter: {
publish: (event) =>
Effect.sync(() => {
events.push(event);
}),
},
},
).pipe(
Effect.flip,
Effect.map((error) => error.message),
);
expect(errorMessage).toContain("hook: fail");
expect(events).toEqual(
expect.arrayContaining([
expect.objectContaining({
kind: "hook_started",
hookName: "pre-commit",
}),
expect.objectContaining({
kind: "action_failed",
phase: "commit",
}),
]),
);
}),
);
});
+67 -265
View File
@@ -2,7 +2,6 @@ import { randomUUID } from "node:crypto";
import { realpathSync } from "node:fs";
import { Effect, FileSystem, Layer, Path } from "effect";
import { GitActionProgressEvent, GitActionProgressPhase, ModelSelection } from "@t3tools/contracts";
import {
resolveAutoFeatureBranchName,
sanitizeBranchFragment,
@@ -10,21 +9,11 @@ import {
} from "@t3tools/shared/git";
import { GitManagerError } from "../Errors.ts";
import {
GitManager,
type GitActionProgressReporter,
type GitManagerShape,
type GitRunStackedActionOptions,
} from "../Services/GitManager.ts";
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
import { GitCore } from "../Services/GitCore.ts";
import { GitHubCli } from "../Services/GitHubCli.ts";
import { TextGeneration } from "../Services/TextGeneration.ts";
const COMMIT_TIMEOUT_MS = 10 * 60_000;
const MAX_PROGRESS_TEXT_LENGTH = 500;
type StripProgressContext<T> = T extends any ? Omit<T, "actionId" | "cwd" | "action"> : never;
type GitActionProgressPayload = StripProgressContext<GitActionProgressEvent>;
interface OpenPrInfo {
number: number;
title: string;
@@ -211,17 +200,6 @@ function sanitizeCommitMessage(generated: {
};
}
function sanitizeProgressText(value: string): string | null {
const trimmed = value.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.length <= MAX_PROGRESS_TEXT_LENGTH) {
return trimmed;
}
return trimmed.slice(0, MAX_PROGRESS_TEXT_LENGTH).trimEnd();
}
interface CommitAndBranchSuggestion {
subject: string;
body: string;
@@ -359,29 +337,6 @@ export const makeGitManager = Effect.gen(function* () {
const gitHubCli = yield* GitHubCli;
const textGeneration = yield* TextGeneration;
const createProgressEmitter = (
input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" },
options?: GitRunStackedActionOptions,
) => {
const actionId = options?.actionId ?? randomUUID();
const reporter = options?.progressReporter;
const emit = (event: GitActionProgressPayload) =>
reporter
? reporter.publish({
actionId,
cwd: input.cwd,
action: input.action,
...event,
} as GitActionProgressEvent)
: Effect.void;
return {
actionId,
emit,
};
};
const configurePullRequestHeadUpstream = (
cwd: string,
pullRequest: ResolvedPullRequest & PullRequestHeadRemoteInfo,
@@ -684,7 +639,7 @@ export const makeGitManager = Effect.gen(function* () {
/** When true, also produce a semantic feature branch name. */
includeBranch?: boolean;
filePaths?: readonly string[];
modelSelection: ModelSelection;
model?: string;
}) =>
Effect.gen(function* () {
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
@@ -711,7 +666,7 @@ export const makeGitManager = Effect.gen(function* () {
stagedSummary: limitContext(context.stagedSummary, 8_000),
stagedPatch: limitContext(context.stagedPatch, 50_000),
...(input.includeBranch ? { includeBranch: true } : {}),
modelSelection: input.modelSelection,
...(input.model ? { model: input.model } : {}),
})
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
@@ -724,112 +679,28 @@ export const makeGitManager = Effect.gen(function* () {
});
const runCommitStep = (
modelSelection: ModelSelection,
cwd: string,
action: "commit" | "commit_push" | "commit_push_pr",
branch: string | null,
commitMessage?: string,
preResolvedSuggestion?: CommitAndBranchSuggestion,
filePaths?: readonly string[],
progressReporter?: GitActionProgressReporter,
actionId?: string,
model?: string,
) =>
Effect.gen(function* () {
const emit = (event: GitActionProgressPayload) =>
progressReporter && actionId
? progressReporter.publish({
actionId,
cwd,
action,
...event,
} as GitActionProgressEvent)
: Effect.void;
let suggestion: CommitAndBranchSuggestion | null | undefined = preResolvedSuggestion;
if (!suggestion) {
const needsGeneration = !commitMessage?.trim();
if (needsGeneration) {
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Generating commit message...",
});
}
suggestion = yield* resolveCommitAndBranchSuggestion({
const suggestion =
preResolvedSuggestion ??
(yield* resolveCommitAndBranchSuggestion({
cwd,
branch,
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
modelSelection,
});
}
...(model ? { model } : {}),
}));
if (!suggestion) {
return { status: "skipped_no_changes" as const };
}
yield* emit({
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
let currentHookName: string | null = null;
const commitProgress =
progressReporter && actionId
? {
onOutputLine: ({ stream, text }: { stream: "stdout" | "stderr"; text: string }) => {
const sanitized = sanitizeProgressText(text);
if (!sanitized) {
return Effect.void;
}
return emit({
kind: "hook_output",
hookName: currentHookName,
stream,
text: sanitized,
});
},
onHookStarted: (hookName: string) => {
currentHookName = hookName;
return emit({
kind: "hook_started",
hookName,
});
},
onHookFinished: ({
hookName,
exitCode,
durationMs,
}: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => {
if (currentHookName === hookName) {
currentHookName = null;
}
return emit({
kind: "hook_finished",
hookName,
exitCode,
durationMs,
});
},
}
: null;
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body, {
timeoutMs: COMMIT_TIMEOUT_MS,
...(commitProgress ? { progress: commitProgress } : {}),
});
if (currentHookName !== null) {
yield* emit({
kind: "hook_finished",
hookName: currentHookName,
exitCode: 0,
durationMs: null,
});
currentHookName = null;
}
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
return {
status: "created" as const,
commitSha,
@@ -837,7 +708,7 @@ export const makeGitManager = Effect.gen(function* () {
};
});
const runPrStep = (modelSelection: ModelSelection, cwd: string, fallbackBranch: string | null) =>
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
Effect.gen(function* () {
const details = yield* gitCore.statusDetails(cwd);
const branch = details.branch ?? fallbackBranch;
@@ -881,7 +752,7 @@ export const makeGitManager = Effect.gen(function* () {
commitSummary: limitContext(rangeContext.commitSummary, 20_000),
diffSummary: limitContext(rangeContext.diffSummary, 20_000),
diffPatch: limitContext(rangeContext.diffPatch, 60_000),
modelSelection,
...(model ? { model } : {}),
});
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
@@ -1102,11 +973,11 @@ export const makeGitManager = Effect.gen(function* () {
);
const runFeatureBranchStep = (
modelSelection: ModelSelection,
cwd: string,
branch: string | null,
commitMessage?: string,
filePaths?: readonly string[],
model?: string,
) =>
Effect.gen(function* () {
const suggestion = yield* resolveCommitAndBranchSuggestion({
@@ -1115,7 +986,7 @@ export const makeGitManager = Effect.gen(function* () {
...(commitMessage ? { commitMessage } : {}),
...(filePaths ? { filePaths } : {}),
includeBranch: true,
modelSelection,
...(model ? { model } : {}),
});
if (!suggestion) {
return yield* gitManagerError(
@@ -1139,135 +1010,66 @@ export const makeGitManager = Effect.gen(function* () {
});
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
function* (input, options) {
const progress = createProgressEmitter(input, options);
const phases: GitActionProgressPhase[] = [
...(input.featureBranch ? (["branch"] as const) : []),
"commit",
...(input.action !== "commit" ? (["push"] as const) : []),
...(input.action === "commit_push_pr" ? (["pr"] as const) : []),
];
let currentPhase: GitActionProgressPhase | null = null;
function* (input) {
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const runAction = Effect.gen(function* () {
yield* progress.emit({
kind: "action_started",
phases,
});
const wantsPush = input.action !== "commit";
const wantsPr = input.action === "commit_push_pr";
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
if (input.featureBranch) {
currentPhase = "branch";
yield* progress.emit({
kind: "phase_started",
phase: "branch",
label: "Preparing feature branch...",
});
const result = yield* runFeatureBranchStep(
input.modelSelection,
input.cwd,
initialStatus.branch,
input.commitMessage,
input.filePaths,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const currentBranch = branchStep.name ?? initialStatus.branch;
currentPhase = "commit";
const commit = yield* runCommitStep(
input.modelSelection,
input.cwd,
input.action,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
input.filePaths,
options?.progressReporter,
progress.actionId,
const initialStatus = yield* gitCore.statusDetails(input.cwd);
if (!input.featureBranch && wantsPush && !initialStatus.branch) {
return yield* gitManagerError("runStackedAction", "Cannot push from detached HEAD.");
}
if (!input.featureBranch && wantsPr && !initialStatus.branch) {
return yield* gitManagerError(
"runStackedAction",
"Cannot create a pull request from detached HEAD.",
);
}
const push = wantsPush
? yield* progress
.emit({
kind: "phase_started",
phase: "push",
label: "Pushing...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "push";
return yield* gitCore.pushCurrentBranch(input.cwd, currentBranch);
}),
),
)
: { status: "skipped_not_requested" as const };
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
let commitMessageForStep = input.commitMessage;
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
const pr = wantsPr
? yield* progress
.emit({
kind: "phase_started",
phase: "pr",
label: "Creating PR...",
})
.pipe(
Effect.flatMap(() =>
Effect.gen(function* () {
currentPhase = "pr";
return yield* runPrStep(input.modelSelection, input.cwd, currentBranch);
}),
),
)
: { status: "skipped_not_requested" as const };
if (input.featureBranch) {
const result = yield* runFeatureBranchStep(
input.cwd,
initialStatus.branch,
input.commitMessage,
input.filePaths,
input.textGenerationModel,
);
branchStep = result.branchStep;
commitMessageForStep = result.resolvedCommitMessage;
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
} else {
branchStep = { status: "skipped_not_requested" as const };
}
const result = {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
yield* progress.emit({
kind: "action_finished",
result,
});
return result;
});
const currentBranch = branchStep.name ?? initialStatus.branch;
return yield* runAction.pipe(
Effect.catch((error) =>
progress
.emit({
kind: "action_failed",
phase: currentPhase,
message: error.message,
})
.pipe(Effect.flatMap(() => Effect.fail(error))),
),
const commit = yield* runCommitStep(
input.cwd,
currentBranch,
commitMessageForStep,
preResolvedCommitSuggestion,
input.filePaths,
input.textGenerationModel,
);
const push = wantsPush
? yield* gitCore.pushCurrentBranch(input.cwd, currentBranch)
: { status: "skipped_not_requested" as const };
const pr = wantsPr
? yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel)
: { status: "skipped_not_requested" as const };
return {
action: input.action,
branch: branchStep,
commit,
push,
pr,
};
},
);
@@ -0,0 +1,59 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, Layer, Schema } from "effect";
import { GitCommandError } from "../Errors.ts";
import { GitServiceLive } from "./GitService.ts";
import { GitService } from "../Services/GitService.ts";
const layer = it.layer(Layer.provideMerge(GitServiceLive, NodeServices.layer));
layer("GitServiceLive", (it) => {
it.effect("runGit executes successful git commands", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.version",
cwd: process.cwd(),
args: ["--version"],
});
assert.equal(result.code, 0);
assert.ok(result.stdout.toLowerCase().includes("git version"));
}),
);
it.effect("runGit can return non-zero exit codes when allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* gitService.execute({
operation: "GitProcess.test.allowNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
allowNonZeroExit: true,
});
assert.notEqual(result.code, 0);
}),
);
it.effect("runGit fails with GitCommandError when non-zero exits are not allowed", () =>
Effect.gen(function* () {
const gitService = yield* GitService;
const result = yield* Effect.result(
gitService.execute({
operation: "GitProcess.test.failOnNonZero",
cwd: process.cwd(),
args: ["rev-parse", "--verify", "__definitely_missing_ref__"],
}),
);
assert.equal(result._tag, "Failure");
if (result._tag === "Failure") {
assert.ok(Schema.is(GitCommandError)(result.failure));
assert.equal(result.failure.operation, "GitProcess.test.failOnNonZero");
assert.equal(result.failure.command, "git rev-parse --verify __definitely_missing_ref__");
}
}),
);
});
+144
View File
@@ -0,0 +1,144 @@
/**
* Git process helpers - Effect-native git execution with typed errors.
*
* Centralizes child-process git invocation for server modules. This module
* only executes git commands and reports structured failures.
*
* @module GitServiceLive
*/
import { Effect, Layer, Option, Schema, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { GitCommandError } from "../Errors.ts";
import {
ExecuteGitInput,
ExecuteGitResult,
GitService,
GitServiceShape,
} from "../Services/GitService.ts";
const DEFAULT_TIMEOUT_MS = 30_000;
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
function quoteGitCommand(args: ReadonlyArray<string>): string {
return `git ${args.join(" ")}`;
}
function toGitCommandError(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
detail: string,
) {
return (cause: unknown) =>
Schema.is(GitCommandError)(cause)
? cause
: new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${cause instanceof Error && cause.message.length > 0 ? cause.message : "Unknown error"} - ${detail}`,
...(cause !== undefined ? { cause } : {}),
});
}
const collectOutput = Effect.fn(function* <E>(
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
stream: Stream.Stream<Uint8Array, E>,
maxOutputBytes: number,
): Effect.fn.Return<string, GitCommandError> {
const decoder = new TextDecoder();
let bytes = 0;
let text = "";
yield* Stream.runForEach(stream, (chunk) =>
Effect.gen(function* () {
bytes += chunk.byteLength;
if (bytes > maxOutputBytes) {
return yield* new GitCommandError({
operation: input.operation,
command: quoteGitCommand(input.args),
cwd: input.cwd,
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
});
}
text += decoder.decode(chunk, { stream: true });
}),
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
text += decoder.decode();
return text;
});
const makeGitService = Effect.gen(function* () {
const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const execute: GitServiceShape["execute"] = Effect.fnUntraced(function* (input) {
const commandInput = {
...input,
args: [...input.args],
} as const;
const timeoutMs = input.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
const commandEffect = Effect.gen(function* () {
const child = yield* commandSpawner
.spawn(
ChildProcess.make("git", commandInput.args, {
cwd: commandInput.cwd,
...(input.env ? { env: input.env } : {}),
}),
)
.pipe(Effect.mapError(toGitCommandError(commandInput, "failed to spawn.")));
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectOutput(commandInput, child.stdout, maxOutputBytes),
collectOutput(commandInput, child.stderr, maxOutputBytes),
child.exitCode.pipe(
Effect.map((value) => Number(value)),
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
),
],
{ concurrency: "unbounded" },
);
if (!input.allowNonZeroExit && exitCode !== 0) {
const trimmedStderr = stderr.trim();
return yield* new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail:
trimmedStderr.length > 0
? `${quoteGitCommand(commandInput.args)} failed: ${trimmedStderr}`
: `${quoteGitCommand(commandInput.args)} failed with code ${exitCode}.`,
});
}
return { code: exitCode, stdout, stderr } satisfies ExecuteGitResult;
});
return yield* commandEffect.pipe(
Effect.scoped,
Effect.timeoutOption(timeoutMs),
Effect.flatMap((result) =>
Option.match(result, {
onNone: () =>
Effect.fail(
new GitCommandError({
operation: commandInput.operation,
command: quoteGitCommand(commandInput.args),
cwd: commandInput.cwd,
detail: `${quoteGitCommand(commandInput.args)} timed out.`,
}),
),
onSome: Effect.succeed,
}),
),
);
});
return {
execute,
} satisfies GitServiceShape;
});
export const GitServiceLive = Layer.effect(GitService, makeGitService);
@@ -1,72 +0,0 @@
/**
* RoutingTextGeneration – Dispatches text generation requests to either the
* Codex CLI or Claude CLI implementation based on the provider in each
* request input.
*
* When `modelSelection.provider` is `"claudeAgent"` the request is forwarded to
* the Claude layer; for any other value (including the default `undefined`) it
* falls through to the Codex layer.
*
* @module RoutingTextGeneration
*/
import { Effect, Layer, ServiceMap } from "effect";
import {
TextGeneration,
type TextGenerationProvider,
type TextGenerationShape,
} from "../Services/TextGeneration.ts";
import { CodexTextGenerationLive } from "./CodexTextGeneration.ts";
import { ClaudeTextGenerationLive } from "./ClaudeTextGeneration.ts";
// ---------------------------------------------------------------------------
// Internal service tags so both concrete layers can coexist.
// ---------------------------------------------------------------------------
class CodexTextGen extends ServiceMap.Service<CodexTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/CodexTextGen",
) {}
class ClaudeTextGen extends ServiceMap.Service<ClaudeTextGen, TextGenerationShape>()(
"t3/git/Layers/RoutingTextGeneration/ClaudeTextGen",
) {}
// ---------------------------------------------------------------------------
// Routing implementation
// ---------------------------------------------------------------------------
const makeRoutingTextGeneration = Effect.gen(function* () {
const codex = yield* CodexTextGen;
const claude = yield* ClaudeTextGen;
const route = (provider?: TextGenerationProvider): TextGenerationShape =>
provider === "claudeAgent" ? claude : codex;
return {
generateCommitMessage: (input) =>
route(input.modelSelection.provider).generateCommitMessage(input),
generatePrContent: (input) => route(input.modelSelection.provider).generatePrContent(input),
generateBranchName: (input) => route(input.modelSelection.provider).generateBranchName(input),
} satisfies TextGenerationShape;
});
const InternalCodexLayer = Layer.effect(
CodexTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(CodexTextGenerationLive));
const InternalClaudeLayer = Layer.effect(
ClaudeTextGen,
Effect.gen(function* () {
const svc = yield* TextGeneration;
return svc;
}),
).pipe(Layer.provide(ClaudeTextGenerationLive));
export const RoutingTextGenerationLive = Layer.effect(
TextGeneration,
makeRoutingTextGeneration,
).pipe(Layer.provide(InternalCodexLayer), Layer.provide(InternalClaudeLayer));
-150
View File
@@ -1,150 +0,0 @@
import { describe, expect, it } from "vitest";
import {
buildBranchNamePrompt,
buildCommitMessagePrompt,
buildPrContentPrompt,
} from "./Prompts.ts";
import { normalizeCliError } from "./Utils.ts";
import { TextGenerationError } from "./Errors.ts";
describe("buildCommitMessagePrompt", () => {
it("includes staged patch and summary in the prompt", () => {
const result = buildCommitMessagePrompt({
branch: "main",
stagedSummary: "M README.md",
stagedPatch: "diff --git a/README.md b/README.md\n+hello",
includeBranch: false,
});
expect(result.prompt).toContain("Staged files:");
expect(result.prompt).toContain("M README.md");
expect(result.prompt).toContain("Staged patch:");
expect(result.prompt).toContain("diff --git a/README.md b/README.md");
expect(result.prompt).toContain("Branch: main");
// Should NOT include the branch generation instruction
expect(result.prompt).not.toContain("branch must be a short semantic git branch fragment");
});
it("includes branch generation instruction when includeBranch is true", () => {
const result = buildCommitMessagePrompt({
branch: "feature/foo",
stagedSummary: "M README.md",
stagedPatch: "diff",
includeBranch: true,
});
expect(result.prompt).toContain("branch must be a short semantic git branch fragment");
expect(result.prompt).toContain("Return a JSON object with keys: subject, body, branch.");
});
it("shows (detached) when branch is null", () => {
const result = buildCommitMessagePrompt({
branch: null,
stagedSummary: "M a.ts",
stagedPatch: "diff",
includeBranch: false,
});
expect(result.prompt).toContain("Branch: (detached)");
});
});
describe("buildPrContentPrompt", () => {
it("includes branch names, commits, and diff in the prompt", () => {
const result = buildPrContentPrompt({
baseBranch: "main",
headBranch: "feature/auth",
commitSummary: "feat: add login page",
diffSummary: "3 files changed",
diffPatch: "diff --git a/auth.ts b/auth.ts\n+export function login()",
});
expect(result.prompt).toContain("Base branch: main");
expect(result.prompt).toContain("Head branch: feature/auth");
expect(result.prompt).toContain("Commits:");
expect(result.prompt).toContain("feat: add login page");
expect(result.prompt).toContain("Diff stat:");
expect(result.prompt).toContain("3 files changed");
expect(result.prompt).toContain("Diff patch:");
expect(result.prompt).toContain("export function login()");
});
});
describe("buildBranchNamePrompt", () => {
it("includes the user message in the prompt", () => {
const result = buildBranchNamePrompt({
message: "Fix the login timeout bug",
});
expect(result.prompt).toContain("User message:");
expect(result.prompt).toContain("Fix the login timeout bug");
expect(result.prompt).not.toContain("Attachment metadata:");
});
it("includes attachment metadata when attachments are provided", () => {
const result = buildBranchNamePrompt({
message: "Fix the layout from screenshot",
attachments: [
{
type: "image" as const,
id: "att-123",
name: "screenshot.png",
mimeType: "image/png",
sizeBytes: 12345,
},
],
});
expect(result.prompt).toContain("Attachment metadata:");
expect(result.prompt).toContain("screenshot.png");
expect(result.prompt).toContain("image/png");
expect(result.prompt).toContain("12345 bytes");
});
});
describe("normalizeCliError", () => {
it("detects 'Command not found' and includes CLI name in the message", () => {
const error = normalizeCliError(
"claude",
"generateCommitMessage",
new Error("Command not found: claude"),
"Something went wrong",
);
expect(error).toBeInstanceOf(TextGenerationError);
expect(error.detail).toContain("Claude CLI");
expect(error.detail).toContain("not available on PATH");
});
it("uses the CLI name from the first argument for codex", () => {
const error = normalizeCliError(
"codex",
"generateBranchName",
new Error("Command not found: codex"),
"Something went wrong",
);
expect(error).toBeInstanceOf(TextGenerationError);
expect(error.detail).toContain("Codex CLI");
expect(error.detail).toContain("not available on PATH");
});
it("returns the error as-is if it is already a TextGenerationError", () => {
const existing = new TextGenerationError({
operation: "generatePrContent",
detail: "Already wrapped",
});
const result = normalizeCliError("claude", "generatePrContent", existing, "fallback");
expect(result).toBe(existing);
});
it("wraps unknown non-Error values with the fallback message", () => {
const result = normalizeCliError("codex", "generateCommitMessage", "string error", "fallback");
expect(result).toBeInstanceOf(TextGenerationError);
expect(result.detail).toBe("fallback");
});
});
-153
View File
@@ -1,153 +0,0 @@
/**
* Shared prompt builders for text generation providers.
*
* Extracts the prompt construction logic that is identical across
* Codex, Claude, and any future CLI-based text generation backends.
*
* @module textGenerationPrompts
*/
import { Schema } from "effect";
import type { ChatAttachment } from "@t3tools/contracts";
import { limitSection } from "./Utils.ts";
// ---------------------------------------------------------------------------
// Commit message
// ---------------------------------------------------------------------------
export interface CommitMessagePromptInput {
branch: string | null;
stagedSummary: string;
stagedPatch: string;
includeBranch: boolean;
}
export function buildCommitMessagePrompt(input: CommitMessagePromptInput) {
const wantsBranch = input.includeBranch;
const prompt = [
"You write concise git commit messages.",
wantsBranch
? "Return a JSON object with keys: subject, body, branch."
: "Return a JSON object with keys: subject, body.",
"Rules:",
"- subject must be imperative, <= 72 chars, and no trailing period",
"- body can be empty string or short bullet points",
...(wantsBranch
? ["- branch must be a short semantic git branch fragment for this change"]
: []),
"- capture the primary user-visible or developer-visible change",
"",
`Branch: ${input.branch ?? "(detached)"}`,
"",
"Staged files:",
limitSection(input.stagedSummary, 6_000),
"",
"Staged patch:",
limitSection(input.stagedPatch, 40_000),
].join("\n");
if (wantsBranch) {
return {
prompt,
outputSchema: Schema.Struct({
subject: Schema.String,
body: Schema.String,
branch: Schema.String,
}),
};
}
return {
prompt,
outputSchema: Schema.Struct({
subject: Schema.String,
body: Schema.String,
}),
};
}
// ---------------------------------------------------------------------------
// PR content
// ---------------------------------------------------------------------------
export interface PrContentPromptInput {
baseBranch: string;
headBranch: string;
commitSummary: string;
diffSummary: string;
diffPatch: string;
}
export function buildPrContentPrompt(input: PrContentPromptInput) {
const prompt = [
"You write GitHub pull request content.",
"Return a JSON object with keys: title, body.",
"Rules:",
"- title should be concise and specific",
"- body must be markdown and include headings '## Summary' and '## Testing'",
"- under Summary, provide short bullet points",
"- under Testing, include bullet points with concrete checks or 'Not run' where appropriate",
"",
`Base branch: ${input.baseBranch}`,
`Head branch: ${input.headBranch}`,
"",
"Commits:",
limitSection(input.commitSummary, 12_000),
"",
"Diff stat:",
limitSection(input.diffSummary, 12_000),
"",
"Diff patch:",
limitSection(input.diffPatch, 40_000),
].join("\n");
const outputSchema = Schema.Struct({
title: Schema.String,
body: Schema.String,
});
return { prompt, outputSchema };
}
// ---------------------------------------------------------------------------
// Branch name
// ---------------------------------------------------------------------------
export interface BranchNamePromptInput {
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
}
export function buildBranchNamePrompt(input: BranchNamePromptInput) {
const attachmentLines = (input.attachments ?? []).map(
(attachment) => `- ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes)`,
);
const promptSections = [
"You generate concise git branch names.",
"Return a JSON object with key: branch.",
"Rules:",
"- Branch should describe the requested work from the user message.",
"- Keep it short and specific (2-6 words).",
"- Use plain words only, no issue prefixes and no punctuation-heavy text.",
"- If images are attached, use them as primary context for visual/UI issues.",
"",
"User message:",
limitSection(input.message, 8_000),
];
if (attachmentLines.length > 0) {
promptSections.push(
"",
"Attachment metadata:",
limitSection(attachmentLines.join("\n"), 4_000),
);
}
const prompt = promptSections.join("\n");
const outputSchema = Schema.Struct({
branch: Schema.String,
});
return { prompt, outputSchema };
}
-52
View File
@@ -24,23 +24,6 @@ import type {
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
readonly progress?: ExecuteGitProgress;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
export interface GitStatusDetails extends Omit<GitStatusResult, "pr"> {
upstreamRef: string | null;
}
@@ -50,35 +33,6 @@ export interface GitPreparedCommitContext {
stagedPatch: string;
}
export interface ExecuteGitProgress {
readonly onStdoutLine?: (line: string) => Effect.Effect<void, never>;
readonly onStderrLine?: (line: string) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitProgress {
readonly onOutputLine?: (input: {
stream: "stdout" | "stderr";
text: string;
}) => Effect.Effect<void, never>;
readonly onHookStarted?: (hookName: string) => Effect.Effect<void, never>;
readonly onHookFinished?: (input: {
hookName: string;
exitCode: number | null;
durationMs: number | null;
}) => Effect.Effect<void, never>;
}
export interface GitCommitOptions {
readonly timeoutMs?: number;
readonly progress?: GitCommitProgress;
}
export interface GitPushResult {
status: "pushed" | "skipped_up_to_date";
branch: string;
@@ -132,11 +86,6 @@ export interface GitSetBranchUpstreamInput {
* GitCoreShape - Service API for low-level Git repository interactions.
*/
export interface GitCoreShape {
/**
* Execute a raw Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
/**
* Read Git status for a repository.
*/
@@ -162,7 +111,6 @@ export interface GitCoreShape {
cwd: string,
subject: string,
body: string,
options?: GitCommitOptions,
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
/**
@@ -7,7 +7,6 @@
* @module GitManager
*/
import {
GitActionProgressEvent,
GitPreparePullRequestThreadInput,
GitPreparePullRequestThreadResult,
GitPullRequestRefInput,
@@ -21,15 +20,6 @@ import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitManagerServiceError } from "../Errors.ts";
export interface GitActionProgressReporter {
readonly publish: (event: GitActionProgressEvent) => Effect.Effect<void, never>;
}
export interface GitRunStackedActionOptions {
readonly actionId?: string;
readonly progressReporter?: GitActionProgressReporter;
}
/**
* GitManagerShape - Service API for high-level Git workflow actions.
*/
@@ -61,7 +51,6 @@ export interface GitManagerShape {
*/
readonly runStackedAction: (
input: GitRunStackedActionInput,
options?: GitRunStackedActionOptions,
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
}
@@ -0,0 +1,45 @@
/**
* GitService - Service for Git command execution.
*
* Uses Effect `ServiceMap.Service` for dependency injection and exposes typed
* domain errors for Git command execution.
*
* @module GitService
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { GitCommandError } from "../Errors.ts";
export interface ExecuteGitInput {
readonly operation: string;
readonly cwd: string;
readonly args: ReadonlyArray<string>;
readonly env?: NodeJS.ProcessEnv;
readonly allowNonZeroExit?: boolean;
readonly timeoutMs?: number;
readonly maxOutputBytes?: number;
}
export interface ExecuteGitResult {
readonly code: number;
readonly stdout: string;
readonly stderr: string;
}
/**
* GitServiceShape - Service API for Git command execution.
*/
export interface GitServiceShape {
/**
* Execute a Git command.
*/
readonly execute: (input: ExecuteGitInput) => Effect.Effect<ExecuteGitResult, GitCommandError>;
}
/**
* GitService - Service for Git command execution.
*/
export class GitService extends ServiceMap.Service<GitService, GitServiceShape>()(
"t3/git/Services/GitService",
) {}
+7 -10
View File
@@ -8,13 +8,10 @@
*/
import { ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ChatAttachment, ModelSelection } from "@t3tools/contracts";
import type { ChatAttachment } 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";
export interface CommitMessageGenerationInput {
cwd: string;
branch: string | null;
@@ -22,8 +19,8 @@ export interface CommitMessageGenerationInput {
stagedPatch: string;
/** When true, the model also returns a semantic branch name for the change. */
includeBranch?: boolean;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface CommitMessageGenerationResult {
@@ -40,8 +37,8 @@ export interface PrContentGenerationInput {
commitSummary: string;
diffSummary: string;
diffPatch: string;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface PrContentGenerationResult {
@@ -53,8 +50,8 @@ export interface BranchNameGenerationInput {
cwd: string;
message: string;
attachments?: ReadonlyArray<ChatAttachment> | undefined;
/** What model and provider to use for generation. */
modelSelection: ModelSelection;
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
model?: string;
}
export interface BranchNameGenerationResult {
-102
View File
@@ -1,102 +0,0 @@
/**
* Shared utilities for text generation layers (Codex, Claude, etc.).
*
* @module textGenerationUtils
*/
import { Schema } from "effect";
import { TextGenerationError } from "./Errors.ts";
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
/** Convert an Effect Schema to a flat JSON Schema object, inlining `$defs` when present. */
export function toJsonSchemaObject(schema: Schema.Top): unknown {
const document = Schema.toJsonSchemaDocument(schema);
if (document.definitions && Object.keys(document.definitions).length > 0) {
return { ...document.schema, $defs: document.definitions };
}
return document.schema;
}
/** Truncate a text section to `maxChars`, appending a `[truncated]` marker when needed. */
export function limitSection(value: string, maxChars: number): string {
if (value.length <= maxChars) return value;
const truncated = value.slice(0, maxChars);
return `${truncated}\n\n[truncated]`;
}
/** Normalise a raw commit subject to imperative-mood, ≤72 chars, no trailing period. */
export function sanitizeCommitSubject(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
const withoutTrailingPeriod = singleLine.replace(/[.]+$/g, "").trim();
if (withoutTrailingPeriod.length === 0) {
return "Update project files";
}
if (withoutTrailingPeriod.length <= 72) {
return withoutTrailingPeriod;
}
return withoutTrailingPeriod.slice(0, 72).trimEnd();
}
/** Normalise a raw PR title to a single line with a sensible fallback. */
export function sanitizePrTitle(raw: string): string {
const singleLine = raw.trim().split(/\r?\n/g)[0]?.trim() ?? "";
if (singleLine.length > 0) {
return singleLine;
}
return "Update project changes";
}
/** CLI name to human-readable label, e.g. "codex" → "Codex CLI (`codex`)" */
function cliLabel(cliName: string): string {
const capitalized = cliName.charAt(0).toUpperCase() + cliName.slice(1);
return `${capitalized} CLI (\`${cliName}\`)`;
}
/**
* Normalize an unknown error from a CLI text generation process into a
* typed `TextGenerationError`. Parameterized by CLI name so both Codex
* and Claude (and future providers) can share the same logic.
*/
export function normalizeCliError(
cliName: string,
operation: string,
error: unknown,
fallback: string,
): TextGenerationError {
if (Schema.is(TextGenerationError)(error)) {
return error;
}
if (error instanceof Error) {
const lower = error.message.toLowerCase();
if (
error.message.includes(`Command not found: ${cliName}`) ||
lower.includes(`spawn ${cliName}`) ||
lower.includes("enoent")
) {
return new TextGenerationError({
operation,
detail: `${cliLabel(cliName)} is required but not available on PATH.`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: `${fallback}: ${error.message}`,
cause: error,
});
}
return new TextGenerationError({
operation,
detail: fallback,
cause: error,
});
}
+6
View File
@@ -0,0 +1,6 @@
import { existsSync } from "node:fs";
import { join } from "node:path";
export function isGitRepository(cwd: string): boolean {
return existsSync(join(cwd, ".git"));
}
+11 -9
View File
@@ -3,7 +3,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertFailure } from "@effect/vitest/utils";
import { Effect, FileSystem, Layer, Logger, Path, Schema } from "effect";
import { ServerConfig } from "./config";
import { ServerConfig, type ServerConfigShape } from "./config";
import {
DEFAULT_KEYBINDINGS,
@@ -17,17 +17,21 @@ import {
} from "./keybindings";
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
const makeKeybindingsLayer = () => {
return KeybindingsLive.pipe(
const makeKeybindingsLayer = () =>
KeybindingsLive.pipe(
Layer.provideMerge(
Layer.fresh(
ServerConfig.layerTest(process.cwd(), {
prefix: "t3code-keybindings-test-",
Layer.effect(
ServerConfig,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const { join } = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-server-config-test-" });
const configPath = join(dir, "keybindings.json");
return { keybindingsConfigPath: configPath } as ServerConfigShape;
}),
),
),
);
};
const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R>) =>
effect.pipe(
@@ -38,9 +42,7 @@ const toDetailResult = <A, R>(effect: Effect.Effect<A, KeybindingsConfigError, R
const writeKeybindingsConfig = (configPath: string, rules: readonly KeybindingRule[]) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const encoded = yield* Schema.encodeEffect(KeybindingsConfigJson)(rules);
yield* fileSystem.makeDirectory(path.dirname(configPath), { recursive: true });
yield* fileSystem.writeFileString(configPath, encoded);
});
+7 -111
View File
@@ -4,9 +4,7 @@ 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 Stream from "effect/Stream";
import * as Command from "effect/unstable/cli/Command";
import { FetchHttpClient } from "effect/unstable/http";
import { beforeEach } from "vitest";
@@ -17,9 +15,7 @@ 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 { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
import { Server, type ServerShape } from "./wsServer";
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings";
const start = vi.fn(() => undefined);
const stop = vi.fn(() => undefined);
@@ -55,13 +51,6 @@ const testLayer = Layer.mergeAll(
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
Layer.succeed(ServerSettingsService, {
start: Effect.void,
ready: Effect.void,
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
streamChanges: Stream.empty,
} satisfies ServerSettingsShape),
AnalyticsService.layerTest,
FetchHttpClient.layer,
NodeServices.layer,
@@ -71,11 +60,13 @@ const runCli = (
args: ReadonlyArray<string>,
env: Record<string, string> = { T3CODE_NO_BROWSER: "true" },
) => {
const uniqueStateDir = `/tmp/t3-cli-state-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`;
return Command.runWith(t3Cli, { version: "0.0.0-test" })(args).pipe(
Effect.provide(
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
T3CODE_STATE_DIR: uniqueStateDir,
...env,
},
}),
@@ -102,8 +93,8 @@ it.layer(testLayer)("server CLI command", (it) => {
"4010",
"--host",
"0.0.0.0",
"--home-dir",
"/tmp/t3-cli-home",
"--state-dir",
"/tmp/t3-cli-state",
"--dev-url",
"http://127.0.0.1:5173",
"--no-browser",
@@ -115,8 +106,7 @@ it.layer(testLayer)("server CLI command", (it) => {
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?.stateDir, "/tmp/t3-cli-state");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://127.0.0.1:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "auth-secret");
@@ -141,7 +131,7 @@ it.layer(testLayer)("server CLI command", (it) => {
T3CODE_MODE: "desktop",
T3CODE_PORT: "4999",
T3CODE_HOST: "100.88.10.4",
T3CODE_HOME: "/tmp/t3-env-home",
T3CODE_STATE_DIR: "/tmp/t3-env-state",
VITE_DEV_SERVER_URL: "http://localhost:5173",
T3CODE_NO_BROWSER: "true",
T3CODE_AUTH_TOKEN: "env-token",
@@ -151,8 +141,7 @@ it.layer(testLayer)("server CLI command", (it) => {
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?.stateDir, "/tmp/t3-env-state");
assert.equal(resolvedConfig?.devUrl?.toString(), "http://localhost:5173/");
assert.equal(resolvedConfig?.noBrowser, true);
assert.equal(resolvedConfig?.authToken, "env-token");
@@ -162,99 +151,6 @@ it.layer(testLayer)("server CLI command", (it) => {
}),
);
const openBootstrapFd = Effect.fn(function* (payload: Record<string, unknown>) {
const fs = yield* FileSystem.FileSystem;
const filePath = yield* fs.makeTempFileScoped({ prefix: "t3-bootstrap-", suffix: ".ndjson" });
yield* fs.writeFileString(filePath, `${JSON.stringify(payload)}\n`);
const { fd } = yield* fs.open(filePath, { flag: "r" });
return fd;
});
it.effect("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));
+44 -148
View File
@@ -11,13 +11,12 @@ 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 { fixPath, resolveStateDir } from "./os-jank";
import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
@@ -27,37 +26,20 @@ 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 stateDir: 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>;
}
@@ -108,12 +90,19 @@ export class CliConfig extends ServiceMap.Service<CliConfig, 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),
Config.map(
Option.match<RuntimeMode, string>({
onNone: () => "web",
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
}),
),
),
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)),
stateDir: Config.string("T3CODE_STATE_DIR").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,
@@ -123,10 +112,6 @@ const CliEnvConfig = Config.all({
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),
@@ -140,14 +125,6 @@ const CliEnvConfig = Config.all({
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,
@@ -161,127 +138,53 @@ const ServerConfigLive = (input: CliInput) =>
),
);
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
bootstrapFd !== undefined
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
: Option.none();
const mode = Option.getOrElse(input.mode, () => env.mode);
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 port = yield* Option.match(input.port, {
onSome: (value) => Effect.succeed(value),
onNone: () => {
if (env.port) {
return Effect.succeed(env.port);
}
if (mode === "desktop") {
return Effect.succeed(DEFAULT_PORT);
}
return findAvailablePort(DEFAULT_PORT);
},
});
const stateDir = yield* resolveStateDir(
Option.getOrUndefined(input.stateDir) ?? env.stateDir,
);
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 devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
input.autoBootstrapProjectFromCwd,
Option.getOrElse(
resolveOptionPrecedence(
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
),
),
() => mode === "web",
),
env.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),
),
env.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 { join } = yield* Path.Path;
const keybindingsConfigPath = join(stateDir, "keybindings.json");
const host =
Option.getOrUndefined(input.host) ??
env.host ??
(mode === "desktop" ? "127.0.0.1" : undefined);
const config: ServerConfigShape = {
mode,
port,
cwd: cliConfig.cwd,
keybindingsConfigPath,
host,
baseDir,
...derivedPaths,
stateDir,
staticDir,
devUrl,
noBrowser,
authToken: Option.getOrUndefined(authToken),
authToken,
autoBootstrapProjectFromCwd,
logWebSocketEvents,
} satisfies ServerConfigShape;
@@ -298,7 +201,6 @@ const LayerLive = (input: CliInput) =>
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerLoggerLive),
Layer.provideMerge(AnalyticsServiceLayerLive),
Layer.provideMerge(ServerSettingsLive),
Layer.provideMerge(ServerConfigLive(input)),
);
@@ -389,7 +291,7 @@ const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
Flag.optional,
);
const portFlag = Flag.integer("port").pipe(
Flag.withSchema(PortSchema),
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
Flag.withDescription("Port for the HTTP/WebSocket server."),
Flag.optional,
);
@@ -397,8 +299,8 @@ 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)."),
const stateDirFlag = Flag.string("state-dir").pipe(
Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
Flag.optional,
);
const devUrlFlag = Flag.string("dev-url").pipe(
@@ -415,11 +317,6 @@ const authTokenFlag = Flag.string("auth-token").pipe(
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.",
@@ -438,11 +335,10 @@ export const t3Cli = Command.make("t3", {
mode: modeFlag,
port: portFlag,
host: hostFlag,
t3Home: t3HomeFlag,
stateDir: stateDirFlag,
devUrl: devUrlFlag,
noBrowser: noBrowserFlag,
authToken: authTokenFlag,
bootstrapFd: bootstrapFdFlag,
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
logWebSocketEvents: logWebSocketEventsFlag,
}).pipe(
@@ -19,7 +19,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { CheckpointStoreLive } from "../../checkpointing/Layers/CheckpointStore.ts";
import { CheckpointStore } from "../../checkpointing/Services/CheckpointStore.ts";
import { GitCoreLive } from "../../git/Layers/GitCore.ts";
import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
@@ -253,16 +252,12 @@ describe("CheckpointReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-checkpoint-reactor-test-",
});
const layer = CheckpointReactorLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(RuntimeReceiptBusLive),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(GitCoreLive))),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(CheckpointStoreLive),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
@@ -282,10 +277,7 @@ describe("CheckpointReactor", () => {
projectId: asProjectId("project-1"),
title: "Test Project",
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -296,10 +288,7 @@ describe("CheckpointReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -24,7 +24,7 @@ import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { RuntimeReceiptBus } from "../Services/RuntimeReceiptBus.ts";
import { CheckpointStoreError } from "../../checkpointing/Errors.ts";
import { OrchestrationDispatchError } from "../Errors.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { isGitRepository } from "../../git/isRepo.ts";
type ReactorInput =
| {
@@ -89,6 +89,7 @@ const make = Effect.gen(function* () {
detail: input.detail,
},
turnId: null,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -113,6 +114,7 @@ const make = Effect.gen(function* () {
detail: input.detail,
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -313,6 +315,7 @@ const make = Effect.gen(function* () {
status: input.status,
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -35,15 +35,12 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
async function createOrchestrationSystem() {
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-engine-test-",
});
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(orchestrationLayer);
@@ -72,10 +69,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -86,10 +80,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -132,10 +123,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-replay"),
title: "Replay Project",
workspaceRoot: "/tmp/project-replay",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -146,10 +134,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-replay"),
projectId: asProjectId("project-replay"),
title: "replay",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -190,10 +175,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-stream"),
title: "Stream Project",
workspaceRoot: "/tmp/project-stream",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -214,10 +196,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-stream"),
projectId: asProjectId("project-stream"),
title: "domain-stream",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -251,10 +230,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-turn-diff"),
title: "Turn Diff Project",
workspaceRoot: "/tmp/project-turn-diff",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -265,10 +241,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
projectId: asProjectId("project-turn-diff"),
title: "Turn diff thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -344,17 +317,13 @@ describe("OrchestrationEngine", () => {
},
};
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-orchestration-engine-test-",
});
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(SqlitePersistenceMemory),
Layer.provideMerge(ServerConfigLayer),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
),
);
@@ -368,10 +337,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-flaky"),
title: "Flaky Project",
workspaceRoot: "/tmp/project-flaky",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -384,10 +350,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
projectId: asProjectId("project-flaky"),
title: "flaky-fail",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -404,10 +367,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
projectId: asProjectId("project-flaky"),
title: "flaky-ok",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -461,10 +421,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-atomic"),
title: "Atomic Project",
workspaceRoot: "/tmp/project-atomic",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -475,10 +432,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-atomic"),
projectId: asProjectId("project-atomic"),
title: "atomic",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -602,10 +556,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-sync"),
title: "Sync Project",
workspaceRoot: "/tmp/project-sync",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -616,10 +567,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-sync"),
projectId: asProjectId("project-sync"),
title: "sync-before",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -687,10 +635,7 @@ describe("OrchestrationEngine", () => {
projectId: asProjectId("project-duplicate"),
title: "Duplicate Project",
workspaceRoot: "/tmp/project-duplicate",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -702,10 +647,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -722,10 +664,7 @@ describe("OrchestrationEngine", () => {
threadId: ThreadId.makeUnsafe("thread-duplicate"),
projectId: asProjectId("project-duplicate"),
title: "duplicate",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
File diff suppressed because it is too large. Load diff
@@ -22,6 +22,10 @@ import {
type ProjectionThreadProposedPlan,
ProjectionThreadProposedPlanRepository,
} from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import {
type ProjectionThreadWorkUnit,
ProjectionThreadWorkUnitRepository,
} from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSessionRepository } from "../../persistence/Services/ProjectionThreadSessions.ts";
import {
type ProjectionTurn,
@@ -34,6 +38,7 @@ import { ProjectionStateRepositoryLive } from "../../persistence/Layers/Projecti
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadWorkUnitRepositoryLive } from "../../persistence/Layers/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSessionRepositoryLive } from "../../persistence/Layers/ProjectionThreadSessions.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionThreadRepositoryLive } from "../../persistence/Layers/ProjectionThreads.ts";
@@ -55,6 +60,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
threadMessages: "projection.thread-messages",
threadProposedPlans: "projection.thread-proposed-plans",
threadActivities: "projection.thread-activities",
threadWorkUnits: "projection.thread-work-units",
threadSessions: "projection.thread-sessions",
threadTurns: "projection.thread-turns",
checkpoints: "projection.checkpoints",
@@ -214,6 +220,28 @@ function retainProjectionProposedPlansAfterRevert(
);
}
function retainProjectionWorkUnitsAfterRevert(
workUnits: ReadonlyArray<ProjectionThreadWorkUnit>,
turns: ReadonlyArray<ProjectionTurn>,
turnCount: number,
): ReadonlyArray<ProjectionThreadWorkUnit> {
const retainedTurnIds = new Set<string>(
turns
.filter(
(turn) =>
turn.turnId !== null &&
turn.checkpointTurnCount !== null &&
turn.checkpointTurnCount <= turnCount,
)
.flatMap((turn) => (turn.turnId === null ? [] : [turn.turnId])),
);
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
const retainedIds = new Set(retained.map((workUnit) => workUnit.workUnitId));
return retained.filter(
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
);
}
function collectThreadAttachmentRelativePaths(
threadId: string,
messages: ReadonlyArray<ProjectionThreadMessage>,
@@ -243,7 +271,7 @@ const runAttachmentSideEffects = Effect.fn(function* (sideEffects: AttachmentSid
const fileSystem = yield* Effect.service(FileSystem.FileSystem);
const path = yield* Effect.service(Path.Path);
const attachmentsRootDir = serverConfig.attachmentsDir;
const attachmentsRootDir = path.join(serverConfig.stateDir, "attachments");
yield* Effect.forEach(
sideEffects.deletedThreadIds,
@@ -346,6 +374,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
const projectionThreadMessageRepository = yield* ProjectionThreadMessageRepository;
const projectionThreadProposedPlanRepository = yield* ProjectionThreadProposedPlanRepository;
const projectionThreadActivityRepository = yield* ProjectionThreadActivityRepository;
const projectionThreadWorkUnitRepository = yield* ProjectionThreadWorkUnitRepository;
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
@@ -362,7 +391,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
projectId: event.payload.projectId,
title: event.payload.title,
workspaceRoot: event.payload.workspaceRoot,
defaultModelSelection: event.payload.defaultModelSelection,
defaultModel: event.payload.defaultModel,
scripts: event.payload.scripts,
createdAt: event.payload.createdAt,
updatedAt: event.payload.updatedAt,
@@ -383,8 +412,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
...(event.payload.workspaceRoot !== undefined
? { workspaceRoot: event.payload.workspaceRoot }
: {}),
...(event.payload.defaultModelSelection !== undefined
? { defaultModelSelection: event.payload.defaultModelSelection }
...(event.payload.defaultModel !== undefined
? { defaultModel: event.payload.defaultModel }
: {}),
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
updatedAt: event.payload.updatedAt,
@@ -420,7 +449,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
threadId: event.payload.threadId,
projectId: event.payload.projectId,
title: event.payload.title,
modelSelection: event.payload.modelSelection,
model: event.payload.model,
runtimeMode: event.payload.runtimeMode,
interactionMode: event.payload.interactionMode,
branch: event.payload.branch,
@@ -442,9 +471,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
yield* projectionThreadRepository.upsert({
...existingRow.value,
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
: {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
...(event.payload.worktreePath !== undefined
? { worktreePath: event.payload.worktreePath }
@@ -707,6 +734,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
activityId: event.payload.activity.id,
threadId: event.payload.threadId,
turnId: event.payload.activity.turnId,
workUnitId: event.payload.activity.workUnitId,
tone: event.payload.activity.tone,
kind: event.payload.activity.kind,
summary: event.payload.activity.summary,
@@ -750,6 +778,64 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
}
});
const applyThreadWorkUnitsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
) =>
Effect.gen(function* () {
switch (event.type) {
case "thread.work-unit-upserted":
yield* projectionThreadWorkUnitRepository.upsert({
workUnitId: event.payload.workUnit.id,
threadId: event.payload.threadId,
turnId: event.payload.workUnit.turnId,
parentWorkUnitId: event.payload.workUnit.parentWorkUnitId,
kind: event.payload.workUnit.kind,
state: event.payload.workUnit.state,
title: event.payload.workUnit.title,
detail: event.payload.workUnit.detail,
spawnedByActivityId: event.payload.workUnit.spawnedByActivityId,
...(event.payload.workUnit.providerRefs !== undefined
? { providerRefs: event.payload.workUnit.providerRefs }
: {}),
startedAt: event.payload.workUnit.startedAt,
updatedAt: event.payload.workUnit.updatedAt,
completedAt: event.payload.workUnit.completedAt,
});
return;
case "thread.reverted": {
const existingRows = yield* projectionThreadWorkUnitRepository.listByThreadId({
threadId: event.payload.threadId,
});
if (existingRows.length === 0) {
return;
}
const existingTurns = yield* projectionTurnRepository.listByThreadId({
threadId: event.payload.threadId,
});
const keptRows = retainProjectionWorkUnitsAfterRevert(
existingRows,
existingTurns,
event.payload.turnCount,
);
if (keptRows.length === existingRows.length) {
return;
}
yield* projectionThreadWorkUnitRepository.deleteByThreadId({
threadId: event.payload.threadId,
});
yield* Effect.forEach(keptRows, projectionThreadWorkUnitRepository.upsert, {
concurrency: 1,
}).pipe(Effect.asVoid);
return;
}
default:
return;
}
});
const applyThreadSessionsProjection: ProjectorDefinition["apply"] = (
event,
_attachmentSideEffects,
@@ -1136,6 +1222,10 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
name: ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
apply: applyThreadActivitiesProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
apply: applyThreadWorkUnitsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
apply: applyThreadSessionsProjection,
@@ -1253,6 +1343,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
Layer.provideMerge(ProjectionThreadMessageRepositoryLive),
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
Layer.provideMerge(ProjectionThreadWorkUnitRepositoryLive),
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
Layer.provideMerge(ProjectionTurnRepositoryLive),
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
@@ -1,4 +1,12 @@
import { CheckpointRef, EventId, MessageId, ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
WorkUnitId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -13,6 +21,7 @@ const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.makeUnsafe(value);
const asWorkUnitId = (value: string): WorkUnitId => WorkUnitId.makeUnsafe(value);
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
@@ -34,7 +43,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
project_id,
title,
workspace_root,
default_model_selection_json,
default_model,
scripts_json,
created_at,
updated_at,
@@ -44,7 +53,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'project-1',
'Project 1',
'/tmp/project-1',
'{"provider":"codex","model":"gpt-5-codex"}',
'gpt-5-codex',
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
'2026-02-24T00:00:00.000Z',
'2026-02-24T00:00:01.000Z',
@@ -57,7 +66,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
thread_id,
project_id,
title,
model_selection_json,
model,
branch,
worktree_path,
latest_turn_id,
@@ -69,7 +78,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'thread-1',
'project-1',
'Thread 1',
'{"provider":"codex","model":"gpt-5-codex"}',
'gpt-5-codex',
NULL,
NULL,
'turn-1',
@@ -130,6 +139,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
activity_id,
thread_id,
turn_id,
work_unit_id,
tone,
kind,
summary,
@@ -140,6 +150,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
'activity-1',
'thread-1',
'turn-1',
'wu:thread-1:turn:turn-1:root',
'info',
'runtime.note',
'provider started',
@@ -148,6 +159,39 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
)
`;
yield* sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
VALUES (
'wu:thread-1:turn:turn-1:root',
'thread-1',
'turn-1',
NULL,
'primary_agent',
'completed',
'Primary agent',
NULL,
NULL,
'{"providerTurnId":"provider-turn-1"}',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z',
'2026-02-24T00:00:08.000Z'
)
`;
yield* sql`
INSERT INTO projection_thread_sessions (
thread_id,
@@ -234,10 +278,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: asProjectId("project-1"),
title: "Project 1",
workspaceRoot: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
scripts: [
{
id: "script-1",
@@ -257,10 +298,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
id: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread 1",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "default",
runtimeMode: "full-access",
branch: null,
@@ -310,9 +348,28 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
summary: "provider started",
payload: { stage: "start" },
turnId: asTurnId("turn-1"),
workUnitId: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
createdAt: "2026-02-24T00:00:06.000Z",
},
],
workUnits: [
{
id: asWorkUnitId("wu:thread-1:turn:turn-1:root"),
turnId: asTurnId("turn-1"),
parentWorkUnitId: null,
kind: "primary_agent",
state: "completed",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: "2026-02-24T00:00:08.000Z",
updatedAt: "2026-02-24T00:00:08.000Z",
completedAt: "2026-02-24T00:00:08.000Z",
},
],
checkpoints: [
{
turnId: asTurnId("turn-1"),
@@ -17,7 +17,7 @@ import {
type OrchestrationSession,
type OrchestrationThread,
type OrchestrationThreadActivity,
ModelSelection,
type OrchestrationWorkUnit,
} from "@t3tools/contracts";
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
@@ -35,6 +35,7 @@ import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadWorkUnit } from "../../persistence/Services/ProjectionThreadWorkUnits.ts";
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
@@ -46,7 +47,6 @@ import {
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
Struct.assign({
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
);
@@ -57,17 +57,20 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
}),
);
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
}),
);
const ProjectionThreadDbRowSchema = ProjectionThread;
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
Struct.assign({
payload: Schema.fromJsonString(Schema.Unknown),
sequence: Schema.NullOr(NonNegativeInt),
}),
);
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
Struct.assign({
providerRefs: Schema.NullOr(
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
),
}),
);
const ProjectionThreadSessionDbRowSchema = ProjectionThreadSession;
const ProjectionCheckpointDbRowSchema = ProjectionCheckpoint.mapFields(
Struct.assign({
@@ -93,6 +96,7 @@ const REQUIRED_SNAPSHOT_PROJECTORS = [
ORCHESTRATION_PROJECTOR_NAMES.threadMessages,
ORCHESTRATION_PROJECTOR_NAMES.threadProposedPlans,
ORCHESTRATION_PROJECTOR_NAMES.threadActivities,
ORCHESTRATION_PROJECTOR_NAMES.threadWorkUnits,
ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
ORCHESTRATION_PROJECTOR_NAMES.checkpoints,
] as const;
@@ -147,7 +151,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_model AS "defaultModel",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -166,7 +170,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
model,
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
@@ -228,6 +232,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
work_unit_id AS "workUnitId",
tone,
kind,
summary,
@@ -244,6 +249,30 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
const listThreadWorkUnitRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadWorkUnitDbRowSchema,
execute: () =>
sql`
SELECT
work_unit_id AS "workUnitId",
thread_id AS "threadId",
turn_id AS "turnId",
parent_work_unit_id AS "parentWorkUnitId",
kind,
state,
title,
detail,
spawned_by_activity_id AS "spawnedByActivityId",
provider_refs_json AS "providerRefs",
started_at AS "startedAt",
updated_at AS "updatedAt",
completed_at AS "completedAt"
FROM projection_thread_work_units
ORDER BY thread_id ASC, started_at ASC, work_unit_id ASC
`,
});
const listThreadSessionRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionThreadSessionDbRowSchema,
@@ -328,6 +357,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messageRows,
proposedPlanRows,
activityRows,
workUnitRows,
sessionRows,
checkpointRows,
latestTurnRows,
@@ -373,6 +403,14 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadWorkUnitRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:query",
"ProjectionSnapshotQuery.getSnapshot:listThreadWorkUnits:decodeRows",
),
),
),
listThreadSessionRows(undefined).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
@@ -410,6 +448,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
const messagesByThread = new Map<string, Array<OrchestrationMessage>>();
const proposedPlansByThread = new Map<string, Array<OrchestrationProposedPlan>>();
const activitiesByThread = new Map<string, Array<OrchestrationThreadActivity>>();
const workUnitsByThread = new Map<string, Array<OrchestrationWorkUnit>>();
const checkpointsByThread = new Map<string, Array<OrchestrationCheckpointSummary>>();
const sessionsByThread = new Map<string, OrchestrationSession>();
const latestTurnByThread = new Map<string, OrchestrationLatestTurn>();
@@ -467,12 +506,33 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
summary: row.summary,
payload: row.payload,
turnId: row.turnId,
workUnitId: row.workUnitId,
...(row.sequence !== null ? { sequence: row.sequence } : {}),
createdAt: row.createdAt,
});
activitiesByThread.set(row.threadId, threadActivities);
}
for (const row of workUnitRows) {
updatedAt = maxIso(updatedAt, row.updatedAt);
const threadWorkUnits = workUnitsByThread.get(row.threadId) ?? [];
threadWorkUnits.push({
id: row.workUnitId,
turnId: row.turnId,
parentWorkUnitId: row.parentWorkUnitId,
kind: row.kind,
state: row.state,
title: row.title,
detail: row.detail,
spawnedByActivityId: row.spawnedByActivityId,
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
startedAt: row.startedAt,
updatedAt: row.updatedAt,
completedAt: row.completedAt,
});
workUnitsByThread.set(row.threadId, threadWorkUnits);
}
for (const row of checkpointRows) {
updatedAt = maxIso(updatedAt, row.completedAt);
const threadCheckpoints = checkpointsByThread.get(row.threadId) ?? [];
@@ -537,22 +597,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
});
}
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
id: row.projectId,
title: row.title,
workspaceRoot: row.workspaceRoot,
defaultModelSelection: row.defaultModelSelection,
defaultModel: row.defaultModel,
scripts: row.scripts,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
}));
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
id: row.threadId,
projectId: row.projectId,
title: row.title,
modelSelection: row.modelSelection,
model: row.model,
runtimeMode: row.runtimeMode,
interactionMode: row.interactionMode,
branch: row.branch,
@@ -564,6 +624,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
messages: messagesByThread.get(row.threadId) ?? [],
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
activities: activitiesByThread.get(row.threadId) ?? [],
workUnits: workUnitsByThread.get(row.threadId) ?? [],
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
session: sessionsByThread.get(row.threadId) ?? null,
}));
@@ -2,7 +2,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
import {
ApprovalRequestId,
CommandId,
@@ -16,7 +16,7 @@ import {
import { Effect, Exit, Layer, ManagedRuntime, PubSub, Scope, Stream } from "effect";
import { afterEach, describe, expect, it, vi } from "vitest";
import { deriveServerPaths, ServerConfig } from "../../config.ts";
import { ServerConfig } from "../../config.ts";
import { TextGenerationError } from "../../git/Errors.ts";
import { ProviderAdapterRequestError } from "../../provider/Errors.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
@@ -34,7 +34,6 @@ import { ProviderCommandReactorLive } from "./ProviderCommandReactor.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderCommandReactor } from "../Services/ProviderCommandReactor.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { ServerSettingsService } from "../../serverSettings.ts";
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asApprovalRequestId = (value: string): ApprovalRequestId =>
@@ -42,9 +41,6 @@ const asApprovalRequestId = (value: string): ApprovalRequestId =>
const asMessageId = (value: string): MessageId => MessageId.makeUnsafe(value);
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)));
async function waitFor(
predicate: () => boolean | Promise<boolean>,
timeoutMs = 2000,
@@ -71,7 +67,6 @@ describe("ProviderCommandReactor", () => {
> | null = null;
let scope: Scope.Closeable | null = null;
const createdStateDirs = new Set<string>();
const createdBaseDirs = new Set<string>();
afterEach(async () => {
if (scope) {
@@ -86,35 +81,39 @@ describe("ProviderCommandReactor", () => {
fs.rmSync(stateDir, { recursive: true, force: true });
}
createdStateDirs.clear();
for (const baseDir of createdBaseDirs) {
fs.rmSync(baseDir, { recursive: true, force: true });
}
createdBaseDirs.clear();
});
async function createHarness(input?: {
readonly baseDir?: string;
readonly threadModelSelection?: ModelSelection;
readonly sessionModelSwitch?: "unsupported" | "in-session";
readonly stateDir?: string;
readonly threadModel?: string;
}) {
const now = new Date().toISOString();
const baseDir = input?.baseDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
createdBaseDirs.add(baseDir);
const { stateDir } = deriveServerPathsSync(baseDir, undefined);
const stateDir = input?.stateDir ?? fs.mkdtempSync(path.join(os.tmpdir(), "t3code-reactor-"));
const threadModel = input?.threadModel ?? "gpt-5-codex";
createdStateDirs.add(stateDir);
const runtimeEventPubSub = Effect.runSync(PubSub.unbounded<ProviderRuntimeEvent>());
let nextSessionIndex = 1;
const runtimeSessions: Array<ProviderSession> = [];
const modelSelection = input?.threadModelSelection ?? {
provider: "codex",
model: "gpt-5-codex",
};
const startSession = vi.fn((_: unknown, input: unknown) => {
const sessionIndex = nextSessionIndex++;
const provider =
typeof input === "object" &&
input !== null &&
"provider" in input &&
(input.provider === "codex" || input.provider === "claudeAgent")
? input.provider
: "codex";
const resumeCursor =
typeof input === "object" && input !== null && "resumeCursor" in input
? input.resumeCursor
: undefined;
const model =
typeof input === "object" &&
input !== null &&
"model" in input &&
typeof input.model === "string"
? input.model
: undefined;
const threadId =
typeof input === "object" &&
input !== null &&
@@ -123,7 +122,7 @@ describe("ProviderCommandReactor", () => {
? ThreadId.makeUnsafe(input.threadId)
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
const session: ProviderSession = {
provider: modelSelection.provider,
provider,
status: "ready" as const,
runtimeMode:
typeof input === "object" &&
@@ -132,7 +131,7 @@ describe("ProviderCommandReactor", () => {
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
? input.runtimeMode
: "full-access",
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
...(model !== undefined ? { model } : {}),
threadId,
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
createdAt: now,
@@ -194,9 +193,9 @@ describe("ProviderCommandReactor", () => {
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
stopSession: stopSession as ProviderServiceShape["stopSession"],
listSessions: () => Effect.succeed(runtimeSessions),
getCapabilities: (_provider) =>
getCapabilities: (provider) =>
Effect.succeed({
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
}),
rollbackConversation: () => unsupported(),
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
@@ -215,8 +214,7 @@ describe("ProviderCommandReactor", () => {
Layer.provideMerge(
Layer.succeed(TextGeneration, { generateBranchName } as unknown as TextGenerationShape),
),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), stateDir)),
Layer.provideMerge(NodeServices.layer),
);
const runtime = ManagedRuntime.make(layer);
@@ -234,7 +232,7 @@ describe("ProviderCommandReactor", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot: "/tmp/provider-project",
defaultModelSelection: modelSelection,
defaultModel: threadModel,
createdAt: now,
}),
);
@@ -245,7 +243,7 @@ describe("ProviderCommandReactor", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: modelSelection,
model: threadModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -295,10 +293,7 @@ describe("ProviderCommandReactor", () => {
expect(harness.startSession.mock.calls[0]?.[0]).toEqual(ThreadId.makeUnsafe("thread-1"));
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
cwd: "/tmp/provider-project",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "approval-required",
});
@@ -323,10 +318,10 @@ describe("ProviderCommandReactor", () => {
text: "hello fast mode",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -340,10 +335,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -351,10 +345,9 @@ describe("ProviderCommandReactor", () => {
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -363,9 +356,7 @@ describe("ProviderCommandReactor", () => {
});
it("forwards claude effort options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
});
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
@@ -379,10 +370,10 @@ describe("ProviderCommandReactor", () => {
text: "hello with effort",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
@@ -395,20 +386,19 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
@@ -416,9 +406,7 @@ describe("ProviderCommandReactor", () => {
});
it("forwards claude fast mode options through session start and turn send", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
});
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
@@ -432,10 +420,10 @@ describe("ProviderCommandReactor", () => {
text: "hello with fast mode",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
@@ -448,20 +436,19 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 1);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
provider: "claudeAgent",
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
});
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
model: "claude-opus-4-6",
modelOptions: {
claudeAgent: {
fastMode: true,
},
},
@@ -507,9 +494,7 @@ describe("ProviderCommandReactor", () => {
});
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
});
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
@@ -523,10 +508,7 @@ describe("ProviderCommandReactor", () => {
text: "hello claude",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -560,53 +542,49 @@ describe("ProviderCommandReactor", () => {
});
});
it("preserves the active session model when in-session model switching is unsupported", async () => {
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
it("rejects a turn when the requested model belongs to a different provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
commandId: CommandId.makeUnsafe("cmd-turn-start-model-provider-mismatch"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-1"),
messageId: asMessageId("user-message-model-provider-mismatch"),
role: "user",
text: "first",
text: "hello",
attachments: [],
},
model: "claude-sonnet-4-6",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
return (
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
false
);
});
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.turn.start",
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-2"),
threadId: ThreadId.makeUnsafe("thread-1"),
message: {
messageId: asMessageId("user-message-unsupported-2"),
role: "user",
text: "second",
attachments: [],
},
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
}),
);
expect(harness.startSession).not.toHaveBeenCalled();
expect(harness.sendTurn).not.toHaveBeenCalled();
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.sendTurn.mock.calls[1]?.[0]).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(
thread?.activities.find((activity) => activity.kind === "provider.turn.start.failed"),
).toMatchObject({
payload: {
detail: expect.stringContaining("does not belong to provider 'codex'"),
},
});
});
@@ -658,9 +636,7 @@ describe("ProviderCommandReactor", () => {
});
it("restarts claude sessions when claude effort changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
});
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
const now = new Date().toISOString();
await Effect.runPromise(
@@ -674,10 +650,10 @@ describe("ProviderCommandReactor", () => {
text: "first claude turn",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "medium",
},
},
@@ -701,10 +677,10 @@ describe("ProviderCommandReactor", () => {
text: "second claude turn",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
@@ -717,11 +693,9 @@ describe("ProviderCommandReactor", () => {
await waitFor(() => harness.startSession.mock.calls.length === 2);
await waitFor(() => harness.sendTurn.mock.calls.length === 2);
expect(harness.startSession.mock.calls[1]?.[1]).toMatchObject({
resumeCursor: { opaque: "resume-1" },
modelSelection: {
provider: "claudeAgent",
model: "claude-sonnet-4-6",
options: {
provider: "claudeAgent",
modelOptions: {
claudeAgent: {
effort: "max",
},
},
@@ -815,51 +789,6 @@ describe("ProviderCommandReactor", () => {
expect(thread?.session?.runtimeMode).toBe("approval-required");
});
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
const harness = await createHarness({
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
});
const now = new Date().toISOString();
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-runtime-mode-claude"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "ready",
providerName: "claudeAgent",
runtimeMode: "full-access",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.runtime-mode.set",
commandId: CommandId.makeUnsafe("cmd-runtime-mode-set-claude-no-options"),
threadId: ThreadId.makeUnsafe("thread-1"),
runtimeMode: "approval-required",
createdAt: now,
}),
);
await waitFor(() => harness.startSession.mock.calls.length === 1);
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
runtimeMode: "approval-required",
});
});
it("rejects provider changes after a thread is already bound to a session provider", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -895,10 +824,7 @@ describe("ProviderCommandReactor", () => {
text: "second",
attachments: [],
},
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
provider: "claudeAgent",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -1171,6 +1097,7 @@ describe("ProviderCommandReactor", () => {
requestKind: "command",
},
turnId: null,
workUnitId: null,
createdAt: now,
},
createdAt: now,
@@ -1209,7 +1136,6 @@ describe("ProviderCommandReactor", () => {
expect(failureActivity).toBeDefined();
expect(failureActivity?.payload).toMatchObject({
requestId: "approval-request-1",
detail: expect.stringContaining("Stale pending approval request: approval-request-1"),
});
const resolvedActivity = thread?.activities.find(
@@ -1222,117 +1148,6 @@ describe("ProviderCommandReactor", () => {
expect(resolvedActivity).toBeUndefined();
});
it("surfaces stale provider user-input failures without faking user-input resolution", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.respondToUserInput.mockImplementation(() =>
Effect.fail(
new ProviderAdapterRequestError({
provider: "claudeAgent",
method: "item/tool/respondToUserInput",
detail: "Unknown pending user-input request: user-input-request-1",
}),
),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.session.set",
commandId: CommandId.makeUnsafe("cmd-session-set-for-user-input-error"),
threadId: ThreadId.makeUnsafe("thread-1"),
session: {
threadId: ThreadId.makeUnsafe("thread-1"),
status: "running",
providerName: "claudeAgent",
runtimeMode: "approval-required",
activeTurnId: null,
lastError: null,
updatedAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.activity.append",
commandId: CommandId.makeUnsafe("cmd-user-input-requested"),
threadId: ThreadId.makeUnsafe("thread-1"),
activity: {
id: EventId.makeUnsafe("activity-user-input-requested"),
tone: "info",
kind: "user-input.requested",
summary: "User input requested",
payload: {
requestId: "user-input-request-1",
questions: [
{
id: "sandbox_mode",
header: "Sandbox",
question: "Which mode should be used?",
options: [
{
label: "workspace-write",
description: "Allow workspace writes only",
},
],
},
],
},
turnId: null,
createdAt: now,
},
createdAt: now,
}),
);
await Effect.runPromise(
harness.engine.dispatch({
type: "thread.user-input.respond",
commandId: CommandId.makeUnsafe("cmd-user-input-respond-stale"),
threadId: ThreadId.makeUnsafe("thread-1"),
requestId: asApprovalRequestId("user-input-request-1"),
answers: {
sandbox_mode: "workspace-write",
},
createdAt: now,
}),
);
await waitFor(async () => {
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find(
(entry) => entry.id === ThreadId.makeUnsafe("thread-1"),
);
if (!thread) return false;
return thread.activities.some(
(activity) => activity.kind === "provider.user-input.respond.failed",
);
});
const readModel = await Effect.runPromise(harness.engine.getReadModel());
const thread = readModel.threads.find((entry) => entry.id === ThreadId.makeUnsafe("thread-1"));
expect(thread).toBeDefined();
const failureActivity = thread?.activities.find(
(activity) => activity.kind === "provider.user-input.respond.failed",
);
expect(failureActivity).toBeDefined();
expect(failureActivity?.payload).toMatchObject({
requestId: "user-input-request-1",
detail: expect.stringContaining("Stale pending user-input request: user-input-request-1"),
});
const resolvedActivity = thread?.activities.find(
(activity) =>
activity.kind === "user-input.resolved" &&
typeof activity.payload === "object" &&
activity.payload !== null &&
(activity.payload as Record<string, unknown>).requestId === "user-input-request-1",
);
expect(resolvedActivity).toBeUndefined();
});
it("reacts to thread.session.stop by stopping provider session and clearing thread session state", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -1,17 +1,19 @@
import {
type ChatAttachment,
CommandId,
DEFAULT_GIT_TEXT_GENERATION_MODEL,
EventId,
type ModelSelection,
type OrchestrationEvent,
type ProviderModelOptions,
ProviderKind,
type ProviderStartOptions,
type OrchestrationSession,
ThreadId,
type ProviderSession,
type RuntimeMode,
type TurnId,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
import { Cache, Cause, Duration, Effect, Layer, Option, Schema, Stream } from "effect";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
@@ -24,7 +26,7 @@ import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService, deriveProviderStartOptions } from "../../serverSettings.ts";
import { inferProviderForModel } from "@t3tools/shared/model";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -74,6 +76,11 @@ const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
const WORKTREE_BRANCH_PREFIX = "t3code";
const TEMP_WORKTREE_BRANCH_PATTERN = new RegExp(`^${WORKTREE_BRANCH_PREFIX}\\/[0-9a-f]{8}$`);
const sameModelOptions = (
left: ProviderModelOptions | undefined,
right: ProviderModelOptions | undefined,
): boolean => JSON.stringify(left ?? null) === JSON.stringify(right ?? null);
function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
@@ -90,21 +97,6 @@ function isUnknownPendingApprovalRequestError(cause: Cause.Cause<ProviderService
);
}
function isUnknownPendingUserInputRequestError(cause: Cause.Cause<ProviderServiceError>): boolean {
const error = Cause.squash(cause);
if (Schema.is(ProviderAdapterRequestError)(error)) {
return error.detail.toLowerCase().includes("unknown pending user-input request");
}
return Cause.pretty(cause).toLowerCase().includes("unknown pending user-input request");
}
function stalePendingRequestDetail(
requestKind: "approval" | "user-input",
requestId: string,
): string {
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
}
function isTemporaryWorktreeBranch(branch: string): boolean {
return TEMP_WORKTREE_BRANCH_PATTERN.test(branch.trim().toLowerCase());
}
@@ -137,7 +129,6 @@ const make = Effect.gen(function* () {
const providerService = yield* ProviderService;
const git = yield* GitCore;
const textGeneration = yield* TextGeneration;
const serverSettingsService = yield* ServerSettingsService;
const handledTurnStartKeys = yield* Cache.make<string, true>({
capacity: HANDLED_TURN_START_KEY_MAX,
timeToLive: HANDLED_TURN_START_KEY_TTL,
@@ -151,7 +142,8 @@ const make = Effect.gen(function* () {
),
);
const threadModelSelections = new Map<string, ModelSelection>();
const threadProviderOptions = new Map<string, ProviderStartOptions>();
const threadModelOptions = new Map<string, ProviderModelOptions>();
const appendProviderFailureActivity = (input: {
readonly threadId: ThreadId;
@@ -181,6 +173,7 @@ const make = Effect.gen(function* () {
...(input.requestId ? { requestId: input.requestId } : {}),
},
turnId: input.turnId,
workUnitId: null,
createdAt: input.createdAt,
},
createdAt: input.createdAt,
@@ -208,7 +201,10 @@ const make = Effect.gen(function* () {
threadId: ThreadId,
createdAt: string,
options?: {
readonly modelSelection?: ModelSelection;
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
},
) {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -223,20 +219,26 @@ const make = Effect.gen(function* () {
)
? thread.session.providerName
: undefined;
const requestedModelSelection = options?.modelSelection;
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
const threadProvider: ProviderKind = currentProvider ?? inferProviderForModel(thread.model);
if (options?.provider !== undefined && options.provider !== threadProvider) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${options.provider}'.`,
});
}
if (
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== threadProvider
options?.model !== undefined &&
inferProviderForModel(options.model, threadProvider) !== threadProvider
) {
return yield* new ProviderAdapterRequestError({
provider: threadProvider,
method: "thread.turn.start",
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
});
}
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
const desiredModel = options?.model ?? thread.model;
const effectiveCwd = resolveThreadWorkspaceCwd({
thread,
projects: readModel.projects,
@@ -251,18 +253,19 @@ const make = Effect.gen(function* () {
readonly resumeCursor?: unknown;
readonly provider?: ProviderKind;
}) =>
Effect.gen(function* () {
const serverSettings = yield* serverSettingsService.getSettings;
const providerOptions = deriveProviderStartOptions(serverSettings);
return yield* providerService.startSession(threadId, {
threadId,
...(preferredProvider ? { provider: preferredProvider } : {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
modelSelection: desiredModelSelection,
...(providerOptions !== undefined ? { providerOptions } : {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
providerService.startSession(threadId, {
threadId,
...((input?.provider ?? preferredProvider)
? { provider: input?.provider ?? preferredProvider }
: {}),
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
...(desiredModel ? { model: desiredModel } : {}),
...(options?.modelOptions !== undefined ? { modelOptions: options.modelOptions } : {}),
...(options?.providerOptions !== undefined
? { providerOptions: options.providerOptions }
: {}),
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
runtimeMode: desiredRuntimeMode,
});
const bindSessionToThread = (session: ProviderSession) =>
@@ -286,53 +289,51 @@ const make = Effect.gen(function* () {
if (existingSessionThreadId) {
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
const providerChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.provider !== currentProvider;
options?.provider !== undefined && options.provider !== currentProvider;
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
const sessionModelSwitch =
currentProvider === undefined
? "in-session"
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
const modelChanged =
requestedModelSelection !== undefined &&
requestedModelSelection.model !== activeSession?.model;
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
const previousModelSelection = threadModelSelections.get(threadId);
const shouldRestartForModelSelectionChange =
const previousModelOptions = threadModelOptions.get(threadId);
const shouldRestartForModelOptionsChange =
currentProvider === "claudeAgent" &&
requestedModelSelection !== undefined &&
!Equal.equals(previousModelSelection, requestedModelSelection);
options?.modelOptions !== undefined &&
!sameModelOptions(previousModelOptions, options.modelOptions);
if (
!runtimeModeChanged &&
!providerChanged &&
!shouldRestartForModelChange &&
!shouldRestartForModelSelectionChange
!shouldRestartForModelOptionsChange
) {
return existingSessionThreadId;
}
const resumeCursor =
providerChanged || shouldRestartForModelChange
providerChanged || shouldRestartForModelChange || shouldRestartForModelOptionsChange
? undefined
: (activeSession?.resumeCursor ?? undefined);
yield* Effect.logInfo("provider command reactor restarting provider session", {
threadId,
existingSessionThreadId,
currentProvider,
desiredProvider: desiredModelSelection.provider,
desiredProvider: options?.provider ?? currentProvider,
currentRuntimeMode: thread.session?.runtimeMode,
desiredRuntimeMode: thread.runtimeMode,
runtimeModeChanged,
providerChanged,
modelChanged,
shouldRestartForModelChange,
shouldRestartForModelSelectionChange,
shouldRestartForModelOptionsChange,
hasResumeCursor: resumeCursor !== undefined,
});
const restartedSession = yield* startProviderSession(
resumeCursor !== undefined ? { resumeCursor } : undefined,
);
const restartedSession = yield* startProviderSession({
...(resumeCursor !== undefined ? { resumeCursor } : {}),
...(options?.provider !== undefined ? { provider: options.provider } : {}),
});
yield* Effect.logInfo("provider command reactor restarted provider session", {
threadId,
previousSessionId: existingSessionThreadId,
@@ -344,7 +345,9 @@ const make = Effect.gen(function* () {
return restartedSession.threadId;
}
const startedSession = yield* startProviderSession(undefined);
const startedSession = yield* startProviderSession(
options?.provider !== undefined ? { provider: options.provider } : undefined,
);
yield* bindSessionToThread(startedSession);
return startedSession.threadId;
});
@@ -353,7 +356,10 @@ const make = Effect.gen(function* () {
readonly threadId: ThreadId;
readonly messageText: string;
readonly attachments?: ReadonlyArray<ChatAttachment>;
readonly modelSelection?: ModelSelection;
readonly provider?: ProviderKind;
readonly model?: string;
readonly modelOptions?: ProviderModelOptions;
readonly providerOptions?: ProviderStartOptions;
readonly interactionMode?: "default" | "plan";
readonly createdAt: string;
}) {
@@ -361,13 +367,17 @@ const make = Effect.gen(function* () {
if (!thread) {
return;
}
yield* ensureSessionForThread(
input.threadId,
input.createdAt,
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
);
if (input.modelSelection !== undefined) {
threadModelSelections.set(input.threadId, input.modelSelection);
yield* ensureSessionForThread(input.threadId, input.createdAt, {
...(input.provider !== undefined ? { provider: input.provider } : {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
});
if (input.providerOptions !== undefined) {
threadProviderOptions.set(input.threadId, input.providerOptions);
}
if (input.modelOptions !== undefined) {
threadModelOptions.set(input.threadId, input.modelOptions);
}
const normalizedInput = toNonEmptyProviderInput(input.messageText);
const normalizedAttachments = input.attachments ?? [];
@@ -380,23 +390,14 @@ const make = Effect.gen(function* () {
activeSession === undefined
? "in-session"
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
const requestedModelSelection =
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
const modelForTurn =
sessionModelSwitch === "unsupported"
? activeSession?.model !== undefined
? {
...requestedModelSelection,
model: activeSession.model,
}
: requestedModelSelection
: input.modelSelection;
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
yield* providerService.sendTurn({
threadId: input.threadId,
...(normalizedInput ? { input: normalizedInput } : {}),
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
});
});
@@ -434,10 +435,7 @@ const make = Effect.gen(function* () {
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection: yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.textGenerationModelSelection,
),
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
})
.pipe(
Effect.catch((error) =>
@@ -512,8 +510,13 @@ const make = Effect.gen(function* () {
threadId: event.payload.threadId,
messageText: message.text,
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
...(event.payload.modelSelection !== undefined
? { modelSelection: event.payload.modelSelection }
...(event.payload.provider !== undefined ? { provider: event.payload.provider } : {}),
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
...(event.payload.modelOptions !== undefined
? { modelOptions: event.payload.modelOptions }
: {}),
...(event.payload.providerOptions !== undefined
? { providerOptions: event.payload.providerOptions }
: {}),
interactionMode: event.payload.interactionMode,
createdAt: event.payload.createdAt,
@@ -587,9 +590,7 @@ const make = Effect.gen(function* () {
threadId: event.payload.threadId,
kind: "provider.approval.respond.failed",
summary: "Provider approval response failed",
detail: isUnknownPendingApprovalRequestError(cause)
? stalePendingRequestDetail("approval", event.payload.requestId)
: Cause.pretty(cause),
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
@@ -633,9 +634,7 @@ const make = Effect.gen(function* () {
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),
detail: Cause.pretty(cause),
turnId: null,
createdAt: event.payload.createdAt,
requestId: event.payload.requestId,
@@ -680,12 +679,14 @@ const make = Effect.gen(function* () {
if (!thread?.session || thread.session.status === "stopped") {
return;
}
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
yield* ensureSessionForThread(
event.payload.threadId,
event.occurredAt,
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
);
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
const cachedModelOptions = threadModelOptions.get(event.payload.threadId);
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
...(cachedProviderOptions !== undefined
? { providerOptions: cachedProviderOptions }
: {}),
...(cachedModelOptions !== undefined ? { modelOptions: cachedModelOptions } : {}),
});
return;
}
case "thread.turn-start-requested":
@@ -12,12 +12,10 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_SERVER_SETTINGS,
EventId,
MessageId,
ProjectId,
ProviderItemId,
type ServerSettings,
ThreadId,
TurnId,
} from "@t3tools/contracts";
@@ -40,20 +38,8 @@ import {
} from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
const settings: ServerSettings = { ...DEFAULT_SERVER_SETTINGS, ...overrides };
return Layer.succeed(ServerSettingsService, {
start: Effect.void,
ready: Effect.void,
getSettings: Effect.succeed(settings),
updateSettings: () => Effect.succeed(settings),
streamChanges: Stream.empty,
} satisfies ServerSettingsShape);
}
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
const asItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
@@ -139,6 +125,7 @@ type ProviderRuntimeTestThread = ProviderRuntimeTestReadModel["threads"][number]
type ProviderRuntimeTestMessage = ProviderRuntimeTestThread["messages"][number];
type ProviderRuntimeTestProposedPlan = ProviderRuntimeTestThread["proposedPlans"][number];
type ProviderRuntimeTestActivity = ProviderRuntimeTestThread["activities"][number];
type ProviderRuntimeTestWorkUnit = ProviderRuntimeTestThread["workUnits"][number];
type ProviderRuntimeTestCheckpoint = ProviderRuntimeTestThread["checkpoints"][number];
describe("ProviderRuntimeIngestion", () => {
@@ -169,7 +156,7 @@ describe("ProviderRuntimeIngestion", () => {
}
});
async function createHarness(options?: { serverSettings?: Partial<ServerSettings> }) {
async function createHarness() {
const workspaceRoot = makeTempDir("t3-provider-project-");
fs.mkdirSync(path.join(workspaceRoot, ".git"));
const provider = createProviderServiceHarness();
@@ -183,7 +170,6 @@ describe("ProviderRuntimeIngestion", () => {
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(NodeServices.layer),
);
@@ -202,10 +188,7 @@ describe("ProviderRuntimeIngestion", () => {
projectId: asProjectId("project-1"),
title: "Provider Project",
workspaceRoot,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
}),
);
@@ -216,10 +199,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -745,10 +725,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
@@ -780,10 +757,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -932,10 +906,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
@@ -1085,10 +1056,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: sourceThreadId,
projectId: asProjectId("project-1"),
title: "Plan Source",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: "plan",
runtimeMode: "approval-required",
branch: null,
@@ -1120,10 +1088,7 @@ describe("ProviderRuntimeIngestion", () => {
threadId: targetThreadId,
projectId: asProjectId("project-1"),
title: "Plan Target",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -1372,7 +1337,7 @@ describe("ProviderRuntimeIngestion", () => {
});
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const harness = await createHarness();
const now = new Date().toISOString();
await Effect.runPromise(
@@ -1386,6 +1351,7 @@ describe("ProviderRuntimeIngestion", () => {
text: "stream please",
attachments: [],
},
assistantDeliveryMode: "streaming",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
createdAt: now,
@@ -1933,185 +1899,6 @@ describe("ProviderRuntimeIngestion", () => {
expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated");
});
it("projects context window updates into normalized thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
usage: {
usedTokens: 1075,
totalProcessedTokens: 10_200,
maxTokens: 128_000,
inputTokens: 1000,
cachedInputTokens: 500,
outputTokens: 50,
reasoningOutputTokens: 25,
lastUsedTokens: 1075,
lastInputTokens: 1000,
lastCachedInputTokens: 500,
lastOutputTokens: 50,
lastReasoningOutputTokens: 25,
compactsAutomatically: true,
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
),
);
const usageActivity = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
);
expect(usageActivity).toBeDefined();
expect(usageActivity?.payload).toMatchObject({
usedTokens: 1075,
totalProcessedTokens: 10_200,
maxTokens: 128_000,
inputTokens: 1000,
cachedInputTokens: 500,
outputTokens: 50,
reasoningOutputTokens: 25,
lastUsedTokens: 1075,
compactsAutomatically: true,
});
});
it("projects Codex camelCase token usage payloads into normalized thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-camel"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
usage: {
usedTokens: 126,
totalProcessedTokens: 11_839,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
lastUsedTokens: 126,
lastInputTokens: 120,
lastCachedInputTokens: 0,
lastOutputTokens: 6,
lastReasoningOutputTokens: 0,
compactsAutomatically: true,
},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
),
);
const usageActivity = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
);
expect(usageActivity?.payload).toMatchObject({
usedTokens: 126,
totalProcessedTokens: 11_839,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
lastUsedTokens: 126,
lastInputTokens: 120,
lastOutputTokens: 6,
compactsAutomatically: true,
});
});
it("projects Claude usage snapshots with context window into normalized thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.token-usage.updated",
eventId: asEventId("evt-thread-token-usage-updated-claude-window"),
provider: "claudeAgent",
createdAt: now,
threadId: asThreadId("thread-1"),
payload: {
usage: {
usedTokens: 31_251,
lastUsedTokens: 31_251,
maxTokens: 200_000,
toolUses: 25,
durationMs: 43_567,
},
},
raw: {
source: "claude.sdk.message",
method: "claude/result/success",
payload: {},
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
),
);
const usageActivity = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
);
expect(usageActivity?.payload).toMatchObject({
usedTokens: 31_251,
lastUsedTokens: 31_251,
maxTokens: 200_000,
toolUses: 25,
durationMs: 43_567,
});
});
it("projects compacted thread state into context compaction activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
harness.emit({
type: "thread.state.changed",
eventId: asEventId("evt-thread-compacted"),
provider: "codex",
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
payload: {
state: "compacted",
detail: { source: "provider" },
},
});
const thread = await waitForThread(harness.engine, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
),
);
const activity = thread.activities.find(
(candidate: ProviderRuntimeTestActivity) => candidate.kind === "context-compaction",
);
expect(activity?.summary).toBe("Context compacted");
expect(activity?.tone).toBe("info");
});
it("projects Codex task lifecycle chunks into thread activities", async () => {
const harness = await createHarness();
const now = new Date().toISOString();
@@ -2123,6 +1910,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
taskType: "plan",
@@ -2136,6 +1924,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
description: "Comparing the desktop rollout chunks to the app-server stream.",
@@ -2150,6 +1939,7 @@ describe("ProviderRuntimeIngestion", () => {
createdAt: now,
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-task-1"),
itemId: "call-collab-1",
payload: {
taskId: "turn-task-1",
status: "completed",
@@ -2208,6 +1998,38 @@ describe("ProviderRuntimeIngestion", () => {
);
expect(completed?.kind).toBe("task.completed");
expect(completedPayload?.detail).toBe("<proposed_plan>\n# Plan title\n</proposed_plan>");
expect(started?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(progress?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(completed?.workUnitId).toBe("wu:thread-1:turn:turn-task-1:task:turn-task-1");
expect(
thread.workUnits.find(
(entry: ProviderRuntimeTestWorkUnit) => entry.id === "wu:thread-1:turn:turn-task-1:root",
),
).toMatchObject({
id: "wu:thread-1:turn:turn-task-1:root",
turnId: "turn-task-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
});
expect(
thread.workUnits.find(
(entry: ProviderRuntimeTestWorkUnit) =>
entry.id === "wu:thread-1:turn:turn-task-1:task:turn-task-1",
),
).toMatchObject({
id: "wu:thread-1:turn:turn-task-1:task:turn-task-1",
turnId: "turn-task-1",
parentWorkUnitId: "wu:thread-1:turn:turn-task-1:root",
kind: "delegated_agent",
state: "completed",
title: "<proposed_plan>\n# Plan title\n</proposed_plan>",
providerRefs: {
runtimeTaskId: "turn-task-1",
runtimeItemId: "call-collab-1",
},
});
expect(
thread.proposedPlans.find(
(entry: ProviderRuntimeTestProposedPlan) => entry.id === "plan:thread-1:turn:turn-task-1",
@@ -7,31 +7,37 @@ import {
type OrchestrationProposedPlanId,
CheckpointRef,
isToolLifecycleItemType,
RuntimeTaskId,
ThreadId,
type ThreadTokenUsageSnapshot,
TurnId,
WorkUnitId,
type OrchestrationThread,
type OrchestrationThreadActivity,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { Cache, Cause, Duration, Effect, Layer, Option, Stream } from "effect";
import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effect";
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { isGitRepository } from "../../git/isRepo.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
ProviderRuntimeIngestionService,
type ProviderRuntimeIngestionShape,
} from "../Services/ProviderRuntimeIngestion.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const providerTurnKey = (threadId: ThreadId, turnId: TurnId) => `${threadId}:${turnId}`;
const providerCommandId = (event: ProviderRuntimeEvent, tag: string): CommandId =>
CommandId.makeUnsafe(`provider:${event.eventId}:${tag}:${crypto.randomUUID()}`);
const rootWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId): WorkUnitId =>
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:root`);
const taskWorkUnitIdForTurn = (threadId: ThreadId, turnId: TurnId, taskId: string): WorkUnitId =>
WorkUnitId.makeUnsafe(`wu:${threadId}:turn:${turnId}:task:${taskId}`);
const DEFAULT_ASSISTANT_DELIVERY_MODE: AssistantDeliveryMode = "buffered";
const TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY = 10_000;
const TURN_MESSAGE_IDS_BY_TURN_TTL = Duration.minutes(120);
const BUFFERED_MESSAGE_TEXT_BY_MESSAGE_ID_CACHE_CAPACITY = 20_000;
@@ -102,15 +108,6 @@ function asString(value: unknown): string | undefined {
return typeof value === "string" ? value : undefined;
}
function buildContextWindowActivityPayload(
event: ProviderRuntimeEvent,
): ThreadTokenUsageSnapshot | undefined {
if (event.type !== "thread.token-usage.updated" || event.payload.usage.usedTokens <= 0) {
return undefined;
}
return event.payload.usage;
}
function runtimePayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
const payload = (event as { payload?: unknown }).payload;
if (!payload || typeof payload !== "object") {
@@ -187,6 +184,57 @@ function requestKindFromCanonicalRequestType(
}
}
function workUnitIdForRuntimeEvent(event: ProviderRuntimeEvent): WorkUnitId | null {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return null;
}
if (
event.type === "task.started" ||
event.type === "task.progress" ||
event.type === "task.completed"
) {
return taskWorkUnitIdForTurn(event.threadId, turnId, String(event.payload.taskId));
}
return rootWorkUnitIdForTurn(event.threadId, turnId);
}
function runtimeTurnStateToWorkUnitState(
state: "completed" | "failed" | "interrupted" | "cancelled",
): "completed" | "failed" | "stopped" | "cancelled" {
switch (state) {
case "failed":
return "failed";
case "interrupted":
return "stopped";
case "cancelled":
return "cancelled";
case "completed":
return "completed";
}
}
function runtimeTaskStateToWorkUnitState(
state: "completed" | "failed" | "stopped",
): "completed" | "failed" | "stopped" {
switch (state) {
case "failed":
return "failed";
case "stopped":
return "stopped";
case "completed":
return "completed";
}
}
function providerTurnWorkUnitRefs(
event: ProviderRuntimeEvent,
): NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]> | undefined {
return event.providerRefs?.providerTurnId !== undefined
? { providerTurnId: event.providerRefs.providerTurnId }
: undefined;
}
function runtimeEventToActivities(
event: ProviderRuntimeEvent,
): ReadonlyArray<OrchestrationThreadActivity> {
@@ -196,6 +244,7 @@ function runtimeEventToActivities(
? { sequence: eventWithSequence.sessionSequence }
: {};
})();
const maybeWorkUnit = { workUnitId: workUnitIdForRuntimeEvent(event) };
switch (event.type) {
case "request.opened": {
if (event.payload.requestType === "tool_user_input") {
@@ -223,6 +272,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -247,6 +297,7 @@ function runtimeEventToActivities(
...(event.payload.decision ? { decision: event.payload.decision } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -268,6 +319,7 @@ function runtimeEventToActivities(
message: truncateDetail(message),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -286,6 +338,7 @@ function runtimeEventToActivities(
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -306,6 +359,7 @@ function runtimeEventToActivities(
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -324,6 +378,7 @@ function runtimeEventToActivities(
questions: event.payload.questions,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -342,6 +397,7 @@ function runtimeEventToActivities(
answers: event.payload.answers,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -368,6 +424,7 @@ function runtimeEventToActivities(
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -389,6 +446,7 @@ function runtimeEventToActivities(
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -414,48 +472,7 @@ function runtimeEventToActivities(
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "thread.state.changed": {
if (event.payload.state !== "compacted") {
return [];
}
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "context-compaction",
summary: "Context compacted",
payload: {
state: event.payload.state,
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "thread.token-usage.updated": {
const payload = buildContextWindowActivityPayload(event);
if (!payload) {
return [];
}
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "context-window.updated",
summary: "Context window updated",
payload,
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -479,6 +496,7 @@ function runtimeEventToActivities(
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -500,6 +518,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -521,6 +540,7 @@ function runtimeEventToActivities(
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeWorkUnit,
...maybeSequence,
},
];
@@ -537,7 +557,10 @@ const make = Effect.gen(function* () {
const orchestrationEngine = yield* OrchestrationEngineService;
const providerService = yield* ProviderService;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const serverSettingsService = yield* ServerSettingsService;
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
DEFAULT_ASSISTANT_DELIVERY_MODE,
);
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
@@ -905,6 +928,74 @@ const make = Effect.gen(function* () {
});
});
const upsertWorkUnit = Effect.fnUntraced(function* (input: {
thread: OrchestrationThread;
event: ProviderRuntimeEvent;
workUnitId: WorkUnitId;
turnId: TurnId;
kind: "primary_agent" | "delegated_agent";
state: "queued" | "running" | "completed" | "failed" | "stopped" | "cancelled";
title: string;
updatedAt: string;
parentWorkUnitId?: WorkUnitId | null;
detail?: string | null;
startedAt?: string;
completedAt?: string | null;
providerRefs?: NonNullable<OrchestrationThread["workUnits"][number]["providerRefs"]>;
}) {
const existing = input.thread.workUnits.find((entry) => sameId(entry.id, input.workUnitId));
const providerRefs =
input.providerRefs !== undefined || existing?.providerRefs !== undefined
? {
...existing?.providerRefs,
...input.providerRefs,
}
: undefined;
yield* orchestrationEngine.dispatch({
type: "thread.work-unit.upsert",
commandId: providerCommandId(input.event, "thread-work-unit-upsert"),
threadId: input.thread.id,
workUnit: {
id: input.workUnitId,
turnId: input.turnId,
parentWorkUnitId: input.parentWorkUnitId ?? existing?.parentWorkUnitId ?? null,
kind: input.kind,
state: input.state,
title: input.title.trim().length > 0 ? input.title : (existing?.title ?? "Work unit"),
detail: input.detail !== undefined ? input.detail : (existing?.detail ?? null),
spawnedByActivityId: existing?.spawnedByActivityId ?? null,
...(providerRefs !== undefined ? { providerRefs } : {}),
startedAt: existing?.startedAt ?? input.startedAt ?? input.updatedAt,
updatedAt: input.updatedAt,
completedAt:
input.completedAt !== undefined ? input.completedAt : (existing?.completedAt ?? null),
},
createdAt: input.updatedAt,
});
});
const ensureRootWorkUnit = Effect.fnUntraced(function* (
thread: OrchestrationThread,
event: ProviderRuntimeEvent,
turnId: TurnId,
updatedAt: string,
) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, turnId),
turnId,
kind: "primary_agent",
state: "running",
title: "Primary agent",
updatedAt,
startedAt: updatedAt,
...(providerRefs ? { providerRefs } : {}),
});
});
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const readModel = yield* orchestrationEngine.getReadModel();
@@ -1029,6 +1120,89 @@ const make = Effect.gen(function* () {
}
}
if (eventTurnId !== undefined) {
yield* ensureRootWorkUnit(thread, event, eventTurnId, now);
}
if (event.type === "turn.started" && eventTurnId !== undefined) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
turnId: eventTurnId,
kind: "primary_agent",
state: "running",
title: "Primary agent",
updatedAt: now,
startedAt: now,
...(providerRefs ? { providerRefs } : {}),
});
}
if (event.type === "turn.completed" && eventTurnId !== undefined) {
const providerRefs = providerTurnWorkUnitRefs(event);
yield* upsertWorkUnit({
thread,
event,
workUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
turnId: eventTurnId,
kind: "primary_agent",
state: runtimeTurnStateToWorkUnitState(runtimeTurnState(event)),
title: "Primary agent",
updatedAt: now,
completedAt: now,
...(providerRefs ? { providerRefs } : {}),
});
}
if (
(event.type === "task.started" ||
event.type === "task.progress" ||
event.type === "task.completed") &&
eventTurnId !== undefined
) {
const taskId = String(event.payload.taskId);
const workUnitId = taskWorkUnitIdForTurn(thread.id, eventTurnId, taskId);
const taskState =
event.type === "task.completed"
? runtimeTaskStateToWorkUnitState(event.payload.status)
: "running";
const taskTitle =
event.type === "task.started"
? (event.payload.description ?? event.payload.taskType ?? "Delegated task")
: event.type === "task.completed"
? (event.payload.summary ?? "Delegated task")
: (event.payload.summary ?? event.payload.description);
const taskDetail =
event.type === "task.started"
? (event.payload.description ?? null)
: event.type === "task.completed"
? (event.payload.summary ?? null)
: (event.payload.summary ?? event.payload.description);
yield* upsertWorkUnit({
thread,
event,
workUnitId,
turnId: eventTurnId,
parentWorkUnitId: rootWorkUnitIdForTurn(thread.id, eventTurnId),
kind: "delegated_agent",
state: taskState,
title: taskTitle,
detail: taskDetail,
updatedAt: now,
...(event.type === "task.started" ? { startedAt: now } : {}),
...(event.type === "task.completed" ? { completedAt: now } : {}),
providerRefs: {
runtimeTaskId: RuntimeTaskId.makeUnsafe(taskId),
...(event.itemId ? { runtimeItemId: event.itemId } : {}),
...(event.providerRefs?.providerTurnId !== undefined
? { providerTurnId: event.providerRefs.providerTurnId }
: {}),
},
});
}
const assistantDelta =
event.type === "content.delta" && event.payload.streamKind === "assistant_text"
? event.payload.delta
@@ -1045,10 +1219,7 @@ const make = Effect.gen(function* () {
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
}
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
);
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
if (assistantDeliveryMode === "buffered") {
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
if (spillChunk.length > 0) {
@@ -1256,7 +1427,11 @@ const make = Effect.gen(function* () {
).pipe(Effect.asVoid);
});
const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
const processDomainEvent = (event: TurnStartRequestedDomainEvent) =>
Ref.set(
assistantDeliveryModeRef,
event.payload.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
);
const processInput = (input: RuntimeIngestionInput) =>
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
+2
View File
@@ -13,6 +13,7 @@ import {
ThreadTurnDiffCompletedPayload as ContractsThreadTurnDiffCompletedPayloadSchema,
ThreadRevertedPayload as ContractsThreadRevertedPayloadSchema,
ThreadActivityAppendedPayload as ContractsThreadActivityAppendedPayloadSchema,
ThreadWorkUnitUpsertedPayload as ContractsThreadWorkUnitUpsertedPayloadSchema,
ThreadTurnStartRequestedPayload as ContractsThreadTurnStartRequestedPayloadSchema,
ThreadTurnInterruptRequestedPayload as ContractsThreadTurnInterruptRequestedPayloadSchema,
ThreadApprovalResponseRequestedPayload as ContractsThreadApprovalResponseRequestedPayloadSchema,
@@ -37,6 +38,7 @@ export const ThreadSessionSetPayload = ContractsThreadSessionSetPayloadSchema;
export const ThreadTurnDiffCompletedPayload = ContractsThreadTurnDiffCompletedPayloadSchema;
export const ThreadRevertedPayload = ContractsThreadRevertedPayloadSchema;
export const ThreadActivityAppendedPayload = ContractsThreadActivityAppendedPayloadSchema;
export const ThreadWorkUnitUpsertedPayload = ContractsThreadWorkUnitUpsertedPayloadSchema;
export const ThreadTurnStartRequestedPayload = ContractsThreadTurnStartRequestedPayloadSchema;
export const ThreadTurnInterruptRequestedPayload =
@@ -28,10 +28,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-a"),
title: "Project A",
workspaceRoot: "/tmp/project-a",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
scripts: [],
createdAt: now,
updatedAt: now,
@@ -41,10 +38,7 @@ const readModel: OrchestrationReadModel = {
id: ProjectId.makeUnsafe("project-b"),
title: "Project B",
workspaceRoot: "/tmp/project-b",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
scripts: [],
createdAt: now,
updatedAt: now,
@@ -56,10 +50,7 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "Thread A",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -71,6 +62,7 @@ const readModel: OrchestrationReadModel = {
session: null,
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
deletedAt: null,
},
@@ -78,10 +70,7 @@ const readModel: OrchestrationReadModel = {
id: ThreadId.makeUnsafe("thread-2"),
projectId: ProjectId.makeUnsafe("project-b"),
title: "Thread B",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -93,6 +82,7 @@ const readModel: OrchestrationReadModel = {
session: null,
activities: [],
proposedPlans: [],
workUnits: [],
checkpoints: [],
deletedAt: null,
},
@@ -156,10 +146,7 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-3"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "new",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -180,10 +167,7 @@ describe("commandInvariants", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: ProjectId.makeUnsafe("project-a"),
title: "dup",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -59,7 +59,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-scripts"),
title: "Scripts",
workspaceRoot: "/tmp/scripts",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -113,7 +113,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -136,10 +136,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
@@ -162,10 +159,10 @@ describe("decider project scripts", () => {
text: "hello",
attachments: [],
},
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -192,10 +189,10 @@ describe("decider project scripts", () => {
expect(turnStartEvent.payload).toMatchObject({
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: asMessageId("message-user-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
provider: "codex",
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -223,7 +220,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -246,10 +243,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -305,7 +299,7 @@ describe("decider project scripts", () => {
projectId: asProjectId("project-1"),
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -328,10 +322,7 @@ describe("decider project scripts", () => {
threadId: ThreadId.makeUnsafe("thread-1"),
projectId: asProjectId("project-1"),
title: "Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "approval-required",
branch: null,
+32 -10
View File
@@ -14,6 +14,7 @@ import {
} from "./commandInvariants.ts";
const nowIso = () => new Date().toISOString();
const DEFAULT_ASSISTANT_DELIVERY_MODE = "buffered" as const;
const defaultMetadata: Omit<OrchestrationEvent, "sequence" | "type" | "payload"> = {
eventId: crypto.randomUUID() as OrchestrationEvent["eventId"],
@@ -76,7 +77,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
title: command.title,
workspaceRoot: command.workspaceRoot,
defaultModelSelection: command.defaultModelSelection ?? null,
defaultModel: command.defaultModel ?? null,
scripts: [],
createdAt: command.createdAt,
updatedAt: command.createdAt,
@@ -103,9 +104,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
projectId: command.projectId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
...(command.defaultModelSelection !== undefined
? { defaultModelSelection: command.defaultModelSelection }
: {}),
...(command.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
updatedAt: occurredAt,
},
@@ -157,7 +156,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
threadId: command.threadId,
projectId: command.projectId,
title: command.title,
modelSelection: command.modelSelection,
model: command.model,
runtimeMode: command.runtimeMode,
interactionMode: command.interactionMode,
branch: command.branch,
@@ -208,9 +207,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
...(command.title !== undefined ? { title: command.title } : {}),
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
: {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.branch !== undefined ? { branch: command.branch } : {}),
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
updatedAt: occurredAt,
@@ -326,9 +323,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
messageId: command.message.messageId,
...(command.modelSelection !== undefined
? { modelSelection: command.modelSelection }
...(command.provider !== undefined ? { provider: command.provider } : {}),
...(command.model !== undefined ? { model: command.model } : {}),
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
...(command.providerOptions !== undefined
? { providerOptions: command.providerOptions }
: {}),
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
runtimeMode: targetThread.runtimeMode,
interactionMode: targetThread.interactionMode,
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
@@ -630,6 +631,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.work-unit.upsert": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
}),
type: "thread.work-unit-upserted",
payload: {
threadId: command.threadId,
workUnit: command.workUnit,
},
};
}
default: {
command satisfies never;
const fallback = command as never as { type: string };
+94 -36
View File
@@ -56,10 +56,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -76,10 +73,7 @@ describe("orchestration projector", () => {
id: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -91,6 +85,7 @@ describe("orchestration projector", () => {
messages: [],
proposedPlans: [],
activities: [],
workUnits: [],
checkpoints: [],
session: null,
},
@@ -116,10 +111,7 @@ describe("orchestration projector", () => {
// missing required threadId
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
branch: null,
worktreePath: null,
createdAt: now,
@@ -131,6 +123,88 @@ describe("orchestration projector", () => {
).rejects.toBeDefined();
});
it("applies thread.work-unit-upserted events", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
const afterCreate = await Effect.runPromise(
projectEvent(
model,
makeEvent({
sequence: 1,
type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-thread-create",
payload: {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
),
);
const next = await Effect.runPromise(
projectEvent(
afterCreate,
makeEvent({
sequence: 2,
type: "thread.work-unit-upserted",
aggregateKind: "thread",
aggregateId: "thread-1",
occurredAt: now,
commandId: "cmd-work-unit-upsert",
payload: {
threadId: "thread-1",
workUnit: {
id: "wu:thread-1:turn:turn-1:root",
turnId: "turn-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: now,
updatedAt: now,
completedAt: null,
},
},
}),
),
);
expect(next.threads[0]?.workUnits).toEqual([
{
id: "wu:thread-1:turn:turn-1:root",
turnId: "turn-1",
parentWorkUnitId: null,
kind: "primary_agent",
state: "running",
title: "Primary agent",
detail: null,
spawnedByActivityId: null,
providerRefs: {
providerTurnId: "provider-turn-1",
},
startedAt: now,
updatedAt: now,
completedAt: null,
},
]);
});
it("keeps projector forward-compatible for unhandled event types", async () => {
const now = new Date().toISOString();
const model = createEmptyReadModel(now);
@@ -179,10 +253,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -245,10 +316,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -302,10 +370,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -389,10 +454,7 @@ describe("orchestration projector", () => {
threadId: "thread-1",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -474,6 +536,7 @@ describe("orchestration projector", () => {
summary: "Edit file started",
payload: { toolKind: "command" },
turnId: "turn-1",
workUnitId: null,
createdAt: "2026-02-23T10:00:02.750Z",
},
},
@@ -548,6 +611,7 @@ describe("orchestration projector", () => {
summary: "Edit file complete",
payload: { toolKind: "command" },
turnId: "turn-2",
workUnitId: null,
createdAt: "2026-02-23T10:00:04.750Z",
},
},
@@ -604,10 +668,7 @@ describe("orchestration projector", () => {
threadId: "thread-revert",
projectId: "project-1",
title: "demo",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
},
model: "gpt-5.3-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
@@ -757,10 +818,7 @@ describe("orchestration projector", () => {
threadId: "thread-capped",
projectId: "project-1",
title: "capped",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
branch: null,
worktreePath: null,
+52 -7
View File
@@ -23,6 +23,7 @@ import {
ThreadRevertedPayload,
ThreadSessionSetPayload,
ThreadTurnDiffCompletedPayload,
ThreadWorkUnitUpsertedPayload,
} from "./Schemas.ts";
type ThreadPatch = Partial<Omit<OrchestrationThread, "id" | "projectId">>;
@@ -136,6 +137,17 @@ function retainThreadProposedPlansAfterRevert(
);
}
function retainThreadWorkUnitsAfterRevert(
workUnits: ReadonlyArray<OrchestrationThread["workUnits"][number]>,
retainedTurnIds: ReadonlySet<string>,
): ReadonlyArray<OrchestrationThread["workUnits"][number]> {
const retained = workUnits.filter((workUnit) => retainedTurnIds.has(workUnit.turnId));
const retainedIds = new Set(retained.map((workUnit) => workUnit.id));
return retained.filter(
(workUnit) => workUnit.parentWorkUnitId === null || retainedIds.has(workUnit.parentWorkUnitId),
);
}
function compareThreadActivities(
left: OrchestrationThread["activities"][number],
right: OrchestrationThread["activities"][number],
@@ -181,7 +193,7 @@ export function projectEvent(
id: payload.projectId,
title: payload.title,
workspaceRoot: payload.workspaceRoot,
defaultModelSelection: payload.defaultModelSelection,
defaultModel: payload.defaultModel,
scripts: payload.scripts,
createdAt: payload.createdAt,
updatedAt: payload.updatedAt,
@@ -211,8 +223,8 @@ export function projectEvent(
...(payload.workspaceRoot !== undefined
? { workspaceRoot: payload.workspaceRoot }
: {}),
...(payload.defaultModelSelection !== undefined
? { defaultModelSelection: payload.defaultModelSelection }
...(payload.defaultModel !== undefined
? { defaultModel: payload.defaultModel }
: {}),
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
updatedAt: payload.updatedAt,
@@ -252,7 +264,7 @@ export function projectEvent(
id: payload.threadId,
projectId: payload.projectId,
title: payload.title,
modelSelection: payload.modelSelection,
model: payload.model,
runtimeMode: payload.runtimeMode,
interactionMode: payload.interactionMode,
branch: payload.branch,
@@ -262,7 +274,9 @@ export function projectEvent(
updatedAt: payload.updatedAt,
deletedAt: null,
messages: [],
proposedPlans: [],
activities: [],
workUnits: [],
checkpoints: [],
session: null,
},
@@ -295,9 +309,7 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
...(payload.title !== undefined ? { title: payload.title } : {}),
...(payload.modelSelection !== undefined
? { modelSelection: payload.modelSelection }
: {}),
...(payload.model !== undefined ? { model: payload.model } : {}),
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
updatedAt: payload.updatedAt,
@@ -565,6 +577,7 @@ export function projectEvent(
retainedTurnIds,
).slice(-200);
const activities = retainThreadActivitiesAfterRevert(thread.activities, retainedTurnIds);
const workUnits = retainThreadWorkUnitsAfterRevert(thread.workUnits, retainedTurnIds);
const latestCheckpoint = checkpoints.at(-1) ?? null;
const latestTurn =
@@ -586,6 +599,7 @@ export function projectEvent(
messages,
proposedPlans,
activities,
workUnits,
latestTurn,
updatedAt: event.occurredAt,
}),
@@ -623,6 +637,37 @@ export function projectEvent(
}),
);
case "thread.work-unit-upserted":
return decodeForEvent(
ThreadWorkUnitUpsertedPayload,
event.payload,
event.type,
"payload",
).pipe(
Effect.map((payload) => {
const thread = nextBase.threads.find((entry) => entry.id === payload.threadId);
if (!thread) {
return nextBase;
}
const workUnits = [
...thread.workUnits.filter((entry) => entry.id !== payload.workUnit.id),
payload.workUnit,
].toSorted(
(left, right) =>
left.startedAt.localeCompare(right.startedAt) || left.id.localeCompare(right.id),
);
return {
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
workUnits,
updatedAt: event.occurredAt,
}),
};
}),
);
default:
return Effect.succeed(nextBase);
}
+2 -2
View File
@@ -27,10 +27,10 @@ export const expandHomePath = Effect.fn(function* (input: string) {
return input;
});
export const resolveBaseDir = Effect.fn(function* (raw: string | undefined) {
export const resolveStateDir = Effect.fn(function* (raw: string | undefined) {
const { join, resolve } = yield* Path.Path;
if (!raw || raw.trim().length === 0) {
return join(OS.homedir(), ".t3");
return join(OS.homedir(), ".t3", "userdata");
}
return resolve(yield* expandHomePath(raw.trim()));
});
@@ -35,7 +35,7 @@ layer("OrchestrationEventStore", (it) => {
projectId: ProjectId.makeUnsafe("project-roundtrip"),
title: "Roundtrip Project",
workspaceRoot: "/tmp/project-roundtrip",
defaultModelSelection: null,
defaultModel: null,
scripts: [],
createdAt: now,
updatedAt: now,
@@ -1,9 +1,9 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer, Option, Schema, Struct } from "effect";
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
DeleteProjectionProjectInput,
GetProjectionProjectInput,
@@ -11,64 +11,69 @@ import {
ProjectionProjectRepository,
type ProjectionProjectRepositoryShape,
} from "../Services/ProjectionProjects.ts";
import { ProjectScript } from "@t3tools/contracts";
const ProjectionProjectDbRow = ProjectionProject.mapFields(
Struct.assign({
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
}),
// Makes sure that the scripts are parsed from the JSON string the DB returns
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
Struct.assign({ scripts: Schema.fromJsonString(Schema.Array(ProjectScript)) }),
);
type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown) =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
}
const makeProjectionProjectRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionProjectRow = SqlSchema.void({
Request: ProjectionProject,
Request: ProjectionProjectDbRowSchema,
execute: (row) =>
sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model_selection_json,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
${row.projectId},
${row.title},
${row.workspaceRoot},
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
${JSON.stringify(row.scripts)},
${row.createdAt},
${row.updatedAt},
${row.deletedAt}
)
ON CONFLICT (project_id)
DO UPDATE SET
title = excluded.title,
workspace_root = excluded.workspace_root,
default_model_selection_json = excluded.default_model_selection_json,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
deleted_at = excluded.deleted_at
`,
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES (
${row.projectId},
${row.title},
${row.workspaceRoot},
${row.defaultModel},
${row.scripts},
${row.createdAt},
${row.updatedAt},
${row.deletedAt}
)
ON CONFLICT (project_id)
DO UPDATE SET
title = excluded.title,
workspace_root = excluded.workspace_root,
default_model = excluded.default_model,
scripts_json = excluded.scripts_json,
created_at = excluded.created_at,
updated_at = excluded.updated_at,
deleted_at = excluded.deleted_at
`,
});
const getProjectionProjectRow = SqlSchema.findOneOption({
Request: GetProjectionProjectInput,
Result: ProjectionProjectDbRow,
Result: ProjectionProjectDbRowSchema,
execute: ({ projectId }) =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_model AS "defaultModel",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -80,14 +85,14 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
const listProjectionProjectRows = SqlSchema.findAll({
Request: Schema.Void,
Result: ProjectionProjectDbRow,
Result: ProjectionProjectDbRowSchema,
execute: () =>
sql`
SELECT
project_id AS "projectId",
title,
workspace_root AS "workspaceRoot",
default_model_selection_json AS "defaultModelSelection",
default_model AS "defaultModel",
scripts_json AS "scripts",
created_at AS "createdAt",
updated_at AS "updatedAt",
@@ -108,17 +113,40 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) =>
upsertProjectionProjectRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")),
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionProjectRepository.upsert:query",
"ProjectionProjectRepository.upsert:encodeRequest",
),
),
);
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
getProjectionProjectRow(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionProjectRepository.getById:query",
"ProjectionProjectRepository.getById:decodeRow",
),
),
Effect.flatMap((rowOption) =>
Option.match(rowOption, {
onNone: () => Effect.succeed(Option.none()),
onSome: (row) =>
Effect.succeed(Option.some(row as Schema.Schema.Type<typeof ProjectionProject>)),
}),
),
);
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
listProjectionProjectRows().pipe(
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionProjectRepository.listAll:query",
"ProjectionProjectRepository.listAll:decodeRows",
),
),
Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionProject>>),
);
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
@@ -1,122 +0,0 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, Layer, Option } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { SqlitePersistenceMemory } from "./Sqlite.ts";
import { ProjectionProjectRepositoryLive } from "./ProjectionProjects.ts";
import { ProjectionThreadRepositoryLive } from "./ProjectionThreads.ts";
import { ProjectionProjectRepository } from "../Services/ProjectionProjects.ts";
import { ProjectionThreadRepository } from "../Services/ProjectionThreads.ts";
const projectionRepositoriesLayer = it.layer(
Layer.mergeAll(
ProjectionProjectRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
ProjectionThreadRepositoryLive.pipe(Layer.provideMerge(SqlitePersistenceMemory)),
SqlitePersistenceMemory,
),
);
projectionRepositoriesLayer("Projection repositories", (it) => {
it.effect("stores SQL NULL for missing project model options", () =>
Effect.gen(function* () {
const projects = yield* ProjectionProjectRepository;
const sql = yield* SqlClient.SqlClient;
yield* projects.upsert({
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options project",
workspaceRoot: "/tmp/project-null-options",
defaultModelSelection: {
provider: "codex",
model: "gpt-5.4",
},
scripts: [],
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
deletedAt: null,
});
const rows = yield* sql<{
readonly defaultModelSelection: string | null;
}>`
SELECT default_model_selection_json AS "defaultModelSelection"
FROM projection_projects
WHERE project_id = 'project-null-options'
`;
const row = rows[0];
if (!row) {
return yield* Effect.fail(new Error("Expected projection_projects row to exist."));
}
assert.strictEqual(
row.defaultModelSelection,
JSON.stringify({
provider: "codex",
model: "gpt-5.4",
}),
);
const persisted = yield* projects.getById({
projectId: ProjectId.makeUnsafe("project-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.defaultModelSelection, {
provider: "codex",
model: "gpt-5.4",
});
}),
);
it.effect("stores JSON for thread model options", () =>
Effect.gen(function* () {
const threads = yield* ProjectionThreadRepository;
const sql = yield* SqlClient.SqlClient;
yield* threads.upsert({
threadId: ThreadId.makeUnsafe("thread-null-options"),
projectId: ProjectId.makeUnsafe("project-null-options"),
title: "Null options thread",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurnId: null,
createdAt: "2026-03-24T00:00:00.000Z",
updatedAt: "2026-03-24T00:00:00.000Z",
deletedAt: null,
});
const rows = yield* sql<{
readonly modelSelection: string | null;
}>`
SELECT model_selection_json AS "modelSelection"
FROM projection_threads
WHERE thread_id = 'thread-null-options'
`;
const row = rows[0];
if (!row) {
return yield* Effect.fail(new Error("Expected projection_threads row to exist."));
}
assert.strictEqual(
row.modelSelection,
JSON.stringify({
provider: "claudeAgent",
model: "claude-opus-4-6",
}),
);
const persisted = yield* threads.getById({
threadId: ThreadId.makeUnsafe("thread-null-options"),
});
assert.deepStrictEqual(Option.getOrNull(persisted)?.modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
});
}),
);
});
@@ -38,6 +38,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activity_id,
thread_id,
turn_id,
work_unit_id,
tone,
kind,
summary,
@@ -49,6 +50,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
${row.activityId},
${row.threadId},
${row.turnId},
${row.workUnitId},
${row.tone},
${row.kind},
${row.summary},
@@ -60,6 +62,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
work_unit_id = excluded.work_unit_id,
tone = excluded.tone,
kind = excluded.kind,
summary = excluded.summary,
@@ -78,6 +81,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
work_unit_id AS "workUnitId",
tone,
kind,
summary,
@@ -126,6 +130,7 @@ const makeProjectionThreadActivityRepository = Effect.gen(function* () {
activityId: row.activityId,
threadId: row.threadId,
turnId: row.turnId,
workUnitId: row.workUnitId,
tone: row.tone,
kind: row.kind,
summary: row.summary,
@@ -0,0 +1,163 @@
import { Effect, Layer, Schema, Struct } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
import {
DeleteProjectionThreadWorkUnitsInput,
ListProjectionThreadWorkUnitsInput,
ProjectionThreadWorkUnit,
ProjectionThreadWorkUnitRepository,
type ProjectionThreadWorkUnitRepositoryShape,
} from "../Services/ProjectionThreadWorkUnits.ts";
const ProjectionThreadWorkUnitDbRowSchema = ProjectionThreadWorkUnit.mapFields(
Struct.assign({
providerRefs: Schema.NullOr(
Schema.fromJsonString(ProjectionThreadWorkUnit.fields.providerRefs),
),
}),
);
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
return (cause: unknown) =>
Schema.isSchemaError(cause)
? toPersistenceDecodeError(decodeOperation)(cause)
: toPersistenceSqlError(sqlOperation)(cause);
}
const makeProjectionThreadWorkUnitRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionThreadWorkUnitRow = SqlSchema.void({
Request: ProjectionThreadWorkUnit,
execute: (row) => sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
VALUES (
${row.workUnitId},
${row.threadId},
${row.turnId},
${row.parentWorkUnitId},
${row.kind},
${row.state},
${row.title},
${row.detail},
${row.spawnedByActivityId},
${row.providerRefs ? JSON.stringify(row.providerRefs) : null},
${row.startedAt},
${row.updatedAt},
${row.completedAt}
)
ON CONFLICT (work_unit_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
parent_work_unit_id = excluded.parent_work_unit_id,
kind = excluded.kind,
state = excluded.state,
title = excluded.title,
detail = excluded.detail,
spawned_by_activity_id = excluded.spawned_by_activity_id,
provider_refs_json = excluded.provider_refs_json,
started_at = excluded.started_at,
updated_at = excluded.updated_at,
completed_at = excluded.completed_at
`,
});
const listProjectionThreadWorkUnitRows = SqlSchema.findAll({
Request: ListProjectionThreadWorkUnitsInput,
Result: ProjectionThreadWorkUnitDbRowSchema,
execute: ({ threadId }) => sql`
SELECT
work_unit_id AS "workUnitId",
thread_id AS "threadId",
turn_id AS "turnId",
parent_work_unit_id AS "parentWorkUnitId",
kind,
state,
title,
detail,
spawned_by_activity_id AS "spawnedByActivityId",
provider_refs_json AS "providerRefs",
started_at AS "startedAt",
updated_at AS "updatedAt",
completed_at AS "completedAt"
FROM projection_thread_work_units
WHERE thread_id = ${threadId}
ORDER BY started_at ASC, work_unit_id ASC
`,
});
const deleteProjectionThreadWorkUnitRows = SqlSchema.void({
Request: DeleteProjectionThreadWorkUnitsInput,
execute: ({ threadId }) => sql`
DELETE FROM projection_thread_work_units
WHERE thread_id = ${threadId}
`,
});
const upsert: ProjectionThreadWorkUnitRepositoryShape["upsert"] = (row) =>
upsertProjectionThreadWorkUnitRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionThreadWorkUnitRepository.upsert:query")),
);
const listByThreadId: ProjectionThreadWorkUnitRepositoryShape["listByThreadId"] = (input) =>
listProjectionThreadWorkUnitRows(input).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionThreadWorkUnitRepository.listByThreadId:query",
"ProjectionThreadWorkUnitRepository.listByThreadId:decodeRows",
),
),
Effect.map((rows) =>
rows.map((row) => ({
workUnitId: row.workUnitId,
threadId: row.threadId,
turnId: row.turnId,
parentWorkUnitId: row.parentWorkUnitId,
kind: row.kind,
state: row.state,
title: row.title,
detail: row.detail,
spawnedByActivityId: row.spawnedByActivityId,
...(row.providerRefs !== null ? { providerRefs: row.providerRefs } : {}),
startedAt: row.startedAt,
updatedAt: row.updatedAt,
completedAt: row.completedAt,
})),
),
);
const deleteByThreadId: ProjectionThreadWorkUnitRepositoryShape["deleteByThreadId"] = (input) =>
deleteProjectionThreadWorkUnitRows(input).pipe(
Effect.mapError(
toPersistenceSqlError("ProjectionThreadWorkUnitRepository.deleteByThreadId:query"),
),
);
return {
upsert,
listByThreadId,
deleteByThreadId,
} satisfies ProjectionThreadWorkUnitRepositoryShape;
});
export const ProjectionThreadWorkUnitRepositoryLive = Layer.effect(
ProjectionThreadWorkUnitRepository,
makeProjectionThreadWorkUnitRepository,
);
@@ -1,6 +1,6 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import { Effect, Layer, Schema, Struct } from "effect";
import { Effect, Layer } from "effect";
import { toPersistenceSqlError } from "../Errors.ts";
import {
@@ -11,14 +11,6 @@ import {
ProjectionThreadRepository,
type ProjectionThreadRepositoryShape,
} from "../Services/ProjectionThreads.ts";
import { ModelSelection } from "@t3tools/contracts";
const ProjectionThreadDbRow = ProjectionThread.mapFields(
Struct.assign({
modelSelection: Schema.fromJsonString(ModelSelection),
}),
);
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
const makeProjectionThreadRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
@@ -31,7 +23,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
thread_id,
project_id,
title,
model_selection_json,
model,
runtime_mode,
interaction_mode,
branch,
@@ -45,7 +37,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.threadId},
${row.projectId},
${row.title},
${JSON.stringify(row.modelSelection)},
${row.model},
${row.runtimeMode},
${row.interactionMode},
${row.branch},
@@ -59,7 +51,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
DO UPDATE SET
project_id = excluded.project_id,
title = excluded.title,
model_selection_json = excluded.model_selection_json,
model = excluded.model,
runtime_mode = excluded.runtime_mode,
interaction_mode = excluded.interaction_mode,
branch = excluded.branch,
@@ -73,14 +65,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
const getProjectionThreadRow = SqlSchema.findOneOption({
Request: GetProjectionThreadInput,
Result: ProjectionThreadDbRow,
Result: ProjectionThread,
execute: ({ threadId }) =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
model,
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
@@ -96,14 +88,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
const listProjectionThreadRows = SqlSchema.findAll({
Request: ListProjectionThreadsByProjectInput,
Result: ProjectionThreadDbRow,
Result: ProjectionThread,
execute: ({ projectId }) =>
sql`
SELECT
thread_id AS "threadId",
project_id AS "projectId",
title,
model_selection_json AS "modelSelection",
model,
runtime_mode AS "runtimeMode",
interaction_mode AS "interactionMode",
branch,
+7 -4
View File
@@ -31,7 +31,7 @@ const setup = Layer.effectDiscard(
const sql = yield* SqlClient.SqlClient;
yield* sql`PRAGMA journal_mode = WAL;`;
yield* sql`PRAGMA foreign_keys = ON;`;
yield* runMigrations();
yield* runMigrations;
}),
);
@@ -49,6 +49,9 @@ export const SqlitePersistenceMemory = Layer.provideMerge(
makeRuntimeSqliteLayer({ filename: ":memory:" }),
);
export const layerConfig = Layer.unwrap(
Effect.map(Effect.service(ServerConfig), ({ dbPath }) => makeSqlitePersistenceLive(dbPath)),
);
export const layerConfig = Effect.gen(function* () {
const { stateDir } = yield* ServerConfig;
const { join } = yield* Path.Path;
const dbPath = join(stateDir, "state.sqlite");
return makeSqlitePersistenceLive(dbPath);
}).pipe(Layer.unwrap);
+26 -47
View File
@@ -10,7 +10,6 @@
import * as Migrator from "effect/unstable/sql/Migrator";
import * as Layer from "effect/Layer";
import * as Effect from "effect/Effect";
// Import all migrations statically
import Migration0001 from "./Migrations/001_OrchestrationEvents.ts";
@@ -28,7 +27,8 @@ import Migration0012 from "./Migrations/012_ProjectionThreadsInteractionMode.ts"
import Migration0013 from "./Migrations/013_ProjectionThreadProposedPlans.ts";
import Migration0014 from "./Migrations/014_ProjectionThreadProposedPlanImplementation.ts";
import Migration0015 from "./Migrations/015_ProjectionTurnsSourceProposedPlan.ts";
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
import Migration0016 from "./Migrations/016_ProjectionThreadWorkUnits.ts";
import { Effect } from "effect";
/**
* Migration loader with all migrations defined inline.
@@ -40,33 +40,24 @@ import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
* Uses Migrator.fromRecord which parses the key format and
* returns migrations sorted by ID.
*/
export const migrationEntries = [
[1, "OrchestrationEvents", Migration0001],
[2, "OrchestrationCommandReceipts", Migration0002],
[3, "CheckpointDiffBlobs", Migration0003],
[4, "ProviderSessionRuntime", Migration0004],
[5, "Projections", Migration0005],
[6, "ProjectionThreadSessionRuntimeModeColumns", Migration0006],
[7, "ProjectionThreadMessageAttachments", Migration0007],
[8, "ProjectionThreadActivitySequence", Migration0008],
[9, "ProviderSessionRuntimeMode", Migration0009],
[10, "ProjectionThreadsRuntimeMode", Migration0010],
[11, "OrchestrationThreadCreatedRuntimeMode", Migration0011],
[12, "ProjectionThreadsInteractionMode", Migration0012],
[13, "ProjectionThreadProposedPlans", Migration0013],
[14, "ProjectionThreadProposedPlanImplementation", Migration0014],
[15, "ProjectionTurnsSourceProposedPlan", Migration0015],
[16, "CanonicalizeModelSelections", Migration0016],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
Migrator.fromRecord(
Object.fromEntries(
migrationEntries
.filter(([id]) => throughId === undefined || id <= throughId)
.map(([id, name, migration]) => [`${id}_${name}`, migration]),
),
);
const loader = Migrator.fromRecord({
"1_OrchestrationEvents": Migration0001,
"2_OrchestrationCommandReceipts": Migration0002,
"3_CheckpointDiffBlobs": Migration0003,
"4_ProviderSessionRuntime": Migration0004,
"5_Projections": Migration0005,
"6_ProjectionThreadSessionRuntimeModeColumns": Migration0006,
"7_ProjectionThreadMessageAttachments": Migration0007,
"8_ProjectionThreadActivitySequence": Migration0008,
"9_ProviderSessionRuntimeMode": Migration0009,
"10_ProjectionThreadsRuntimeMode": Migration0010,
"11_OrchestrationThreadCreatedRuntimeMode": Migration0011,
"12_ProjectionThreadsInteractionMode": Migration0012,
"13_ProjectionThreadProposedPlans": Migration0013,
"14_ProjectionThreadProposedPlanImplementation": Migration0014,
"15_ProjectionTurnsSourceProposedPlan": Migration0015,
"16_ProjectionThreadWorkUnits": Migration0016,
});
/**
* Migrator run function - no schema dumping needed
@@ -74,10 +65,6 @@ export const makeMigrationLoader = (throughId?: number) =>
*/
const run = Migrator.make({});
export interface RunMigrationsOptions {
readonly toMigrationInclusive?: number | undefined;
}
/**
* Run all pending migrations.
*
@@ -88,19 +75,11 @@ export interface RunMigrationsOptions {
*
* @returns Effect containing array of executed migrations
*/
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
Effect.gen(function* () {
yield* Effect.log(
toMigrationInclusive === undefined
? "Running all migrations..."
: `Running migrations 1 through ${toMigrationInclusive}...`,
);
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
yield* Effect.log("Migrations ran successfully").pipe(
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
);
return executedMigrations;
});
export const runMigrations = Effect.gen(function* () {
yield* Effect.log("Running migrations...");
yield* run({ loader });
yield* Effect.log("Migrations ran successfully");
});
/**
* Layer that runs migrations when the layer is built.
@@ -119,4 +98,4 @@ export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {
* )
* ```
*/
export const MigrationsLive = Layer.effectDiscard(runMigrations());
export const MigrationsLive = Layer.effectDiscard(runMigrations);
@@ -1,357 +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("016_CanonicalizeModelSelections", (it) => {
it.effect(
"migrates legacy projection rows and event payloads to the canonical model-selection shape",
() =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
// Setup base state
{
yield* runMigrations({ toMigrationInclusive: 15 });
yield* sql`
INSERT INTO projection_projects (
project_id,
title,
workspace_root,
default_model,
scripts_json,
created_at,
updated_at,
deleted_at
)
VALUES
('project-codex', 'Codex project', '/tmp/project-codex', 'gpt-5.4', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
('project-claude', 'Claude project', '/tmp/project-claude', 'claude-sonnet-4-6', '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL),
('project-null', 'Null project', '/tmp/project-null', NULL, '[]', '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL)
`;
yield* sql`
UPDATE projection_projects
SET default_model = 'claude-opus-4-6'
WHERE project_id = 'project-claude'
`;
yield* sql`
INSERT INTO projection_threads (
thread_id,
project_id,
title,
model,
branch,
worktree_path,
latest_turn_id,
created_at,
updated_at,
deleted_at,
runtime_mode,
interaction_mode
)
VALUES
('thread-session', 'project-codex', 'Session thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
('thread-claude', 'project-claude', 'Claude thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
('thread-codex', 'project-codex', 'Codex thread', 'gpt-5.4', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default'),
('thread-legacy-options', 'project-claude', 'Legacy options thread', 'claude-opus-4-6', NULL, NULL, NULL, '2026-01-01T00:00:00.000Z', '2026-01-01T00:00:00.000Z', NULL, 'full-access', 'default')
`;
yield* sql`
INSERT INTO projection_thread_sessions (
thread_id,
status,
provider_name,
provider_session_id,
provider_thread_id,
active_turn_id,
last_error,
updated_at,
runtime_mode
)
VALUES (
'thread-session',
'running',
'claudeAgent',
'provider-session-1',
'provider-thread-1',
NULL,
NULL,
'2026-01-01T00:00:00.000Z',
'full-access'
)
`;
yield* sql`
INSERT INTO orchestration_events (
event_id,
aggregate_kind,
stream_id,
stream_version,
event_type,
occurred_at,
command_id,
causation_event_id,
correlation_id,
actor_kind,
payload_json,
metadata_json
)
VALUES
(
'event-project-created',
'project',
'project-1',
1,
'project.created',
'2026-01-01T00:00:00.000Z',
'command-project-created',
NULL,
'correlation-project-created',
'user',
'{"projectId":"project-1","title":"Project","workspaceRoot":"/tmp/project","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-project-created-fallback',
'project',
'project-2',
1,
'project.created',
'2026-01-01T00:00:00.000Z',
'command-project-created-fallback',
NULL,
'correlation-project-created-fallback',
'user',
'{"projectId":"project-2","title":"Fallback Project","workspaceRoot":"/tmp/project-2","defaultModel":"claude-opus-4-6","defaultModelOptions":{"codex":{"reasoningEffort":"low"}},"scripts":[],"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-created',
'thread',
'thread-1',
1,
'thread.created',
'2026-01-01T00:00:00.000Z',
'command-thread-created',
NULL,
'correlation-thread-created',
'user',
'{"threadId":"thread-1","projectId":"project-1","title":"Thread","model":"claude-opus-4-6","modelOptions":{"codex":{"reasoningEffort":"high"},"claudeAgent":{"effort":"max","thinking":false}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-thread-created-fallback',
'thread',
'thread-2',
1,
'thread.created',
'2026-01-01T00:00:00.000Z',
'command-thread-created-fallback',
NULL,
'correlation-thread-created-fallback',
'user',
'{"threadId":"thread-2","projectId":"project-1","title":"Fallback Thread","model":"gpt-5.4","modelOptions":{"claudeAgent":{"effort":"max"}},"runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
),
(
'event-turn-start-requested',
'thread',
'thread-1',
2,
'thread.turn-start-requested',
'2026-01-01T00:00:00.000Z',
'command-turn-start-requested',
NULL,
'correlation-turn-start-requested',
'user',
'{"threadId":"thread-1","turnId":"turn-1","input":"hi","model":"gpt-5.4","modelOptions":{"codex":{"fastMode":true},"claudeAgent":{"effort":"max"}},"deliveryMode":"buffered"}',
'{}'
),
(
'event-thread-created-no-model',
'thread',
'thread-3',
1,
'thread.created',
'2026-01-01T00:00:00.000Z',
'command-thread-created-no-model',
NULL,
'correlation-thread-created-no-model',
'user',
'{"threadId":"thread-3","projectId":"project-1","title":"Ancient Thread","runtimeMode":"full-access","interactionMode":"default","branch":null,"worktreePath":null,"createdAt":"2026-01-01T00:00:00.000Z","updatedAt":"2026-01-01T00:00:00.000Z"}',
'{}'
)
`;
}
// Execute migration under test
yield* runMigrations({ toMigrationInclusive: 16 });
// Assert expected state
{
const projectRows = yield* sql<{
readonly projectId: string;
readonly defaultModelSelection: string | null;
}>`
SELECT
project_id AS "projectId",
default_model_selection_json AS "defaultModelSelection"
FROM projection_projects
ORDER BY project_id
`;
assert.deepStrictEqual(projectRows, [
{
projectId: "project-claude",
defaultModelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
},
{
projectId: "project-codex",
defaultModelSelection: '{"provider":"codex","model":"gpt-5.4"}',
},
{ projectId: "project-null", defaultModelSelection: null },
]);
const threadRows = yield* sql<{
readonly threadId: string;
readonly modelSelection: string | null;
}>`
SELECT
thread_id AS "threadId",
model_selection_json AS "modelSelection"
FROM projection_threads
ORDER BY thread_id
`;
assert.deepStrictEqual(threadRows, [
{
threadId: "thread-claude",
modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
},
{
threadId: "thread-codex",
modelSelection: '{"provider":"codex","model":"gpt-5.4"}',
},
{
threadId: "thread-legacy-options",
modelSelection: '{"provider":"claudeAgent","model":"claude-opus-4-6"}',
},
{
threadId: "thread-session",
modelSelection: '{"provider":"claudeAgent","model":"gpt-5.4"}',
},
]);
const eventRows = yield* sql<{
readonly payloadJson: string;
}>`
SELECT payload_json AS "payloadJson"
FROM orchestration_events
ORDER BY rowid ASC
`;
assert.deepStrictEqual(JSON.parse(eventRows[0]!.payloadJson), {
projectId: "project-1",
title: "Project",
workspaceRoot: "/tmp/project",
defaultModelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
},
},
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[1]!.payloadJson), {
projectId: "project-2",
title: "Fallback Project",
workspaceRoot: "/tmp/project-2",
defaultModelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
reasoningEffort: "low",
},
},
scripts: [],
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
threadId: "thread-1",
projectId: "project-1",
title: "Thread",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
effort: "max",
thinking: false,
},
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[3]!.payloadJson), {
threadId: "thread-2",
projectId: "project-1",
title: "Fallback Thread",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
effort: "max",
},
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
assert.deepStrictEqual(JSON.parse(eventRows[4]!.payloadJson), {
threadId: "thread-1",
turnId: "turn-1",
input: "hi",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
options: {
fastMode: true,
},
},
deliveryMode: "buffered",
});
assert.deepStrictEqual(JSON.parse(eventRows[5]!.payloadJson), {
threadId: "thread-3",
projectId: "project-1",
title: "Ancient Thread",
modelSelection: {
provider: "codex",
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
});
}
}),
);
});
@@ -1,235 +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`
ALTER TABLE projection_projects
ADD COLUMN default_model_selection_json TEXT
`;
yield* sql`
UPDATE projection_projects
SET default_model_selection_json = CASE
WHEN default_model IS NULL THEN NULL
ELSE json_object(
'provider',
CASE
WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'
ELSE 'codex'
END,
'model',
default_model
)
END
WHERE default_model_selection_json IS NULL
`;
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN model_selection_json TEXT
`;
yield* sql`
UPDATE projection_threads
SET model_selection_json = json_object(
'provider',
COALESCE(
(
SELECT provider_name
FROM projection_thread_sessions
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
),
CASE
WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent'
ELSE 'codex'
END,
'codex'
),
'model',
model
)
WHERE model_selection_json IS NULL
`;
yield* sql`
ALTER TABLE projection_projects
DROP COLUMN default_model
`;
yield* sql`
ALTER TABLE projection_threads
DROP COLUMN model
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = CASE
WHEN json_type(payload_json, '$.defaultModel') = 'null' THEN json_remove(
json_set(payload_json, '$.defaultModelSelection', json('null')),
'$.defaultProvider',
'$.defaultModel',
'$.defaultModelOptions'
)
ELSE json_remove(
json_set(
payload_json,
'$.defaultModelSelection',
json_patch(
json_object(
'provider',
CASE
WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL
THEN json_extract(payload_json, '$.defaultProvider')
WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'
THEN 'claudeAgent'
ELSE 'codex'
END,
'model',
json_extract(payload_json, '$.defaultModel')
),
CASE
WHEN json_type(payload_json, '$.defaultModelOptions') IS NULL THEN '{}'
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
OR json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
THEN CASE
WHEN (
CASE
WHEN json_extract(payload_json, '$.defaultProvider') IS NOT NULL
THEN json_extract(payload_json, '$.defaultProvider')
WHEN lower(json_extract(payload_json, '$.defaultModel')) LIKE '%claude%'
THEN 'claudeAgent'
ELSE 'codex'
END
) = 'claudeAgent'
THEN CASE
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
)
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
)
ELSE '{}'
END
ELSE CASE
WHEN json_type(payload_json, '$.defaultModelOptions.codex') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
)
WHEN json_type(payload_json, '$.defaultModelOptions.claudeAgent') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
)
ELSE '{}'
END
END
ELSE json_object(
'options',
json(json_extract(payload_json, '$.defaultModelOptions'))
)
END
)
),
'$.defaultProvider',
'$.defaultModel',
'$.defaultModelOptions'
)
END
WHERE event_type IN ('project.created', 'project.meta-updated')
AND json_type(payload_json, '$.defaultModelSelection') IS NULL
AND json_type(payload_json, '$.defaultModel') IS NOT NULL
`;
yield* sql`
UPDATE orchestration_events
SET payload_json = json_remove(
json_set(
payload_json,
'$.modelSelection',
json_patch(
json_object(
'provider',
CASE
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
THEN json_extract(payload_json, '$.provider')
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
THEN 'claudeAgent'
ELSE 'codex'
END,
'model',
json_extract(payload_json, '$.model')
),
CASE
WHEN json_type(payload_json, '$.modelOptions') IS NULL THEN '{}'
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
OR json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
THEN CASE
WHEN (
CASE
WHEN json_extract(payload_json, '$.provider') IS NOT NULL
THEN json_extract(payload_json, '$.provider')
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
THEN 'claudeAgent'
ELSE 'codex'
END
) = 'claudeAgent'
THEN CASE
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
)
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.modelOptions.codex'))
)
ELSE '{}'
END
ELSE CASE
WHEN json_type(payload_json, '$.modelOptions.codex') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.modelOptions.codex'))
)
WHEN json_type(payload_json, '$.modelOptions.claudeAgent') IS NOT NULL
THEN json_object(
'options',
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
)
ELSE '{}'
END
END
ELSE json_object('options', json(json_extract(payload_json, '$.modelOptions')))
END
)
),
'$.provider',
'$.model',
'$.modelOptions'
)
WHERE event_type IN ('thread.created', 'thread.meta-updated', 'thread.turn-start-requested')
AND json_type(payload_json, '$.modelSelection') IS NULL
AND json_type(payload_json, '$.model') IS NOT NULL
`;
// Backfill thread.created events that predate the model field entirely
yield* sql`
UPDATE orchestration_events
SET payload_json = json_set(
payload_json,
'$.modelSelection',
json(json_object('provider', 'codex', 'model', 'gpt-5.4'))
)
WHERE event_type = 'thread.created'
AND json_type(payload_json, '$.modelSelection') IS NULL
AND json_type(payload_json, '$.model') IS NULL
`;
});
@@ -0,0 +1,88 @@
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`
ALTER TABLE projection_thread_activities
ADD COLUMN work_unit_id TEXT
`;
yield* sql`
CREATE TABLE IF NOT EXISTS projection_thread_work_units (
work_unit_id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
turn_id TEXT NOT NULL,
parent_work_unit_id TEXT,
kind TEXT NOT NULL,
state TEXT NOT NULL,
title TEXT NOT NULL,
detail TEXT,
spawned_by_activity_id TEXT,
provider_refs_json TEXT,
started_at TEXT NOT NULL,
updated_at TEXT NOT NULL,
completed_at TEXT
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_turn
ON projection_thread_work_units(thread_id, turn_id, started_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_thread_work_units_thread_parent
ON projection_thread_work_units(thread_id, parent_work_unit_id, started_at)
`;
yield* sql`
INSERT INTO projection_thread_work_units (
work_unit_id,
thread_id,
turn_id,
parent_work_unit_id,
kind,
state,
title,
detail,
spawned_by_activity_id,
provider_refs_json,
started_at,
updated_at,
completed_at
)
SELECT
'wu:' || thread_id || ':turn:' || turn_id || ':root',
thread_id,
turn_id,
NULL,
'primary_agent',
CASE state
WHEN 'completed' THEN 'completed'
WHEN 'error' THEN 'failed'
WHEN 'interrupted' THEN 'stopped'
ELSE 'running'
END,
'Primary agent',
NULL,
NULL,
NULL,
COALESCE(started_at, requested_at),
COALESCE(completed_at, started_at, requested_at),
CASE
WHEN state IN ('completed', 'error', 'interrupted') THEN COALESCE(completed_at, started_at, requested_at)
ELSE NULL
END
FROM projection_turns
WHERE turn_id IS NOT NULL
`;
yield* sql`
UPDATE projection_thread_activities
SET work_unit_id = 'wu:' || thread_id || ':turn:' || turn_id || ':root'
WHERE turn_id IS NOT NULL
AND work_unit_id IS NULL
`;
});
@@ -6,7 +6,7 @@
*
* @module ProjectionProjectRepository
*/
import { IsoDateTime, ModelSelection, ProjectId, ProjectScript } from "@t3tools/contracts";
import { IsoDateTime, ProjectId, ProjectScript } from "@t3tools/contracts";
import { Option, Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
@@ -16,7 +16,7 @@ export const ProjectionProject = Schema.Struct({
projectId: ProjectId,
title: Schema.String,
workspaceRoot: Schema.String,
defaultModelSelection: Schema.NullOr(ModelSelection),
defaultModel: Schema.NullOr(Schema.String),
scripts: Schema.Array(ProjectScript),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
@@ -13,6 +13,7 @@ import {
OrchestrationThreadActivityTone,
ThreadId,
TurnId,
WorkUnitId,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
@@ -23,6 +24,7 @@ export const ProjectionThreadActivity = Schema.Struct({
activityId: EventId,
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
workUnitId: Schema.NullOr(WorkUnitId),
tone: OrchestrationThreadActivityTone,
kind: Schema.String,
summary: Schema.String,
@@ -0,0 +1,59 @@
import {
EventId,
IsoDateTime,
OrchestrationWorkUnitKind,
OrchestrationWorkUnitProviderRefs,
OrchestrationWorkUnitState,
ThreadId,
TurnId,
TrimmedNonEmptyString,
WorkUnitId,
} from "@t3tools/contracts";
import { Schema, ServiceMap } from "effect";
import type { Effect } from "effect";
import type { ProjectionRepositoryError } from "../Errors.ts";
export const ProjectionThreadWorkUnit = Schema.Struct({
workUnitId: WorkUnitId,
threadId: ThreadId,
turnId: TurnId,
parentWorkUnitId: Schema.NullOr(WorkUnitId),
kind: OrchestrationWorkUnitKind,
state: OrchestrationWorkUnitState,
title: TrimmedNonEmptyString,
detail: Schema.NullOr(TrimmedNonEmptyString),
spawnedByActivityId: Schema.NullOr(EventId),
providerRefs: Schema.optional(OrchestrationWorkUnitProviderRefs),
startedAt: IsoDateTime,
updatedAt: IsoDateTime,
completedAt: Schema.NullOr(IsoDateTime),
});
export type ProjectionThreadWorkUnit = typeof ProjectionThreadWorkUnit.Type;
export const ListProjectionThreadWorkUnitsInput = Schema.Struct({
threadId: ThreadId,
});
export type ListProjectionThreadWorkUnitsInput = typeof ListProjectionThreadWorkUnitsInput.Type;
export const DeleteProjectionThreadWorkUnitsInput = Schema.Struct({
threadId: ThreadId,
});
export type DeleteProjectionThreadWorkUnitsInput = typeof DeleteProjectionThreadWorkUnitsInput.Type;
export interface ProjectionThreadWorkUnitRepositoryShape {
readonly upsert: (
workUnit: ProjectionThreadWorkUnit,
) => Effect.Effect<void, ProjectionRepositoryError>;
readonly listByThreadId: (
input: ListProjectionThreadWorkUnitsInput,
) => Effect.Effect<ReadonlyArray<ProjectionThreadWorkUnit>, ProjectionRepositoryError>;
readonly deleteByThreadId: (
input: DeleteProjectionThreadWorkUnitsInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
}
export class ProjectionThreadWorkUnitRepository extends ServiceMap.Service<
ProjectionThreadWorkUnitRepository,
ProjectionThreadWorkUnitRepositoryShape
>()("t3/persistence/Services/ProjectionThreadWorkUnits/ProjectionThreadWorkUnitRepository") {}
@@ -8,7 +8,6 @@
*/
import {
IsoDateTime,
ModelSelection,
ProjectId,
ProviderInteractionMode,
RuntimeMode,
@@ -24,7 +23,7 @@ export const ProjectionThread = Schema.Struct({
threadId: ThreadId,
projectId: ProjectId,
title: Schema.String,
modelSelection: ModelSelection,
model: Schema.String,
runtimeMode: RuntimeMode,
interactionMode: ProviderInteractionMode,
branch: Schema.NullOr(Schema.String),
File diff suppressed because it is too large. Load diff
+118 -480
View File
@@ -15,7 +15,6 @@ import {
type PermissionUpdate,
type SDKMessage,
type SDKResultMessage,
type SettingSource,
type SDKUserMessage,
} from "@anthropic-ai/claude-agent-sdk";
import {
@@ -29,7 +28,6 @@ import {
type ProviderRuntimeTurnStatus,
type ProviderSendTurnInput,
type ProviderSession,
type ThreadTokenUsageSnapshot,
type ProviderUserInputAnswers,
type RuntimeContentStreamKind,
RuntimeItemId,
@@ -38,31 +36,18 @@ import {
ThreadId,
TurnId,
type UserInputQuestion,
ClaudeCodeEffort,
} from "@t3tools/contracts";
import {
hasEffortLevel,
applyClaudePromptEffortPrefix,
getModelCapabilities,
trimOrNull,
getEffectiveClaudeCodeEffort,
getReasoningEffortOptions,
resolveReasoningEffortForProvider,
supportsClaudeFastMode,
supportsClaudeThinkingToggle,
supportsClaudeUltrathinkKeyword,
} from "@t3tools/shared/model";
import {
Cause,
DateTime,
Deferred,
Effect,
Exit,
FileSystem,
Fiber,
Layer,
Queue,
Random,
Ref,
Stream,
} from "effect";
import { Cause, DateTime, Deferred, Effect, Layer, Queue, Random, Ref, Stream } from "effect";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -102,14 +87,14 @@ interface ClaudeTurnState {
readonly startedAt: string;
readonly items: Array<unknown>;
readonly assistantTextBlocks: Map<number, AssistantTextBlockState>;
readonly assistantTextBlockOrder: Array<AssistantTextBlockState>;
readonly assistantTextBlockOrder: Array<number>;
readonly capturedProposedPlanKeys: Set<string>;
readonly taskItemIds: Map<string, string>;
nextSyntheticAssistantBlockIndex: number;
}
interface AssistantTextBlockState {
readonly itemId: string;
readonly blockIndex: number;
emittedTextDelta: boolean;
fallbackText: string;
streamClosed: boolean;
@@ -143,7 +128,6 @@ interface ClaudeSessionContext {
session: ProviderSession;
readonly promptQueue: Queue.Queue<PromptQueueItem>;
readonly query: ClaudeQueryRuntime;
streamFiber: Fiber.Fiber<void, Error> | undefined;
readonly startedAt: string;
readonly basePermissionMode: PermissionMode | undefined;
resumeSessionId: string | undefined;
@@ -155,8 +139,6 @@ interface ClaudeSessionContext {
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
lastAssistantUuid: string | undefined;
lastThreadStartedId: string | undefined;
stopped: boolean;
@@ -194,56 +176,6 @@ function toMessage(cause: unknown, fallback: string): string {
return fallback;
}
function toError(cause: unknown, fallback: string): Error {
return cause instanceof Error ? cause : new Error(toMessage(cause, fallback));
}
function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray<string> {
const errors = Cause.prettyErrors(cause)
.map((error) => error.message.trim())
.filter((message) => message.length > 0);
if (errors.length > 0) {
return errors;
}
const squashed = toMessage(Cause.squash(cause), "").trim();
return squashed.length > 0 ? [squashed] : [];
}
function getEffectiveClaudeCodeEffort(
effort: ClaudeCodeEffort | null | undefined,
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
if (!effort) {
return null;
}
return effort === "ultrathink" ? null : effort;
}
function isClaudeInterruptedMessage(message: string): boolean {
const normalized = message.toLowerCase();
return (
normalized.includes("all fibers interrupted without error") ||
normalized.includes("request was aborted") ||
normalized.includes("interrupted by user")
);
}
function isClaudeInterruptedCause(cause: Cause.Cause<Error>): boolean {
return (
Cause.hasInterruptsOnly(cause) ||
normalizeClaudeStreamMessages(cause).some(isClaudeInterruptedMessage)
);
}
function messageFromClaudeStreamCause(cause: Cause.Cause<Error>, fallback: string): string {
return normalizeClaudeStreamMessages(cause)[0] ?? fallback;
}
function interruptionMessageFromClaudeCause(cause: Cause.Cause<Error>): string {
const message = messageFromClaudeStreamCause(cause, "Claude runtime interrupted.");
return isClaudeInterruptedMessage(message) ? "Claude runtime interrupted." : message;
}
function resultErrorsText(result: SDKResultMessage): string {
return "errors" in result && Array.isArray(result.errors)
? result.errors.join(" ").toLowerCase()
@@ -269,82 +201,6 @@ function asRuntimeItemId(value: string): RuntimeItemId {
return RuntimeItemId.makeUnsafe(value);
}
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
if (!modelUsage || typeof modelUsage !== "object") {
return undefined;
}
let maxContextWindow: number | undefined;
for (const value of Object.values(modelUsage as Record<string, unknown>)) {
if (!value || typeof value !== "object") {
continue;
}
const contextWindow = (value as { contextWindow?: unknown }).contextWindow;
if (
typeof contextWindow !== "number" ||
!Number.isFinite(contextWindow) ||
contextWindow <= 0
) {
continue;
}
maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);
}
return maxContextWindow;
}
function normalizeClaudeTokenUsage(
usage: unknown,
contextWindow?: number,
): ThreadTokenUsageSnapshot | undefined {
if (!usage || typeof usage !== "object") {
return undefined;
}
const record = usage as Record<string, unknown>;
const directUsedTokens =
typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens)
? record.total_tokens
: undefined;
const inputTokens =
(typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)
? record.input_tokens
: 0) +
(typeof record.cache_creation_input_tokens === "number" &&
Number.isFinite(record.cache_creation_input_tokens)
? record.cache_creation_input_tokens
: 0) +
(typeof record.cache_read_input_tokens === "number" &&
Number.isFinite(record.cache_read_input_tokens)
? record.cache_read_input_tokens
: 0);
const outputTokens =
typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)
? record.output_tokens
: 0;
const derivedUsedTokens = inputTokens + outputTokens;
const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined);
if (usedTokens === undefined || usedTokens <= 0) {
return undefined;
}
return {
usedTokens,
lastUsedTokens: usedTokens,
...(inputTokens > 0 ? { inputTokens } : {}),
...(outputTokens > 0 ? { outputTokens } : {}),
...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
? { maxTokens: contextWindow }
: {}),
...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses)
? { toolUses: record.tool_uses }
: {}),
...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)
? { durationMs: record.duration_ms }
: {}),
};
}
function asCanonicalTurnId(value: TurnId): TurnId {
return value;
}
@@ -507,126 +363,45 @@ function titleForTool(itemType: CanonicalItemType): string {
}
}
const SUPPORTED_CLAUDE_IMAGE_MIME_TYPES = new Set([
"image/gif",
"image/jpeg",
"image/png",
"image/webp",
]);
const CLAUDE_SETTING_SOURCES = [
"user",
"project",
"local",
] as const satisfies ReadonlyArray<SettingSource>;
function buildUserMessage(input: ProviderSendTurnInput): SDKUserMessage {
const fragments: string[] = [];
function buildPromptText(input: ProviderSendTurnInput): string {
const rawEffort =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null;
const requestedEffort = trimOrNull(rawEffort);
const claudeModel =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
const caps = getModelCapabilities("claudeAgent", claudeModel);
if (input.input && input.input.trim().length > 0) {
fragments.push(input.input.trim());
}
for (const attachment of input.attachments ?? []) {
if (attachment.type === "image") {
fragments.push(
`Attached image: ${attachment.name} (${attachment.mimeType}, ${attachment.sizeBytes} bytes).`,
);
}
}
const requestedEffort = resolveReasoningEffortForProvider(
"claudeAgent",
input.modelOptions?.claudeAgent?.effort ?? null,
);
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
const promptEffort =
requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0
requestedEffort === "ultrathink" && supportsClaudeUltrathinkKeyword(input.model)
? "ultrathink"
: requestedEffort && hasEffortLevel(caps, requestedEffort)
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
? requestedEffort
: null;
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
}
const text = applyClaudePromptEffortPrefix(fragments.join("\n\n"), promptEffort);
function buildUserMessage(input: {
readonly sdkContent: Array<Record<string, unknown>>;
}): SDKUserMessage {
return {
type: "user",
session_id: "",
parent_tool_use_id: null,
message: {
role: "user",
content: input.sdkContent,
content: [{ type: "text", text }],
},
} as SDKUserMessage;
}
function buildClaudeImageContentBlock(input: {
readonly mimeType: string;
readonly bytes: Uint8Array;
}): Record<string, unknown> {
return {
type: "image",
source: {
type: "base64",
media_type: input.mimeType,
data: Buffer.from(input.bytes).toString("base64"),
},
};
}
function buildUserMessageEffect(
input: ProviderSendTurnInput,
dependencies: {
readonly fileSystem: FileSystem.FileSystem;
readonly attachmentsDir: string;
},
): Effect.Effect<SDKUserMessage, ProviderAdapterRequestError> {
return Effect.gen(function* () {
const text = buildPromptText(input);
const sdkContent: Array<Record<string, unknown>> = [];
if (text.length > 0) {
sdkContent.push({ type: "text", text });
}
for (const attachment of input.attachments ?? []) {
if (attachment.type !== "image") {
continue;
}
if (!SUPPORTED_CLAUDE_IMAGE_MIME_TYPES.has(attachment.mimeType)) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: `Unsupported Claude image attachment type '${attachment.mimeType}'.`,
});
}
const attachmentPath = resolveAttachmentPath({
attachmentsDir: dependencies.attachmentsDir,
attachment,
});
if (!attachmentPath) {
return yield* new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: `Invalid attachment id '${attachment.id}'.`,
});
}
const bytes = yield* dependencies.fileSystem.readFile(attachmentPath).pipe(
Effect.mapError(
(cause) =>
new ProviderAdapterRequestError({
provider: PROVIDER,
method: "turn/start",
detail: toMessage(cause, "Failed to read attachment file."),
cause,
}),
),
);
sdkContent.push(
buildClaudeImageContentBlock({
mimeType: attachment.mimeType,
bytes,
}),
);
}
return buildUserMessage({ sdkContent });
});
}
function turnStatusFromResult(result: SDKResultMessage): ProviderRuntimeTurnStatus {
if (result.subtype === "success") {
return "completed";
@@ -660,6 +435,20 @@ function nativeProviderRefs(
return {};
}
function taskEventParentItemFields(
context: ClaudeSessionContext,
taskId: string,
): Pick<ProviderRuntimeEvent, "itemId" | "providerRefs"> | undefined {
const providerItemId = context.turnState?.taskItemIds.get(taskId);
if (!providerItemId) {
return undefined;
}
return {
itemId: asRuntimeItemId(providerItemId),
providerRefs: nativeProviderRefs(context, { providerItemId }),
};
}
function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
if (message.type !== "assistant") {
return [];
@@ -924,8 +713,6 @@ function sdkNativeItemId(message: SDKMessage): string | undefined {
function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const serverConfig = yield* ServerConfig;
const nativeEventLogger =
options?.nativeEventLogger ??
(options?.nativeEventLogPath !== undefined
@@ -1057,7 +844,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
}
const existing = turnState.assistantTextBlocks.get(blockIndex);
if (existing && !existing.completionEmitted) {
if (existing) {
if (existing.fallbackText.length === 0 && options?.fallbackText) {
existing.fallbackText = options.fallbackText;
}
@@ -1069,14 +856,13 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const block: AssistantTextBlockState = {
itemId: yield* Random.nextUUIDv4,
blockIndex,
emittedTextDelta: false,
fallbackText: options?.fallbackText ?? "",
streamClosed: options?.streamClosed ?? false,
completionEmitted: false,
};
turnState.assistantTextBlocks.set(blockIndex, block);
turnState.assistantTextBlockOrder.push(block);
turnState.assistantTextBlockOrder.push(blockIndex);
return { blockIndex, block };
});
@@ -1106,7 +892,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const completeAssistantTextBlock = (
context: ClaudeSessionContext,
block: AssistantTextBlockState,
blockIndex: number,
options?: {
readonly force?: boolean;
readonly rawMethod?: string;
@@ -1115,7 +901,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
): Effect.Effect<void> =>
Effect.gen(function* () {
const turnState = context.turnState;
if (!turnState || block.completionEmitted) {
const block = turnState?.assistantTextBlocks.get(blockIndex);
if (!turnState || !block || block.completionEmitted) {
return;
}
@@ -1151,9 +938,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
}
block.completionEmitted = true;
if (turnState.assistantTextBlocks.get(block.blockIndex) === block) {
turnState.assistantTextBlocks.delete(block.blockIndex);
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
@@ -1198,10 +982,19 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
return;
}
const orderedBlocks = turnState.assistantTextBlockOrder.map((block) => ({
blockIndex: block.blockIndex,
block,
}));
const orderedBlocks = turnState.assistantTextBlockOrder
.map((blockIndex) => ({
blockIndex,
block: turnState.assistantTextBlocks.get(blockIndex),
}))
.filter(
(
entry,
): entry is {
readonly blockIndex: number;
readonly block: AssistantTextBlockState;
} => entry.block !== undefined,
);
for (const [position, text] of snapshotTextBlocks.entries()) {
const existingEntry = orderedBlocks[position];
@@ -1225,7 +1018,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
}
if (entry.block.streamClosed && !entry.block.completionEmitted) {
yield* completeAssistantTextBlock(context, entry.block, {
yield* completeAssistantTextBlock(context, entry.blockIndex, {
rawMethod: "claude/assistant",
rawPayload: message,
});
@@ -1374,53 +1167,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
result?: SDKResultMessage,
): Effect.Effect<void> =>
Effect.gen(function* () {
const resultUsage =
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
if (resultContextWindow !== undefined) {
context.lastKnownContextWindow = resultContextWindow;
}
// The SDK result.usage contains *accumulated* totals across all API calls
// (input_tokens, cache_read_input_tokens, etc. summed over every request).
// This does NOT represent the current context window size.
// Instead, use the last known context-window-accurate usage from task_progress
// events and treat the accumulated total as totalProcessedTokens.
const accumulatedSnapshot = normalizeClaudeTokenUsage(
resultUsage,
resultContextWindow ?? context.lastKnownContextWindow,
);
const lastGoodUsage = context.lastKnownTokenUsage;
const maxTokens = resultContextWindow ?? context.lastKnownContextWindow;
const usageSnapshot: ThreadTokenUsageSnapshot | undefined = lastGoodUsage
? {
...lastGoodUsage,
...(typeof maxTokens === "number" && Number.isFinite(maxTokens) && maxTokens > 0
? { maxTokens }
: {}),
...(accumulatedSnapshot && accumulatedSnapshot.usedTokens > lastGoodUsage.usedTokens
? { totalProcessedTokens: accumulatedSnapshot.usedTokens }
: {}),
}
: accumulatedSnapshot;
const turnState = context.turnState;
if (!turnState) {
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
payload: {
usage: usageSnapshot,
},
providerRefs: {},
});
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.completed",
@@ -1475,8 +1223,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
// Clear any remaining stale entries (e.g. from interrupted content blocks)
context.inFlightTools.clear();
for (const block of turnState.assistantTextBlockOrder) {
yield* completeAssistantTextBlock(context, block, {
for (const blockIndex of turnState.assistantTextBlockOrder) {
yield* completeAssistantTextBlock(context, blockIndex, {
force: true,
rawMethod: "claude/result",
rawPayload: result ?? { status },
@@ -1488,22 +1236,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
items: [...turnState.items],
});
if (usageSnapshot) {
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "thread.token-usage.updated",
eventId: usageStamp.eventId,
provider: PROVIDER,
createdAt: usageStamp.createdAt,
threadId: context.session.threadId,
turnId: turnState.turnId,
payload: {
usage: usageSnapshot,
},
providerRefs: nativeProviderRefs(context),
});
}
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "turn.completed",
@@ -1743,7 +1475,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const assistantBlock = context.turnState?.assistantTextBlocks.get(index);
if (assistantBlock) {
assistantBlock.streamClosed = true;
yield* completeAssistantTextBlock(context, assistantBlock, {
yield* completeAssistantTextBlock(context, index, {
rawMethod: "claude/stream_event/content_block_stop",
rawPayload: message,
});
@@ -1882,6 +1614,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
taskItemIds: new Map(),
nextSyntheticAssistantBlockIndex: -1,
};
context.session = {
@@ -2064,6 +1797,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
case "task_started":
yield* offerRuntimeEvent({
...base,
...taskEventParentItemFields(context, message.task_id),
type: "task.started",
payload: {
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
@@ -2073,27 +1807,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
});
return;
case "task_progress":
if (message.usage) {
const normalizedUsage = normalizeClaudeTokenUsage(
message.usage,
context.lastKnownContextWindow,
);
if (normalizedUsage) {
context.lastKnownTokenUsage = normalizedUsage;
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: usageStamp.eventId,
createdAt: usageStamp.createdAt,
type: "thread.token-usage.updated",
payload: {
usage: normalizedUsage,
},
});
}
}
yield* offerRuntimeEvent({
...base,
...taskEventParentItemFields(context, message.task_id),
type: "task.progress",
payload: {
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
@@ -2105,27 +1821,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
});
return;
case "task_notification":
if (message.usage) {
const normalizedUsage = normalizeClaudeTokenUsage(
message.usage,
context.lastKnownContextWindow,
);
if (normalizedUsage) {
context.lastKnownTokenUsage = normalizedUsage;
const usageStamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: usageStamp.eventId,
createdAt: usageStamp.createdAt,
type: "thread.token-usage.updated",
payload: {
usage: normalizedUsage,
},
});
}
}
yield* offerRuntimeEvent({
...base,
...taskEventParentItemFields(context, message.task_id),
type: "task.completed",
payload: {
taskId: RuntimeTaskId.makeUnsafe(message.task_id),
@@ -2189,8 +1887,13 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
};
if (message.type === "tool_progress") {
if (message.task_id && context.turnState) {
context.turnState.taskItemIds.set(message.task_id, message.tool_use_id);
}
yield* offerRuntimeEvent({
...base,
itemId: asRuntimeItemId(message.tool_use_id),
providerRefs: nativeProviderRefs(context, { providerItemId: message.tool_use_id }),
type: "tool.progress",
payload: {
toolUseId: message.tool_use_id,
@@ -2281,48 +1984,21 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
}
});
const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void, Error> =>
Stream.fromAsyncIterable(context.query, (cause) =>
toError(cause, "Claude runtime stream failed."),
).pipe(
const runSdkStream = (context: ClaudeSessionContext): Effect.Effect<void> =>
Stream.fromAsyncIterable(context.query, (cause) => cause).pipe(
Stream.takeWhile(() => !context.stopped),
Stream.runForEach((message) => handleSdkMessage(context, message)),
);
const handleStreamExit = (
context: ClaudeSessionContext,
exit: Exit.Exit<void, Error>,
): Effect.Effect<void> =>
Effect.gen(function* () {
if (context.stopped) {
return;
}
if (Exit.isFailure(exit)) {
if (isClaudeInterruptedCause(exit.cause)) {
if (context.turnState) {
yield* completeTurn(
context,
"interrupted",
interruptionMessageFromClaudeCause(exit.cause),
);
Effect.catchCause((cause) =>
Effect.gen(function* () {
if (Cause.hasInterruptsOnly(cause) || context.stopped) {
return;
}
} else {
const message = messageFromClaudeStreamCause(
exit.cause,
"Claude runtime stream failed.",
);
yield* emitRuntimeError(context, message, Cause.pretty(exit.cause));
const message = toMessage(Cause.squash(cause), "Claude runtime stream failed.");
yield* emitRuntimeError(context, message, cause);
yield* completeTurn(context, "failed", message);
}
} else if (context.turnState) {
yield* completeTurn(context, "interrupted", "Claude runtime stream ended.");
}
yield* stopSessionInternal(context, {
emitExitEvent: true,
});
});
}),
),
);
const stopSessionInternal = (
context: ClaudeSessionContext,
@@ -2359,18 +2035,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
yield* Queue.shutdown(context.promptQueue);
const streamFiber = context.streamFiber;
context.streamFiber = undefined;
if (streamFiber && streamFiber.pollUnsafe() === undefined) {
yield* Fiber.interrupt(streamFiber);
}
// @effect-diagnostics-next-line tryCatchInEffectGen:off
try {
context.query.close();
} catch (cause) {
yield* emitRuntimeError(context, "Failed to close Claude runtime query.", cause);
}
context.query.close();
const updatedAt = yield* nowIso;
context.session = {
@@ -2435,18 +2100,11 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const startedAt = yield* nowIso;
const resumeState = readClaudeResumeState(input.resumeCursor);
const threadId = input.threadId;
const existingResumeSessionId = resumeState?.resume;
const newSessionId =
existingResumeSessionId === undefined ? yield* Random.nextUUIDv4 : undefined;
const sessionId = existingResumeSessionId ?? newSessionId;
const promptQueue = yield* Queue.unbounded<PromptQueueItem>();
const prompt = Stream.fromQueue(promptQueue).pipe(
Stream.filter((item) => item.type === "message"),
Stream.map((item) => item.message),
Stream.catchCause((cause) =>
Cause.hasInterruptsOnly(cause) ? Stream.empty : Stream.failCause(cause),
),
Stream.toAsyncIterable,
);
@@ -2486,7 +2144,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
);
const answersDeferred = yield* Deferred.make<ProviderUserInputAnswers>();
let aborted = false;
const pendingInput: PendingUserInput = {
questions,
answers: answersDeferred,
@@ -2520,7 +2177,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
if (!pendingUserInputs.has(requestId)) {
return;
}
aborted = true;
pendingUserInputs.delete(requestId);
Effect.runFork(Deferred.succeed(answersDeferred, {} as ProviderUserInputAnswers));
};
@@ -2551,13 +2207,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
},
});
if (aborted) {
return {
behavior: "deny",
message: "User cancelled tool execution.",
} satisfies PermissionResult;
}
// Return the answers to the SDK in the expected format:
// { questions: [...], answers: { questionText: selectedLabel } }
return {
@@ -2728,16 +2377,21 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
);
const providerOptions = input.providerOptions?.claudeAgent;
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null);
const caps = getModelCapabilities("claudeAgent", modelSelection?.model);
const requestedEffort = resolveReasoningEffortForProvider(
"claudeAgent",
input.modelOptions?.claudeAgent?.effort ?? null,
);
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
const effort =
requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
requestedEffort && supportedEffortOptions.includes(requestedEffort)
? requestedEffort
: null;
const fastMode =
input.modelOptions?.claudeAgent?.fastMode === true && supportsClaudeFastMode(input.model);
const thinking =
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
? modelSelection.options.thinking
typeof input.modelOptions?.claudeAgent?.thinking === "boolean" &&
supportsClaudeThinkingToggle(input.model)
? input.modelOptions.claudeAgent.thinking
: undefined;
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
const permissionMode =
@@ -2750,9 +2404,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const queryOptions: ClaudeQueryOptions = {
...(input.cwd ? { cwd: input.cwd } : {}),
...(modelSelection?.model ? { model: modelSelection.model } : {}),
pathToClaudeCodeExecutable: providerOptions?.binaryPath ?? "claude",
settingSources: [...CLAUDE_SETTING_SOURCES],
...(input.model ? { model: input.model } : {}),
...(providerOptions?.binaryPath
? { pathToClaudeCodeExecutable: providerOptions.binaryPath }
: {}),
...(effectiveEffort ? { effort: effectiveEffort } : {}),
...(permissionMode ? { permissionMode } : {}),
...(permissionMode === "bypassPermissions"
@@ -2762,8 +2417,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
: {}),
...(Object.keys(settings).length > 0 ? { settings } : {}),
...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),
...(newSessionId ? { sessionId: newSessionId } : {}),
...(resumeState?.resume ? { resume: resumeState.resume } : {}),
...(resumeState?.resumeSessionAt ? { resumeSessionAt: resumeState.resumeSessionAt } : {}),
includePartialMessages: true,
canUseTool,
env: process.env,
@@ -2791,11 +2446,11 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
status: "ready",
runtimeMode: input.runtimeMode,
...(input.cwd ? { cwd: input.cwd } : {}),
...(modelSelection?.model ? { model: modelSelection.model } : {}),
...(input.model ? { model: input.model } : {}),
...(threadId ? { threadId } : {}),
resumeCursor: {
...(threadId ? { threadId } : {}),
...(sessionId ? { resume: sessionId } : {}),
...(resumeState?.resume ? { resume: resumeState.resume } : {}),
...(resumeState?.resumeSessionAt
? { resumeSessionAt: resumeState.resumeSessionAt }
: {}),
@@ -2809,17 +2464,14 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
session,
promptQueue,
query: queryRuntime,
streamFiber: undefined,
startedAt,
basePermissionMode: permissionMode,
resumeSessionId: sessionId,
resumeSessionId: resumeState?.resume,
pendingApprovals,
pendingUserInputs,
turns: [],
inFlightTools,
turnState: undefined,
lastKnownContextWindow: undefined,
lastKnownTokenUsage: undefined,
lastAssistantUuid: resumeState?.resumeSessionAt,
lastThreadStartedId: undefined,
stopped: false,
@@ -2847,7 +2499,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
threadId,
payload: {
config: {
...(modelSelection?.model ? { model: modelSelection.model } : {}),
...(input.model ? { model: input.model } : {}),
...(input.cwd ? { cwd: input.cwd } : {}),
...(effectiveEffort ? { effort: effectiveEffort } : {}),
...(permissionMode ? { permissionMode } : {}),
@@ -2873,17 +2525,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
providerRefs: {},
});
const streamFiber = Effect.runFork(runSdkStream(context));
context.streamFiber = streamFiber;
streamFiber.addObserver((exit) => {
if (context.stopped) {
return;
}
if (context.streamFiber === streamFiber) {
context.streamFiber = undefined;
}
Effect.runFork(handleStreamExit(context, exit));
});
Effect.runFork(runSdkStream(context));
return {
...session,
@@ -2893,8 +2535,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const sendTurn: ClaudeAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
const context = yield* requireSession(input.threadId);
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
if (context.turnState) {
// Auto-close a stale synthetic turn (from background agent responses
@@ -2902,9 +2542,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
yield* completeTurn(context, "completed");
}
if (modelSelection?.model) {
if (input.model) {
yield* Effect.tryPromise({
try: () => context.query.setModel(modelSelection.model),
try: () => context.query.setModel(input.model),
catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause),
});
}
@@ -2934,6 +2574,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
assistantTextBlocks: new Map(),
assistantTextBlockOrder: [],
capturedProposedPlanKeys: new Set(),
taskItemIds: new Map(),
nextSyntheticAssistantBlockIndex: -1,
};
@@ -2954,14 +2595,11 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
createdAt: turnStartedStamp.createdAt,
threadId: context.session.threadId,
turnId,
payload: modelSelection?.model ? { model: modelSelection.model } : {},
payload: input.model ? { model: input.model } : {},
providerRefs: {},
});
const message = yield* buildUserMessageEffect(input, {
fileSystem,
attachmentsDir: serverConfig.attachmentsDir,
});
const message = buildUserMessage(input);
yield* Queue.offer(context.promptQueue, {
type: "message",
@@ -0,0 +1,149 @@
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { query, type SpawnOptions, type SpawnedProcess } from "@anthropic-ai/claude-agent-sdk";
import { afterEach, describe, expect, it } from "vitest";
async function* emptyPrompt(): AsyncGenerator<never, void, void> {}
class FakeClaudeCodeProcess implements SpawnedProcess {
readonly stdin = new PassThrough();
readonly stdout = new PassThrough();
killed = false;
exitCode: number | null = null;
private readonly events = new EventEmitter();
private bufferedInput = "";
constructor(
private readonly onMessage: (
message: Record<string, unknown>,
process: FakeClaudeCodeProcess,
) => void,
) {
this.stdin.setEncoding("utf8");
this.stdin.on("data", (chunk: string) => {
this.bufferedInput += chunk;
this.drainInput();
});
}
emitJson(message: unknown): void {
this.stdout.write(`${JSON.stringify(message)}\n`);
}
kill(_signal: NodeJS.Signals): boolean {
this.killed = true;
this.exitCode = 0;
this.stdout.end();
this.events.emit("exit", 0, null);
return true;
}
on(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.on(event, listener);
}
once(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.once(event, listener);
}
off(
event: "exit" | "error",
listener:
| ((code: number | null, signal: NodeJS.Signals | null) => void)
| ((error: Error) => void),
): void {
this.events.off(event, listener);
}
private drainInput(): void {
while (true) {
const newlineIndex = this.bufferedInput.indexOf("\n");
if (newlineIndex === -1) {
return;
}
const line = this.bufferedInput.slice(0, newlineIndex).trim();
this.bufferedInput = this.bufferedInput.slice(newlineIndex + 1);
if (line.length === 0) {
continue;
}
this.onMessage(JSON.parse(line) as Record<string, unknown>, this);
}
}
}
describe("Claude SDK fast mode probe", () => {
let activeQuery: ReturnType<typeof query> | null = null;
afterEach(() => {
activeQuery?.close();
activeQuery = null;
});
it("passes fast mode through the SDK settings flag", async () => {
let spawnOptions: SpawnOptions | undefined;
activeQuery = query({
prompt: emptyPrompt(),
options: {
persistSession: false,
settings: {
fastMode: true,
},
spawnClaudeCodeProcess: (options): SpawnedProcess => {
spawnOptions = options;
return new FakeClaudeCodeProcess((message, process) => {
if (
message.type !== "control_request" ||
typeof message.request_id !== "string" ||
!message.request ||
typeof message.request !== "object" ||
(message.request as { subtype?: unknown }).subtype !== "initialize"
) {
return;
}
process.emitJson({
type: "control_response",
response: {
subtype: "success",
request_id: message.request_id,
response: {
commands: [],
agents: [],
output_style: "default",
available_output_styles: ["default"],
models: [],
account: {
subscriptionType: "max",
},
fast_mode_state: "on",
},
},
});
});
},
},
});
const initialization = await activeQuery.initializationResult();
expect(initialization.fast_mode_state).toBe("on");
expect(spawnOptions).toBeDefined();
const settingsFlagIndex = spawnOptions?.args.indexOf("--settings") ?? -1;
expect(settingsFlagIndex).toBeGreaterThan(-1);
expect(JSON.parse(spawnOptions?.args[settingsFlagIndex + 1] ?? "")).toEqual({
fastMode: true,
});
});
});
@@ -188,10 +188,9 @@ validationLayer("CodexAdapterLive validation", (it) => {
yield* adapter.startSession({
provider: "codex",
threadId: asThreadId("thread-1"),
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
model: "gpt-5.3-codex",
modelOptions: {
codex: {
fastMode: true,
},
},
@@ -257,10 +256,9 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
adapter.sendTurn({
threadId: asThreadId("sess-missing"),
input: "hello",
modelSelection: {
provider: "codex",
model: "gpt-5.3-codex",
options: {
model: "gpt-5.3-codex",
modelOptions: {
codex: {
reasoningEffort: "high",
fastMode: true,
},
@@ -814,6 +812,7 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-parent"),
itemId: asItemId("call-collab-1"),
createdAt: new Date().toISOString(),
method: "codex/event/task_started",
payload: {
@@ -837,74 +836,12 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
return;
}
assert.equal(firstEvent.value.turnId, "turn-parent");
assert.equal(firstEvent.value.itemId, "call-collab-1");
assert.equal(firstEvent.value.providerRefs?.providerTurnId, "turn-parent");
assert.equal(firstEvent.value.providerRefs?.providerItemId, "call-collab-1");
assert.equal(firstEvent.value.payload.taskId, "turn-child");
}),
);
it.effect("unwraps Codex token usage payloads for context window events", () =>
Effect.gen(function* () {
const adapter = yield* CodexAdapter;
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
lifecycleManager.emit("event", {
id: asEventId("evt-codex-thread-token-usage-updated"),
kind: "notification",
provider: "codex",
threadId: asThreadId("thread-1"),
turnId: asTurnId("turn-1"),
createdAt: new Date().toISOString(),
method: "thread/tokenUsage/updated",
payload: {
threadId: "thread-1",
turnId: "turn-1",
tokenUsage: {
total: {
inputTokens: 11_833,
cachedInputTokens: 3456,
outputTokens: 6,
reasoningOutputTokens: 0,
totalTokens: 11_839,
},
last: {
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
totalTokens: 126,
},
modelContextWindow: 258_400,
},
},
} satisfies ProviderEvent);
const firstEvent = yield* Fiber.join(firstEventFiber);
assert.equal(firstEvent._tag, "Some");
if (firstEvent._tag !== "Some") {
return;
}
assert.equal(firstEvent.value.type, "thread.token-usage.updated");
if (firstEvent.value.type !== "thread.token-usage.updated") {
return;
}
assert.deepEqual(firstEvent.value.payload.usage, {
usedTokens: 126,
totalProcessedTokens: 11_839,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
outputTokens: 6,
reasoningOutputTokens: 0,
lastUsedTokens: 126,
lastInputTokens: 120,
lastCachedInputTokens: 0,
lastOutputTokens: 6,
lastReasoningOutputTokens: 0,
compactsAutomatically: true,
});
}),
);
});
afterAll(() => {
@@ -11,7 +11,6 @@ import {
type CanonicalRequestType,
type ProviderEvent,
type ProviderRuntimeEvent,
type ThreadTokenUsageSnapshot,
type ProviderUserInputAnswers,
RuntimeItemId,
RuntimeRequestId,
@@ -110,48 +109,6 @@ function asNumber(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
const usage = asObject(value);
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
const lastUsage = asObject(usage?.last_token_usage ?? usage?.last);
const totalProcessedTokens =
asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens);
const usedTokens =
asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens;
if (usedTokens === undefined || usedTokens <= 0) {
return undefined;
}
const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow);
const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens);
const cachedInputTokens =
asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens);
const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens);
const reasoningOutputTokens =
asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens);
return {
usedTokens,
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
? { totalProcessedTokens }
: {}),
...(maxTokens !== undefined ? { maxTokens } : {}),
...(inputTokens !== undefined ? { inputTokens } : {}),
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(outputTokens !== undefined ? { outputTokens } : {}),
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),
...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),
...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),
...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),
...(reasoningOutputTokens !== undefined
? { lastReasoningOutputTokens: reasoningOutputTokens }
: {}),
compactsAutomatically: true,
};
}
function toTurnId(value: string | undefined): TurnId | undefined {
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
}
@@ -751,17 +708,12 @@ function mapToRuntimeEvents(
}
if (event.method === "thread/tokenUsage/updated") {
const tokenUsage = asObject(payload?.tokenUsage);
const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload);
if (!normalizedUsage) {
return [];
}
return [
{
type: "thread.token-usage.updated",
...runtimeEventBase(event, canonicalThreadId),
payload: {
usage: normalizedUsage,
usage: event.payload ?? {},
},
},
];
@@ -1361,12 +1313,8 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
runtimeMode: input.runtimeMode,
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
: {}),
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
};
return Effect.tryPromise({
@@ -1388,7 +1336,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
(attachment) =>
Effect.gen(function* () {
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment,
});
if (!attachmentPath) {
@@ -1422,17 +1370,11 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
const managerInput = {
threadId: input.threadId,
...(input.input !== undefined ? { input: input.input } : {}),
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.reasoningEffort !== undefined
? { effort: input.modelSelection.options.reasoningEffort }
: {}),
...(input.modelSelection?.provider === "codex" &&
input.modelSelection.options?.fastMode
? { serviceTier: "fast" }
...(input.model !== undefined ? { model: input.model } : {}),
...(input.modelOptions?.codex?.reasoningEffort !== undefined
? { effort: input.modelOptions.codex.reasoningEffort }
: {}),
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
...(input.interactionMode !== undefined
? { interactionMode: input.interactionMode }
: {}),
@@ -195,21 +195,9 @@ function makeFakeCodexAdapter(provider: ProviderKind = "codex") {
Effect.runSync(PubSub.publish(runtimeEventPubSub, event as unknown as ProviderRuntimeEvent));
};
const updateSession = (
threadId: ThreadId,
update: (session: ProviderSession) => ProviderSession,
): void => {
const existing = sessions.get(threadId);
if (!existing) {
return;
}
sessions.set(threadId, update(existing));
};
return {
adapter,
emit,
updateSession,
startSession,
sendTurn,
interruptTurn,
@@ -360,29 +348,16 @@ it.effect(
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const updatedResumeCursor = {
threadId: asThreadId("thread-1"),
resume: "resume-session-1",
resumeSessionAt: "assistant-message-1",
turnCount: 1,
};
const startedSession = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
const threadId = asThreadId("thread-1");
const session = yield* provider.startSession(threadId, {
return yield* provider.startSession(threadId, {
provider: "codex",
cwd: "/tmp/project",
runtimeMode: "full-access",
threadId,
});
firstCodex.updateSession(threadId, (existing) => ({
...existing,
status: "ready",
resumeCursor: updatedResumeCursor,
updatedAt: new Date(Date.now() + 1_000).toISOString(),
}));
return session;
}).pipe(Effect.provide(firstProviderLayer));
const persistedAfterStopAll = yield* Effect.gen(function* () {
@@ -392,7 +367,7 @@ it.effect(
assert.equal(Option.isSome(persistedAfterStopAll), true);
if (Option.isSome(persistedAfterStopAll)) {
assert.equal(persistedAfterStopAll.value.status, "stopped");
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, updatedResumeCursor);
assert.deepEqual(persistedAfterStopAll.value.resumeCursor, startedSession.resumeCursor);
}
const secondCodex = makeFakeCodexAdapter();
@@ -435,7 +410,7 @@ it.effect(
};
assert.equal(startPayload.provider, "codex");
assert.equal(startPayload.cwd, "/tmp/project");
assert.deepEqual(startPayload.resumeCursor, updatedResumeCursor);
assert.deepEqual(startPayload.resumeCursor, startedSession.resumeCursor);
assert.equal(startPayload.threadId, startedSession.threadId);
}
assert.equal(secondCodex.rollbackThread.mock.calls.length, 1);
@@ -633,10 +608,8 @@ routing.layer("ProviderServiceLive routing", (it) => {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-send-turn"),
cwd: "/tmp/project-claude-send-turn",
modelSelection: {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
modelOptions: {
claudeAgent: {
effort: "max",
},
},
@@ -660,16 +633,14 @@ routing.layer("ProviderServiceLive routing", (it) => {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
modelSelection?: unknown;
modelOptions?: unknown;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
assert.deepEqual(startPayload.modelSelection, {
provider: "claudeAgent",
model: "claude-opus-4-6",
options: {
assert.deepEqual(startPayload.modelOptions, {
claudeAgent: {
effort: "max",
},
});
@@ -745,96 +716,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
}
}),
);
it.effect("reuses persisted resume cursor when startSession is called after a restart", () =>
Effect.gen(function* () {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "t3-provider-service-start-"));
const dbPath = path.join(tempDir, "orchestration.sqlite");
const persistenceLayer = makeSqlitePersistenceLive(dbPath);
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(persistenceLayer),
);
const firstClaude = makeFakeCodexAdapter("claudeAgent");
const firstRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "claudeAgent"
? Effect.succeed(firstClaude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["claudeAgent"]),
};
const firstDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
const initial = yield* Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession(asThreadId("thread-claude-start"), {
provider: "claudeAgent",
threadId: asThreadId("thread-claude-start"),
cwd: "/tmp/project-claude-start",
runtimeMode: "full-access",
});
}).pipe(Effect.provide(firstProviderLayer));
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.listSessions();
}).pipe(Effect.provide(firstProviderLayer));
const secondClaude = makeFakeCodexAdapter("claudeAgent");
const secondRegistry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "claudeAgent"
? Effect.succeed(secondClaude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["claudeAgent"]),
};
const secondDirectoryLayer = ProviderSessionDirectoryLive.pipe(
Layer.provide(runtimeRepositoryLayer),
);
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
Layer.provide(AnalyticsService.layerTest),
);
secondClaude.startSession.mockClear();
yield* Effect.gen(function* () {
const provider = yield* ProviderService;
yield* provider.startSession(initial.threadId, {
provider: "claudeAgent",
threadId: initial.threadId,
cwd: "/tmp/project-claude-start",
runtimeMode: "full-access",
});
}).pipe(Effect.provide(secondProviderLayer));
assert.equal(secondClaude.startSession.mock.calls.length, 1);
const resumedStartInput = secondClaude.startSession.mock.calls[0]?.[0];
assert.equal(typeof resumedStartInput === "object" && resumedStartInput !== null, true);
if (resumedStartInput && typeof resumedStartInput === "object") {
const startPayload = resumedStartInput as {
provider?: string;
cwd?: string;
resumeCursor?: unknown;
threadId?: string;
};
assert.equal(startPayload.provider, "claudeAgent");
assert.equal(startPayload.cwd, "/tmp/project-claude-start");
assert.deepEqual(startPayload.resumeCursor, initial.resumeCursor);
assert.equal(startPayload.threadId, initial.threadId);
}
fs.rmSync(tempDir, { recursive: true, force: true });
}).pipe(Effect.provide(NodeServices.layer)),
);
});
const fanout = makeProviderServiceLayer();
@@ -852,7 +733,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
const consumer = yield* Stream.runForEach(provider.streamEvents, (event) =>
Ref.update(eventsRef, (current) => [...current, event]),
).pipe(Effect.forkChild);
yield* sleep(50);
yield* sleep(20);
const completedEvent: LegacyProviderRuntimeEvent = {
type: "turn.completed",
@@ -865,7 +746,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
};
fanout.codex.emit(completedEvent);
yield* sleep(50);
yield* sleep(20);
const events = yield* Ref.get(eventsRef);
yield* Fiber.interrupt(consumer);
@@ -891,7 +772,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
Stream.runForEach((event) => Ref.update(receivedRef, (current) => [...current, event])),
Effect.forkChild,
);
yield* sleep(50);
yield* sleep(20);
fanout.codex.emit({
type: "tool.started",
@@ -955,7 +836,7 @@ fanout.layer("ProviderServiceLive fanout", (it) => {
Stream.runForEach(() => Effect.fail("listener crash")),
Effect.forkChild,
);
yield* sleep(50);
yield* sleep(20);
const events: ReadonlyArray<LegacyProviderRuntimeEvent> = [
{
@@ -10,7 +10,6 @@
* @module ProviderServiceLive
*/
import {
ModelSelection,
NonNegativeInt,
ThreadId,
ProviderInterruptTurnInput,
@@ -89,35 +88,27 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: {
readonly modelSelection?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
): Record<string, unknown> {
return {
cwd: session.cwd ?? null,
model: session.model ?? null,
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
...(extra?.lastRuntimeEventAt !== undefined
? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
: {}),
};
}
function readPersistedModelSelection(
function readPersistedModelOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): ModelSelection | undefined {
): Record<string, unknown> | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
return Schema.is(ModelSelection)(raw) ? raw : undefined;
const raw = "modelOptions" in runtimePayload ? runtimePayload.modelOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
}
function readPersistedProviderOptions(
@@ -171,12 +162,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const upsertSessionBinding = (
session: ProviderSession,
threadId: ThreadId,
extra?: {
readonly modelSelection?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
extra?: { readonly modelOptions?: unknown; readonly providerOptions?: unknown },
) =>
directory.upsert({
threadId,
@@ -191,6 +177,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const adapters = yield* Effect.forEach(providers, (provider) =>
registry.getByProvider(provider),
);
const processRuntimeEvent = (event: ProviderRuntimeEvent): Effect.Effect<void> =>
publishRuntimeEvent(event);
@@ -238,14 +225,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
@@ -308,17 +295,8 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
threadId,
provider: parsed.provider ?? "codex",
};
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
(persistedBinding?.provider === input.provider
? persistedBinding.resumeCursor
: undefined);
const adapter = yield* registry.getByProvider(input.provider);
const session = yield* adapter.startSession({
...input,
...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}),
});
const session = yield* adapter.startSession(input);
if (session.provider !== adapter.provider) {
return yield* toValidationError(
@@ -328,7 +306,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
}
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
modelOptions: input.modelOptions,
providerOptions: input.providerOptions,
});
yield* analytics.record("provider.session.started", {
@@ -336,9 +314,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
runtimeMode: input.runtimeMode,
hasResumeCursor: session.resumeCursor !== undefined,
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
hasModel:
typeof input.modelSelection?.model === "string" &&
input.modelSelection.model.trim().length > 0,
hasModel: typeof input.model === "string" && input.model.trim().length > 0,
});
return session;
@@ -374,7 +350,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
status: "running",
...(turn.resumeCursor !== undefined ? { resumeCursor: turn.resumeCursor } : {}),
runtimePayload: {
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
activeTurnId: turn.turnId,
lastRuntimeEvent: "provider.sendTurn",
lastRuntimeEventAt: new Date().toISOString(),
@@ -382,7 +357,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
});
yield* analytics.record("provider.turn.sent", {
provider: routed.adapter.provider,
model: input.modelSelection?.model,
model: input.model,
interactionMode: input.interactionMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
@@ -538,17 +513,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const runStopAll = () =>
Effect.gen(function* () {
const threadIds = yield* directory.listThreadIds();
const activeSessions = yield* Effect.forEach(adapters, (adapter) =>
adapter.listSessions(),
).pipe(
Effect.map((sessionsByAdapter) => sessionsByAdapter.flatMap((sessions) => sessions)),
);
yield* Effect.forEach(activeSessions, (session) =>
upsertSessionBinding(session, session.threadId, {
lastRuntimeEvent: "provider.stopAll",
lastRuntimeEventAt: new Date().toISOString(),
}),
).pipe(Effect.asVoid);
yield* Effect.forEach(adapters, (adapter) => adapter.stopAll()).pipe(Effect.asVoid);
yield* Effect.forEach(threadIds, (threadId) =>
directory.getProvider(threadId).pipe(
+24 -29
View File
@@ -1,5 +1,7 @@
import path from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { Effect, FileSystem, Layer, Path } from "effect";
import { Effect, FileSystem, Layer } from "effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery";
@@ -30,34 +32,21 @@ import { KeybindingsLive } from "./keybindings";
import { GitManagerLive } from "./git/Layers/GitManager";
import { GitCoreLive } from "./git/Layers/GitCore";
import { GitHubCliLive } from "./git/Layers/GitHubCli";
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
import { PtyAdapter } from "./terminal/Services/PTY";
import { CodexTextGenerationLive } from "./git/Layers/CodexTextGeneration";
import { GitServiceLive } from "./git/Layers/GitService";
import { BunPtyAdapterLive } from "./terminal/Layers/BunPTY";
import { NodePtyAdapterLive } from "./terminal/Layers/NodePTY";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
type RuntimePtyAdapterLoader = {
layer: Layer.Layer<PtyAdapter, never, FileSystem.FileSystem | Path.Path>;
};
const runtimePtyAdapterLoaders = {
bun: () => import("./terminal/Layers/BunPTY"),
node: () => import("./terminal/Layers/NodePTY"),
} satisfies Record<string, () => Promise<RuntimePtyAdapterLoader>>;
const makeRuntimePtyAdapterLayer = () =>
Effect.gen(function* () {
const runtime = process.versions.bun !== undefined ? "bun" : "node";
const loader = runtimePtyAdapterLoaders[runtime];
const ptyAdapterModule = yield* Effect.promise<RuntimePtyAdapterLoader>(loader);
return ptyAdapterModule.layer;
}).pipe(Layer.unwrap);
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
ProviderUnsupportedError,
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
> {
return Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
const { stateDir } = yield* ServerConfig;
const providerLogsDir = path.join(stateDir, "logs", "provider");
const providerEventLogPath = path.join(providerLogsDir, "events.log");
const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
stream: "native",
});
@@ -85,8 +74,8 @@ export function makeServerProviderLayer(): Layer.Layer<
}
export function makeServerRuntimeServicesLayer() {
const textGenerationLayer = RoutingTextGenerationLive;
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
const gitCoreLayer = GitCoreLive.pipe(Layer.provideMerge(GitServiceLive));
const textGenerationLayer = CodexTextGenerationLive;
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionPipelineLive),
@@ -96,13 +85,13 @@ export function makeServerRuntimeServicesLayer() {
const checkpointDiffQueryLayer = CheckpointDiffQueryLive.pipe(
Layer.provideMerge(OrchestrationProjectionSnapshotQueryLive),
Layer.provideMerge(checkpointStoreLayer),
Layer.provideMerge(CheckpointStoreLive),
);
const runtimeServicesLayer = Layer.mergeAll(
orchestrationLayer,
OrchestrationProjectionSnapshotQueryLive,
checkpointStoreLayer,
CheckpointStoreLive,
checkpointDiffQueryLayer,
RuntimeReceiptBusLive,
);
@@ -111,7 +100,7 @@ export function makeServerRuntimeServicesLayer() {
);
const providerCommandReactorLayer = ProviderCommandReactorLive.pipe(
Layer.provideMerge(runtimeServicesLayer),
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(textGenerationLayer),
);
const checkpointReactorLayer = CheckpointReactorLive.pipe(
@@ -123,17 +112,23 @@ export function makeServerRuntimeServicesLayer() {
Layer.provideMerge(checkpointReactorLayer),
);
const terminalLayer = TerminalManagerLive.pipe(Layer.provide(makeRuntimePtyAdapterLayer()));
const terminalLayer = TerminalManagerLive.pipe(
Layer.provide(
typeof Bun !== "undefined" && process.platform !== "win32"
? BunPtyAdapterLive
: NodePtyAdapterLive,
),
);
const gitManagerLayer = GitManagerLive.pipe(
Layer.provideMerge(GitCoreLive),
Layer.provideMerge(gitCoreLayer),
Layer.provideMerge(GitHubCliLive),
Layer.provideMerge(textGenerationLayer),
);
return Layer.mergeAll(
orchestrationReactorLayer,
GitCoreLive,
gitCoreLayer,
gitManagerLayer,
terminalLayer,
KeybindingsLive,
+7 -3
View File
@@ -1,4 +1,5 @@
import fs from "node:fs";
import path from "node:path";
import { Effect, Logger } from "effect";
import * as Layer from "effect/Layer";
@@ -6,13 +7,16 @@ import * as Layer from "effect/Layer";
import { ServerConfig } from "./config";
export const ServerLoggerLive = Effect.gen(function* () {
const { logsDir, serverLogPath } = yield* ServerConfig;
const config = yield* ServerConfig;
const logDir = path.join(config.stateDir, "logs");
const logPath = path.join(logDir, "server.log");
yield* Effect.sync(() => {
fs.mkdirSync(logsDir, { recursive: true });
fs.mkdirSync(logDir, { recursive: true });
});
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(serverLogPath));
const fileLogger = Logger.formatSimple.pipe(Logger.toFile(logPath));
return Logger.layer([Logger.defaultLogger, fileLogger], {
mergeWithExisting: false,
-283
View File
@@ -1,283 +0,0 @@
/**
* ServerSettings - Server-authoritative settings service.
*
* Owns persistence, validation, and change notification of settings that affect
* server-side behavior (binary paths, streaming mode, env mode, custom models,
* text generation model selection).
*
* Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +
* Semaphore + FileSystem.watch for concurrency and external edit detection.
*
* @module ServerSettings
*/
import {
DEFAULT_SERVER_SETTINGS,
type ProviderStartOptions,
ServerSettings,
type ServerSettingsPatch,
} from "@t3tools/contracts";
import {
Cache,
Deferred,
Effect,
Exit,
FileSystem,
Layer,
Path,
PubSub,
Ref,
Schema,
SchemaGetter,
Scope,
ServiceMap,
Stream,
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
"ServerSettingsError",
{
settingsPath: Schema.String,
detail: Schema.String,
cause: Schema.optional(Schema.Defect),
},
) {
override get message(): string {
return `Server settings error at ${this.settingsPath}: ${this.detail}`;
}
}
export interface ServerSettingsShape {
/** Start the settings runtime and attach file watching. */
readonly start: Effect.Effect<void, ServerSettingsError>;
/** Await settings runtime readiness. */
readonly ready: Effect.Effect<void, ServerSettingsError>;
/** Read the current settings. */
readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
/** Patch settings and persist. Returns the new full settings object. */
readonly updateSettings: (
patch: ServerSettingsPatch,
) => Effect.Effect<ServerSettings, ServerSettingsError>;
/** Stream of settings change events. */
readonly streamChanges: Stream.Stream<ServerSettings>;
}
export class ServerSettingsService extends ServiceMap.Service<
ServerSettingsService,
ServerSettingsShape
>()("t3/serverSettings/ServerSettingsService") {
static readonly layerTest = (overrides: Partial<ServerSettings> = {}) =>
Layer.succeed(ServerSettingsService, {
start: Effect.void,
ready: Effect.void,
getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
updateSettings: () => Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
streamChanges: Stream.empty,
} satisfies ServerSettingsShape);
}
/**
* Derive `ProviderStartOptions` from server settings.
* Replaces the client-side `getProviderStartOptions()` function.
*/
export function deriveProviderStartOptions(
settings: ServerSettings,
): ProviderStartOptions | undefined {
const providerOptions: ProviderStartOptions = {
...(settings.codex
? {
codex: {
...(settings.codex.binaryPath ? { binaryPath: settings.codex.binaryPath } : {}),
...(settings.codex.homePath ? { homePath: settings.codex.homePath } : {}),
},
}
: {}),
...(settings.claude?.binaryPath
? {
claudeAgent: {
binaryPath: settings.claude.binaryPath,
},
}
: {}),
};
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
}
const ServerSettingsJson = Schema.fromJsonString(ServerSettings);
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
SchemaGetter.stringifyJson({ space: 2 }),
);
const ServerSettingsPrettyJson = ServerSettingsJson.pipe(
Schema.encode({
decode: PrettyJsonString,
encode: PrettyJsonString,
}),
);
const makeServerSettings = Effect.gen(function* () {
const { settingsPath } = yield* ServerConfig;
const fs = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const writeSemaphore = yield* Semaphore.make(1);
const cacheKey = "settings" as const;
const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
const startedRef = yield* Ref.make(false);
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
const watcherScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
const emitChange = (settings: ServerSettings) =>
PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
const readConfigExists = fs.exists(settingsPath).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to check settings file existence",
cause,
}),
),
);
const readRawConfig = fs.readFileString(settingsPath).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to read settings file",
cause,
}),
),
);
const loadSettingsFromDisk = Effect.gen(function* () {
if (!(yield* readConfigExists)) {
return DEFAULT_SERVER_SETTINGS;
}
const raw = yield* readRawConfig;
const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
if (decoded._tag === "Failure") {
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
path: settingsPath,
});
return DEFAULT_SERVER_SETTINGS;
}
return decoded.value;
});
const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
capacity: 1,
lookup: () => loadSettingsFromDisk,
});
const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
const writeSettingsAtomically = (settings: ServerSettings) => {
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
return Schema.encodeEffect(ServerSettingsPrettyJson)(settings).pipe(
Effect.map((encoded) => `${encoded}\n`),
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to write settings file",
cause,
}),
),
);
};
const revalidateAndEmit = writeSemaphore.withPermits(1)(
Effect.gen(function* () {
yield* Cache.invalidate(settingsCache, cacheKey);
const settings = yield* getSettingsFromCache;
yield* emitChange(settings);
}),
);
const startWatcher = Effect.gen(function* () {
const settingsDir = pathService.dirname(settingsPath);
const settingsFile = pathService.basename(settingsPath);
const settingsPathResolved = pathService.resolve(settingsPath);
yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath,
detail: "failed to prepare settings directory",
cause,
}),
),
);
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
yield* Stream.runForEach(fs.watch(settingsDir), (event) => {
const isTargetEvent =
event.path === settingsFile ||
event.path === settingsPath ||
pathService.resolve(settingsDir, event.path) === settingsPathResolved;
if (!isTargetEvent) {
return Effect.void;
}
return revalidateAndEmitSafely;
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
});
const start = Effect.gen(function* () {
const alreadyStarted = yield* Ref.get(startedRef);
if (alreadyStarted) {
return yield* Deferred.await(startedDeferred);
}
yield* Ref.set(startedRef, true);
const startup = Effect.gen(function* () {
yield* startWatcher;
yield* Cache.invalidate(settingsCache, cacheKey);
yield* getSettingsFromCache;
});
const startupExit = yield* Effect.exit(startup);
if (startupExit._tag === "Failure") {
yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
return yield* Effect.failCause(startupExit.cause);
}
yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
});
return {
start,
ready: Deferred.await(startedDeferred),
getSettings: getSettingsFromCache,
updateSettings: (patch) =>
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
const next: ServerSettings = { ...current, ...patch };
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
return next;
}),
),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ServerSettingsShape;
});
export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings);
+4 -25
View File
@@ -9,10 +9,6 @@ const CodexAuthJsonSchema = Schema.Struct({
}),
});
const ClaudeJsonSchema = Schema.Struct({
userID: Schema.String,
});
class IdentifyUserError extends Schema.TaggedErrorClass<IdentifyUserError>()("IdentifyUserError", {
message: Schema.String,
cause: Schema.optional(Schema.Defect),
@@ -41,23 +37,12 @@ const getCodexAccountId = Effect.gen(function* () {
return authJson.tokens.account_id;
});
const getClaudeUserId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const claudeJsonPath = path.join(homedir(), ".claude.json");
const claudeJson = yield* Effect.flatMap(
fileSystem.readFileString(claudeJsonPath),
Schema.decodeEffect(Schema.fromJsonString(ClaudeJsonSchema)),
);
return claudeJson.userID;
});
const upsertAnonymousId = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const { anonymousIdPath } = yield* ServerConfig;
const path = yield* Path.Path;
const serverConfig = yield* ServerConfig;
const anonymousIdPath = path.join(serverConfig.stateDir, "anonymous-id");
const anonymousId = yield* fileSystem.readFileString(anonymousIdPath).pipe(
Effect.catch(() =>
Effect.gen(function* () {
@@ -74,8 +59,7 @@ const upsertAnonymousId = Effect.gen(function* () {
/**
* getTelemetryIdentifier - Users are "identified" by finding the first match of the following, then hashing the value.
* 1. ~/.codex/auth.json tokens.account_id
* 2. ~/.claude.json userID
* 3. ~/.t3/telemetry/anonymous-id
* 2. ~/.t3/telemetry/anonymous-id
*/
export const getTelemetryIdentifier = Effect.gen(function* () {
const codexAccountId = yield* Effect.result(getCodexAccountId);
@@ -83,11 +67,6 @@ export const getTelemetryIdentifier = Effect.gen(function* () {
return yield* hash(codexAccountId.success);
}
const claudeUserId = yield* Effect.result(getClaudeUserId);
if (claudeUserId._tag === "Success") {
return yield* hash(claudeUserId.success);
}
const anonymousId = yield* Effect.result(upsertAnonymousId);
if (anonymousId._tag === "Success") {
return yield* hash(anonymousId.success);
@@ -1,7 +1,7 @@
import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { ConfigProvider, Effect, Layer } from "effect";
import { ConfigProvider, Effect, FileSystem, Layer } from "effect";
import * as HttpServer from "effect/unstable/http/HttpServer";
import * as HttpServerRequest from "effect/unstable/http/HttpServerRequest";
import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
@@ -37,11 +37,14 @@ interface RecordedBatchBody {
it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
it.effect("flush drains all buffered events across multiple batches", () =>
Effect.gen(function* () {
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), {
prefix: "t3-telemetry-base-",
const fileSystem = yield* FileSystem.FileSystem;
const stateDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-telemetry-flush-",
});
const capturedRequests: Array<RecordedBatchRequest> = [];
const serverConfigLayer = ServerConfig.layerTest(process.cwd(), stateDir);
const telemetryLayer = AnalyticsServiceLayerLive.pipe(Layer.provideMerge(serverConfigLayer));
const configLayer = ConfigProvider.layer(
ConfigProvider.fromUnknown({
+2 -4
View File
@@ -86,13 +86,11 @@ class BunPtyProcess implements PtyProcess {
}
}
export const layer = Layer.effect(
export const BunPtyAdapterLive = Layer.effect(
PtyAdapter,
Effect.gen(function* () {
if (process.platform === "win32") {
return yield* Effect.die(
"Bun PTY terminal support is unavailable on Windows. Please use Node.js (e.g. by running `npx t3`) instead.",
);
return yield* Effect.die("Bun PTY terminal support is unavailable on Windows.");
}
return {
spawn: (input) =>
@@ -469,89 +469,6 @@ describe("TerminalManager", () => {
manager.dispose();
});
it("strips replay-unsafe terminal query and reply sequences from persisted history", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("prompt ");
process.emitData("\u001b[32mok\u001b[0m ");
process.emitData("\u001b]11;rgb:ffff/ffff/ffff\u0007");
process.emitData("\u001b[1;1R");
process.emitData("done\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("prompt \u001b[32mok\u001b[0m done\n");
manager.dispose();
});
it("preserves clear and style control sequences while dropping chunk-split query traffic", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before clear\n");
process.emitData("\u001b[H\u001b[2J");
process.emitData("prompt ");
process.emitData("\u001b]11;");
process.emitData("rgb:ffff/ffff/ffff\u0007\u001b[1;1");
process.emitData("R\u001b[36mdone\u001b[0m\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe(
"before clear\n\u001b[H\u001b[2Jprompt \u001b[36mdone\u001b[0m\n",
);
manager.dispose();
});
it("does not leak final bytes from ESC sequences with intermediate bytes", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before ");
process.emitData("\u001b(B");
process.emitData("after\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("before \u001b(Bafter\n");
manager.dispose();
});
it("preserves chunk-split ESC sequences with intermediate bytes without leaking final bytes", async () => {
const { manager, ptyAdapter } = makeManager();
await manager.open(openInput());
const process = ptyAdapter.processes[0];
expect(process).toBeDefined();
if (!process) return;
process.emitData("before ");
process.emitData("\u001b(");
process.emitData("Bafter\n");
await manager.close({ threadId: "thread-1" });
const reopened = await manager.open(openInput());
expect(reopened.history).toBe("before \u001b(Bafter\n");
manager.dispose();
});
it("deletes history file when close(deleteHistory=true)", async () => {
const { manager, ptyAdapter, logsDir } = makeManager();
await manager.open(openInput());
+7 -194
View File
@@ -13,7 +13,7 @@ import {
type TerminalEvent,
type TerminalSessionSnapshot,
} from "@t3tools/contracts";
import { Effect, Encoding, Layer, Schema } from "effect";
import { Effect, Encoding, Layer, Path, Schema } from "effect";
import { createLogger } from "../../logger";
import { PtyAdapter, PtyAdapterShape, type PtyExitEvent, type PtyProcess } from "../Services/PTY";
@@ -254,180 +254,6 @@ function capHistory(history: string, maxLines: number): string {
return hasTrailingNewline ? `${capped}\n` : capped;
}
function isCsiFinalByte(codePoint: number): boolean {
return codePoint >= 0x40 && codePoint <= 0x7e;
}
function shouldStripCsiSequence(body: string, finalByte: string): boolean {
if (finalByte === "n") {
return true;
}
if (finalByte === "R" && /^[0-9;?]*$/.test(body)) {
return true;
}
if (finalByte === "c" && /^[>0-9;?]*$/.test(body)) {
return true;
}
return false;
}
function shouldStripOscSequence(content: string): boolean {
return /^(10|11|12);(?:\?|rgb:)/.test(content);
}
function stripStringTerminator(value: string): string {
if (value.endsWith("\u001b\\")) {
return value.slice(0, -2);
}
const lastCharacter = value.at(-1);
if (lastCharacter === "\u0007" || lastCharacter === "\u009c") {
return value.slice(0, -1);
}
return value;
}
function findStringTerminatorIndex(input: string, start: number): number | null {
for (let index = start; index < input.length; index += 1) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x07 || codePoint === 0x9c) {
return index + 1;
}
if (codePoint === 0x1b && input.charCodeAt(index + 1) === 0x5c) {
return index + 2;
}
}
return null;
}
function isEscapeIntermediateByte(codePoint: number): boolean {
return codePoint >= 0x20 && codePoint <= 0x2f;
}
function isEscapeFinalByte(codePoint: number): boolean {
return codePoint >= 0x30 && codePoint <= 0x7e;
}
function findEscapeSequenceEndIndex(input: string, start: number): number | null {
let cursor = start;
while (cursor < input.length && isEscapeIntermediateByte(input.charCodeAt(cursor))) {
cursor += 1;
}
if (cursor >= input.length) {
return null;
}
return isEscapeFinalByte(input.charCodeAt(cursor)) ? cursor + 1 : start + 1;
}
function sanitizeTerminalHistoryChunk(
pendingControlSequence: string,
data: string,
): { visibleText: string; pendingControlSequence: string } {
const input = `${pendingControlSequence}${data}`;
let visibleText = "";
let index = 0;
const append = (value: string) => {
visibleText += value;
};
while (index < input.length) {
const codePoint = input.charCodeAt(index);
if (codePoint === 0x1b) {
const nextCodePoint = input.charCodeAt(index + 1);
if (Number.isNaN(nextCodePoint)) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
if (nextCodePoint === 0x5b) {
let cursor = index + 2;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
const sequence = input.slice(index, cursor + 1);
const body = input.slice(index + 2, cursor);
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
append(sequence);
}
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (
nextCodePoint === 0x5d ||
nextCodePoint === 0x50 ||
nextCodePoint === 0x5e ||
nextCodePoint === 0x5f
) {
const terminatorIndex = findStringTerminatorIndex(input, index + 2);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 2, terminatorIndex));
if (nextCodePoint !== 0x5d || !shouldStripOscSequence(content)) {
append(sequence);
}
index = terminatorIndex;
continue;
}
const escapeSequenceEndIndex = findEscapeSequenceEndIndex(input, index + 1);
if (escapeSequenceEndIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
append(input.slice(index, escapeSequenceEndIndex));
index = escapeSequenceEndIndex;
continue;
}
if (codePoint === 0x9b) {
let cursor = index + 1;
while (cursor < input.length) {
if (isCsiFinalByte(input.charCodeAt(cursor))) {
const sequence = input.slice(index, cursor + 1);
const body = input.slice(index + 1, cursor);
if (!shouldStripCsiSequence(body, input[cursor] ?? "")) {
append(sequence);
}
index = cursor + 1;
break;
}
cursor += 1;
}
if (cursor >= input.length) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
continue;
}
if (codePoint === 0x9d || codePoint === 0x90 || codePoint === 0x9e || codePoint === 0x9f) {
const terminatorIndex = findStringTerminatorIndex(input, index + 1);
if (terminatorIndex === null) {
return { visibleText, pendingControlSequence: input.slice(index) };
}
const sequence = input.slice(index, terminatorIndex);
const content = stripStringTerminator(input.slice(index + 1, terminatorIndex));
if (codePoint !== 0x9d || !shouldStripOscSequence(content)) {
append(sequence);
}
index = terminatorIndex;
continue;
}
append(input[index] ?? "");
index += 1;
}
return { visibleText, pendingControlSequence: "" };
}
function legacySafeThreadId(threadId: string): string {
return threadId.replace(/[^a-zA-Z0-9._-]/g, "_");
}
@@ -552,7 +378,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history,
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -582,12 +407,10 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
existing.cwd = input.cwd;
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (existing.status === "exited" || existing.status === "error") {
existing.runtimeEnv = nextRuntimeEnv;
existing.history = "";
existing.pendingHistoryControlSequence = "";
await this.persistHistory(existing.threadId, existing.terminalId, existing.history);
} else if (currentRuntimeEnv !== nextRuntimeEnv) {
existing.runtimeEnv = nextRuntimeEnv;
@@ -646,7 +469,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
await this.runWithThreadLock(input.threadId, async () => {
const session = this.requireSession(input.threadId, input.terminalId);
session.history = "";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
await this.persistHistory(input.threadId, input.terminalId, session.history);
this.emitEvent({
@@ -675,7 +497,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
status: "starting",
pid: null,
history: "",
pendingHistoryControlSequence: "",
exitCode: null,
exitSignal: null,
updatedAt: new Date().toISOString(),
@@ -699,7 +520,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
const rows = input.rows ?? session.rows;
session.history = "";
session.pendingHistoryControlSequence = "";
await this.persistHistory(input.threadId, input.terminalId, session.history);
await this.startSession(session, { ...input, cols, rows }, "restarted");
return this.snapshot(session);
@@ -874,16 +694,9 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
}
private onProcessData(session: TerminalSessionState, data: string): void {
const sanitized = sanitizeTerminalHistoryChunk(session.pendingHistoryControlSequence, data);
session.pendingHistoryControlSequence = sanitized.pendingControlSequence;
if (sanitized.visibleText.length > 0) {
session.history = capHistory(
`${session.history}${sanitized.visibleText}`,
this.historyLineLimit,
);
this.queuePersist(session.threadId, session.terminalId, session.history);
}
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
session.updatedAt = new Date().toISOString();
this.queuePersist(session.threadId, session.terminalId, session.history);
this.emitEvent({
type: "output",
threadId: session.threadId,
@@ -900,7 +713,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.exitCode = Number.isInteger(event.exitCode) ? event.exitCode : null;
session.exitSignal = Number.isInteger(event.signal) ? event.signal : null;
session.updatedAt = new Date().toISOString();
@@ -924,7 +736,6 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
session.pid = null;
session.hasRunningSubprocess = false;
session.status = "exited";
session.pendingHistoryControlSequence = "";
session.updatedAt = new Date().toISOString();
this.killProcessWithEscalation(process, session.threadId, session.terminalId);
this.evictInactiveSessionsIfNeeded();
@@ -1361,11 +1172,13 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
export const TerminalManagerLive = Layer.effect(
TerminalManager,
Effect.gen(function* () {
const { terminalLogsDir } = yield* ServerConfig;
const { stateDir } = yield* ServerConfig;
const { join } = yield* Path.Path;
const logsDir = join(stateDir, "logs", "terminals");
const ptyAdapter = yield* PtyAdapter;
const runtime = yield* Effect.acquireRelease(
Effect.sync(() => new TerminalManagerRuntime({ logsDir: terminalLogsDir, ptyAdapter })),
Effect.sync(() => new TerminalManagerRuntime({ logsDir, ptyAdapter })),
(r) => Effect.sync(() => r.dispose()),
);
+1 -1
View File
@@ -84,7 +84,7 @@ class NodePtyProcess implements PtyProcess {
}
}
export const layer = Layer.effect(
export const NodePtyAdapterLive = Layer.effect(
PtyAdapter,
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -32,7 +32,6 @@ export interface TerminalSessionState {
status: TerminalSessionStatus;
pid: number | null;
history: string;
pendingHistoryControlSequence: string;
exitCode: number | null;
exitSignal: number | null;
updatedAt: string;
+52 -189
View File
@@ -8,7 +8,7 @@ import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effec
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
import { deriveServerPaths, ServerConfig, type ServerConfigShape } from "./config";
import { ServerConfig, type ServerConfigShape } from "./config";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import {
@@ -53,7 +53,6 @@ import { GitCore } from "./git/Services/GitCore.ts";
import { GitCommandError, GitManagerError } from "./git/Errors.ts";
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
import { ServerSettingsService } from "./serverSettings.ts";
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
@@ -452,16 +451,6 @@ function expectAvailableEditors(value: unknown): void {
}
}
function ensureParentDir(filePath: string): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
}
function deriveServerPathsSync(baseDir: string, devUrl: URL | undefined) {
return Effect.runSync(
deriveServerPaths(baseDir, devUrl).pipe(Effect.provide(NodeServices.layer)),
);
}
describe("WebSocket Server", () => {
let server: Http.Server | null = null;
let serverScope: Scope.Closeable | null = null;
@@ -485,7 +474,7 @@ describe("WebSocket Server", () => {
logWebSocketEvents?: boolean;
devUrl?: string;
authToken?: string;
baseDir?: string;
stateDir?: string;
staticDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
providerHealth?: ProviderHealthShape;
@@ -499,9 +488,7 @@ describe("WebSocket Server", () => {
throw new Error("Test server is already running");
}
const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-");
const devUrl = options.devUrl ? new URL(options.devUrl) : undefined;
const derivedPaths = deriveServerPathsSync(baseDir, devUrl);
const stateDir = options.stateDir ?? makeTempDir("t3code-ws-state-");
const scope = await Effect.runPromise(Scope.make("sequential"));
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
@@ -515,10 +502,10 @@ describe("WebSocket Server", () => {
port: 0,
host: undefined,
cwd: options.cwd ?? "/test/project",
baseDir,
...derivedPaths,
keybindingsConfigPath: path.join(stateDir, "keybindings.json"),
stateDir,
staticDir: options.staticDir,
devUrl,
devUrl: options.devUrl ? new URL(options.devUrl) : undefined,
noBrowser: true,
authToken: options.authToken,
autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false,
@@ -546,7 +533,6 @@ describe("WebSocket Server", () => {
Layer.provideMerge(runtimeLayer),
Layer.provideMerge(providerHealthLayer),
Layer.provideMerge(openLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(serverConfigLayer),
Layer.provideMerge(AnalyticsService.layerTest),
Layer.provideMerge(NodeServices.layer),
@@ -604,13 +590,12 @@ describe("WebSocket Server", () => {
});
it("serves persisted attachments from stateDir", async () => {
const baseDir = makeTempDir("t3code-state-attachments-");
const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined);
const attachmentPath = path.join(attachmentsDir, "thread-a", "message-a", "0.png");
const stateDir = makeTempDir("t3code-state-attachments-");
const attachmentPath = path.join(stateDir, "attachments", "thread-a", "message-a", "0.png");
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
fs.writeFileSync(attachmentPath, Buffer.from("hello-attachment"));
server = await createTestServer({ cwd: "/test/project", baseDir });
server = await createTestServer({ cwd: "/test/project", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -623,10 +608,10 @@ describe("WebSocket Server", () => {
});
it("serves persisted attachments for URL-encoded paths", async () => {
const baseDir = makeTempDir("t3code-state-attachments-encoded-");
const { attachmentsDir } = deriveServerPathsSync(baseDir, undefined);
const stateDir = makeTempDir("t3code-state-attachments-encoded-");
const attachmentPath = path.join(
attachmentsDir,
stateDir,
"attachments",
"thread%20folder",
"message%20folder",
"file%20name.png",
@@ -634,7 +619,7 @@ describe("WebSocket Server", () => {
fs.mkdirSync(path.dirname(attachmentPath), { recursive: true });
fs.writeFileSync(attachmentPath, Buffer.from("hello-encoded-attachment"));
server = await createTestServer({ cwd: "/test/project", baseDir });
server = await createTestServer({ cwd: "/test/project", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -649,11 +634,11 @@ describe("WebSocket Server", () => {
});
it("serves static index for root path", async () => {
const baseDir = makeTempDir("t3code-state-static-root-");
const stateDir = makeTempDir("t3code-state-static-root-");
const staticDir = makeTempDir("t3code-static-root-");
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>static-root</h1>", "utf8");
server = await createTestServer({ cwd: "/test/project", baseDir, staticDir });
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -664,11 +649,11 @@ describe("WebSocket Server", () => {
});
it("rejects static path traversal attempts", async () => {
const baseDir = makeTempDir("t3code-state-static-traversal-");
const stateDir = makeTempDir("t3code-state-static-traversal-");
const staticDir = makeTempDir("t3code-static-traversal-");
fs.writeFileSync(path.join(staticDir, "index.html"), "<h1>safe</h1>", "utf8");
server = await createTestServer({ cwd: "/test/project", baseDir, staticDir });
server = await createTestServer({ cwd: "/test/project", stateDir, staticDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
expect(port).toBeGreaterThan(0);
@@ -705,19 +690,13 @@ describe("WebSocket Server", () => {
id: string;
workspaceRoot: string;
title: string;
defaultModelSelection: {
provider: string;
model: string;
} | null;
defaultModel: string | null;
}>;
threads: Array<{
id: string;
projectId: string;
title: string;
modelSelection: {
provider: string;
model: string;
};
model: string;
branch: string | null;
worktreePath: string | null;
}>;
@@ -733,10 +712,7 @@ describe("WebSocket Server", () => {
id: bootstrapProjectId,
workspaceRoot: "/test/bootstrap-workspace",
title: "bootstrap-workspace",
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
}),
]),
);
@@ -746,10 +722,7 @@ describe("WebSocket Server", () => {
id: bootstrapThreadId,
projectId: bootstrapProjectId,
title: "New thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
branch: null,
worktreePath: null,
}),
@@ -758,16 +731,15 @@ describe("WebSocket Server", () => {
});
it("includes bootstrap ids in welcome when cwd project and thread already exist", async () => {
const baseDir = makeTempDir("t3code-state-bootstrap-existing-");
const { dbPath } = deriveServerPathsSync(baseDir, undefined);
const persistenceLayer = makeSqlitePersistenceLive(dbPath).pipe(
const stateDir = makeTempDir("t3code-state-bootstrap-existing-");
const persistenceLayer = makeSqlitePersistenceLive(path.join(stateDir, "state.sqlite")).pipe(
Layer.provide(NodeServices.layer),
);
const cwd = "/test/bootstrap-existing";
server = await createTestServer({
cwd,
baseDir,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
@@ -790,7 +762,7 @@ describe("WebSocket Server", () => {
server = await createTestServer({
cwd,
baseDir,
stateDir,
persistenceLayer,
autoBootstrapProjectFromCwd: true,
});
@@ -839,12 +811,11 @@ describe("WebSocket Server", () => {
});
it("responds to server.getConfig", async () => {
const baseDir = makeTempDir("t3code-state-get-config-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-get-config-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(keybindingsPath, "[]", "utf8");
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -865,11 +836,11 @@ describe("WebSocket Server", () => {
});
it("bootstraps default keybindings file when missing", async () => {
const baseDir = makeTempDir("t3code-state-bootstrap-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
const stateDir = makeTempDir("t3code-state-bootstrap-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
expect(fs.existsSync(keybindingsPath)).toBe(false);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -895,12 +866,11 @@ describe("WebSocket Server", () => {
});
it("falls back to defaults and reports malformed keybindings config issues", async () => {
const baseDir = makeTempDir("t3code-state-malformed-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-malformed-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(keybindingsPath, "{ not-json", "utf8");
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -927,9 +897,8 @@ describe("WebSocket Server", () => {
});
it("ignores invalid keybinding entries but keeps valid entries and reports issues", async () => {
const baseDir = makeTempDir("t3code-state-partial-invalid-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-partial-invalid-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([
@@ -940,7 +909,7 @@ describe("WebSocket Server", () => {
"utf8",
);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -979,12 +948,11 @@ describe("WebSocket Server", () => {
});
it("pushes server.configUpdated issues when keybindings file changes", async () => {
const baseDir = makeTempDir("t3code-state-keybindings-watch-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-keybindings-watch-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(keybindingsPath, "[]", "utf8");
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -1040,9 +1008,8 @@ describe("WebSocket Server", () => {
});
it("reads keybindings from the configured state directory", async () => {
const baseDir = makeTempDir("t3code-state-keybindings-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-keybindings-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([
@@ -1052,7 +1019,7 @@ describe("WebSocket Server", () => {
]),
"utf8",
);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -1076,16 +1043,15 @@ describe("WebSocket Server", () => {
});
it("upserts keybinding rules and updates cached server config", async () => {
const baseDir = makeTempDir("t3code-state-upsert-keybinding-");
const { keybindingsConfigPath: keybindingsPath } = deriveServerPathsSync(baseDir, undefined);
ensureParentDir(keybindingsPath);
const stateDir = makeTempDir("t3code-state-upsert-keybinding-");
const keybindingsPath = path.join(stateDir, "keybindings.json");
fs.writeFileSync(
keybindingsPath,
JSON.stringify([{ key: "mod+j", command: "terminal.toggle" }]),
"utf8",
);
server = await createTestServer({ cwd: "/my/workspace", baseDir });
server = await createTestServer({ cwd: "/my/workspace", stateDir });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
@@ -1206,10 +1172,7 @@ describe("WebSocket Server", () => {
projectId: "project-diff",
title: "Diff Project",
workspaceRoot,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
});
expect(createProjectResponse.error).toBeUndefined();
@@ -1219,10 +1182,7 @@ describe("WebSocket Server", () => {
threadId: "thread-diff",
projectId: "project-diff",
title: "Diff Thread",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -1290,10 +1250,7 @@ describe("WebSocket Server", () => {
projectId: "project-1",
title: "WS Project",
workspaceRoot,
defaultModelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
defaultModel: "gpt-5-codex",
createdAt,
});
expect(createProjectResponse.error).toBeUndefined();
@@ -1303,10 +1260,7 @@ describe("WebSocket Server", () => {
threadId: "thread-1",
projectId: "project-1",
title: "Thread 1",
modelSelection: {
provider: "codex",
model: "gpt-5-codex",
},
model: "gpt-5-codex",
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
@@ -1837,106 +1791,15 @@ describe("WebSocket Server", () => {
connections.push(ws);
const response = await sendRequest(ws, WS_METHODS.gitRunStackedAction, {
actionId: "client-action-1",
cwd: "/test",
action: "commit_push",
modelSelection: {
provider: "codex",
model: "gpt-5.4-mini",
},
});
expect(response.result).toBeUndefined();
expect(response.error?.message).toContain("detached HEAD");
expect(runStackedAction).toHaveBeenCalledWith(
{
actionId: "client-action-1",
cwd: "/test",
action: "commit_push",
modelSelection: {
provider: "codex",
model: "gpt-5.4-mini",
},
},
expect.objectContaining({
actionId: "client-action-1",
progressReporter: expect.any(Object),
}),
);
});
it("publishes git action progress only to the initiating websocket", async () => {
const runStackedAction = vi.fn(
(_input, options) =>
options?.progressReporter
?.publish({
actionId: options.actionId ?? "action-1",
cwd: "/test",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
})
.pipe(
Effect.flatMap(() =>
Effect.succeed({
action: "commit" as const,
branch: { status: "skipped_not_requested" as const },
commit: {
status: "created" as const,
commitSha: "abc1234",
subject: "Test commit",
},
push: { status: "skipped_not_requested" as const },
pr: { status: "skipped_not_requested" as const },
}),
),
) ?? Effect.void,
);
const gitManager: GitManagerShape = {
status: vi.fn(() => Effect.void as any),
resolvePullRequest: vi.fn(() => Effect.void as any),
preparePullRequestThread: vi.fn(() => Effect.void as any),
runStackedAction,
};
server = await createTestServer({ cwd: "/test", gitManager });
const addr = server.address();
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
const [initiatingWs] = await connectAndAwaitWelcome(port);
const [otherWs] = await connectAndAwaitWelcome(port);
connections.push(initiatingWs, otherWs);
const responsePromise = sendRequest(initiatingWs, WS_METHODS.gitRunStackedAction, {
actionId: "client-action-2",
expect(runStackedAction).toHaveBeenCalledWith({
cwd: "/test",
action: "commit",
modelSelection: {
provider: "codex",
model: "gpt-5.4-mini",
},
action: "commit_push",
});
const progressPush = await waitForPush(initiatingWs, WS_CHANNELS.gitActionProgress);
expect(progressPush.data).toEqual({
actionId: "client-action-2",
cwd: "/test",
action: "commit",
kind: "phase_started",
phase: "commit",
label: "Committing...",
});
await expect(
waitForPush(otherWs, WS_CHANNELS.gitActionProgress, undefined, 10, 100),
).rejects.toThrow("Timed out waiting for WebSocket message after 100ms");
await expect(responsePromise).resolves.toEqual(
expect.objectContaining({
result: expect.objectContaining({
action: "commit",
}),
}),
);
});
it("rejects websocket connections without a valid auth token", async () => {
+12 -52
View File
@@ -49,7 +49,6 @@ import { createLogger } from "./logger";
import { GitManager } from "./git/Services/GitManager.ts";
import { TerminalManager } from "./terminal/Services/Manager.ts";
import { Keybindings } from "./keybindings";
import { ServerSettingsService } from "./serverSettings";
import { searchWorkspaceEntries } from "./workspaceEntries";
import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
@@ -217,7 +216,6 @@ export type ServerRuntimeServices =
| GitCore
| TerminalManager
| Keybindings
| ServerSettingsService
| Open
| AnalyticsService;
@@ -255,7 +253,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const gitManager = yield* GitManager;
const terminalManager = yield* TerminalManager;
const keybindingsManager = yield* Keybindings;
const serverSettingsManager = yield* ServerSettingsService;
const providerHealth = yield* ProviderHealth;
const git = yield* GitCore;
const fileSystem = yield* FileSystem.FileSystem;
@@ -298,11 +295,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
),
);
yield* readiness.markKeybindingsReady;
yield* serverSettingsManager.start.pipe(
Effect.mapError(
(cause) => new ServerLifecycleError({ operation: "serverSettingsRuntimeStart", cause }),
),
);
const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
readonly command: ClientOrchestrationCommand;
@@ -378,7 +370,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
};
const attachmentPath = resolveAttachmentPath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachment: persistedAttachment,
});
if (!attachmentPath) {
@@ -448,11 +440,11 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
!normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
const filePath = isIdLookup
? resolveAttachmentPathById({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
attachmentId: normalizedRelativePath,
})
: resolveAttachmentRelativePath({
attachmentsDir: serverConfig.attachmentsDir,
stateDir: serverConfig.stateDir,
relativePath: normalizedRelativePath,
});
if (!filePath) {
@@ -626,14 +618,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Stream.runForEach(serverSettingsManager.streamChanges, (settings) =>
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: [],
providers: providerStatuses,
settings,
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
yield* readiness.markOrchestrationSubscriptionsReady;
@@ -647,31 +631,25 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
);
let bootstrapProjectId: ProjectId;
let bootstrapProjectDefaultModelSelection;
let bootstrapProjectDefaultModel: string;
if (!existingProject) {
const createdAt = new Date().toISOString();
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
const bootstrapProjectTitle = path.basename(cwd) || "project";
bootstrapProjectDefaultModelSelection = {
provider: "codex" as const,
model: "gpt-5-codex",
};
bootstrapProjectDefaultModel = "gpt-5-codex";
yield* orchestrationEngine.dispatch({
type: "project.create",
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
projectId: bootstrapProjectId,
title: bootstrapProjectTitle,
workspaceRoot: cwd,
defaultModelSelection: bootstrapProjectDefaultModelSelection,
defaultModel: bootstrapProjectDefaultModel,
createdAt,
});
} else {
bootstrapProjectId = existingProject.id;
bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
provider: "codex" as const,
model: "gpt-5-codex",
};
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
}
const existingThread = snapshot.threads.find(
@@ -686,7 +664,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
threadId,
projectId: bootstrapProjectId,
title: "New thread",
modelSelection: bootstrapProjectDefaultModelSelection,
model: bootstrapProjectDefaultModel,
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
runtimeMode: "full-access",
branch: null,
@@ -726,7 +704,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
);
const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) {
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
switch (request.body._tag) {
case ORCHESTRATION_WS_METHODS.getSnapshot:
return yield* projectionReadModelQuery.getSnapshot();
@@ -815,13 +793,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.gitRunStackedAction: {
const body = stripRequestTag(request.body);
return yield* gitManager.runStackedAction(body, {
actionId: body.actionId,
progressReporter: {
publish: (event) =>
pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid),
},
});
return yield* gitManager.runStackedAction(body);
}
case WS_METHODS.gitResolvePullRequest: {
@@ -894,9 +866,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
return yield* terminalManager.close(body);
}
case WS_METHODS.serverGetConfig: {
case WS_METHODS.serverGetConfig:
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
const settings = yield* serverSettingsManager.getSettings;
return {
cwd,
keybindingsConfigPath,
@@ -904,9 +875,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
issues: keybindingsConfig.issues,
providers: providerStatuses,
availableEditors,
settings,
};
}
case WS_METHODS.serverUpsertKeybinding: {
const body = stripRequestTag(request.body);
@@ -914,15 +883,6 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
return { keybindings: keybindingsConfig, issues: [] };
}
case WS_METHODS.serverGetSettings: {
return yield* serverSettingsManager.getSettings;
}
case WS_METHODS.serverUpdateSettings: {
const body = stripRequestTag(request.body);
return yield* serverSettingsManager.updateSettings(body.patch);
}
default: {
const _exhaustiveCheck: never = request.body;
return yield* new RouteRequestError({
@@ -955,7 +915,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
});
}
const result = yield* Effect.exit(routeRequest(ws, request.success));
const result = yield* Effect.exit(routeRequest(request.success));
if (Exit.isFailure(result)) {
return yield* sendWsResponse({
id: request.success.id,
+2 -3
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/web",
"version": "0.0.14",
"version": "0.0.10",
"private": true,
"type": "module",
"scripts": {
@@ -19,7 +19,6 @@
"@dnd-kit/modifiers": "^9.0.0",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@formkit/auto-animate": "^0.9.0",
"@lexical/react": "^0.41.0",
"@pierre/diffs": "^1.1.0-beta.16",
"@t3tools/contracts": "workspace:*",
@@ -52,7 +51,7 @@
"@vitejs/plugin-react": "^6.0.0",
"@vitest/browser-playwright": "^4.0.18",
"babel-plugin-react-compiler": "^19.0.0-beta-e552027-20250112",
"msw": "2.12.11",
"msw": "^2.12.10",
"playwright": "^1.58.2",
"tailwindcss": "^4.0.0",
"typescript": "catalog:",
+1 -1
View File
@@ -7,7 +7,7 @@
* - Please do NOT modify this file.
*/
const PACKAGE_VERSION = '2.12.11'
const PACKAGE_VERSION = '2.12.10'
const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
+25 -176
View File
@@ -1,22 +1,13 @@
import { Schema } from "effect";
import { describe, expect, it } from "vitest";
import {
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
AppSettingsSchema,
DEFAULT_TIMESTAMP_FORMAT,
} from "./appSettings";
import {
getAppModelOptions,
getCustomModelOptionsByProvider,
getCustomModelsByProvider,
getCustomModelsForProvider,
getDefaultCustomModelsForProvider,
MODEL_PROVIDER_SETTINGS,
normalizeCustomModelSlugs,
patchCustomModels,
resolveAppModelSelectionState,
resolveAppModelSelection,
} from "./modelSelection";
} from "./appSettings";
describe("normalizeCustomModelSlugs", () => {
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
@@ -75,35 +66,13 @@ describe("getAppModelOptions", () => {
describe("resolveAppModelSelection", () => {
it("preserves saved custom model slugs instead of falling back to the default", () => {
expect(
resolveAppModelSelection(
"codex",
{ codex: ["galapagos-alpha"], claudeAgent: [] },
"galapagos-alpha",
),
).toBe("galapagos-alpha");
expect(resolveAppModelSelection("codex", ["galapagos-alpha"], "galapagos-alpha")).toBe(
"galapagos-alpha",
);
});
it("falls back to the provider default when no model is selected", () => {
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "")).toBe("gpt-5.4");
});
it("resolves display names through the shared resolver", () => {
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "GPT-5.3 Codex")).toBe(
"gpt-5.3-codex",
);
});
it("resolves aliases through the shared resolver", () => {
expect(resolveAppModelSelection("claudeAgent", { codex: [], claudeAgent: [] }, "sonnet")).toBe(
"claude-sonnet-4-6",
);
});
it("resolves transient selected custom models included in app model options", () => {
expect(
resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "custom/selected-model"),
).toBe("custom/selected-model");
expect(resolveAppModelSelection("codex", [], "")).toBe("gpt-5.4");
});
});
@@ -113,16 +82,6 @@ describe("timestamp format defaults", () => {
});
});
describe("sidebar sort defaults", () => {
it("defaults project sorting to updated_at", () => {
expect(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER).toBe("updated_at");
});
it("defaults thread sorting to updated_at", () => {
expect(DEFAULT_SIDEBAR_THREAD_SORT_ORDER).toBe("updated_at");
});
});
describe("provider-specific custom models", () => {
it("includes provider-specific custom slugs in non-codex model lists", () => {
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
@@ -131,136 +90,26 @@ describe("provider-specific custom models", () => {
});
});
describe("provider-indexed custom model settings", () => {
const settings = {
customCodexModels: ["custom/codex-model"],
customClaudeModels: ["claude/custom-opus"],
} as const;
it("exports one provider config per provider", () => {
expect(MODEL_PROVIDER_SETTINGS.map((config) => config.provider)).toEqual([
"codex",
"claudeAgent",
]);
});
it("reads custom models for each provider", () => {
expect(getCustomModelsForProvider(settings, "codex")).toEqual(["custom/codex-model"]);
expect(getCustomModelsForProvider(settings, "claudeAgent")).toEqual(["claude/custom-opus"]);
});
it("reads default custom models for each provider", () => {
const defaults = {
customCodexModels: ["default/codex-model"],
customClaudeModels: ["claude/default-opus"],
} as const;
expect(getDefaultCustomModelsForProvider(defaults, "codex")).toEqual(["default/codex-model"]);
expect(getDefaultCustomModelsForProvider(defaults, "claudeAgent")).toEqual([
"claude/default-opus",
]);
});
it("patches custom models for codex", () => {
expect(patchCustomModels("codex", ["custom/codex-model"])).toEqual({
customCodexModels: ["custom/codex-model"],
});
});
it("patches custom models for claude", () => {
expect(patchCustomModels("claudeAgent", ["claude/custom-opus"])).toEqual({
customClaudeModels: ["claude/custom-opus"],
});
});
it("builds a complete provider-indexed custom model record", () => {
expect(getCustomModelsByProvider(settings)).toEqual({
codex: ["custom/codex-model"],
claudeAgent: ["claude/custom-opus"],
});
});
it("builds provider-indexed model options including custom models", () => {
const modelOptionsByProvider = getCustomModelOptionsByProvider(settings);
describe("AppSettingsSchema", () => {
it("fills decoding defaults for persisted settings that predate newer keys", () => {
const decode = Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema));
expect(
modelOptionsByProvider.codex.some((option) => option.slug === "custom/codex-model"),
).toBe(true);
expect(
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude/custom-opus"),
).toBe(true);
});
it("normalizes and deduplicates custom model options per provider", () => {
const modelOptionsByProvider = getCustomModelOptionsByProvider({
customCodexModels: [" custom/codex-model ", "gpt-5.4", "custom/codex-model"],
customClaudeModels: [" sonnet ", "claude/custom-opus", "claude/custom-opus"],
});
expect(
modelOptionsByProvider.codex.filter((option) => option.slug === "custom/codex-model"),
).toHaveLength(1);
expect(modelOptionsByProvider.codex.some((option) => option.slug === "gpt-5.4")).toBe(true);
expect(
modelOptionsByProvider.claudeAgent.filter((option) => option.slug === "claude/custom-opus"),
).toHaveLength(1);
expect(
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude-sonnet-4-6"),
).toBe(true);
});
});
describe("resolveAppModelSelectionState", () => {
it("falls back to the default git-writing codex selection", () => {
expect(
resolveAppModelSelectionState({
customCodexModels: [],
customClaudeModels: [],
textGenerationModelSelection: undefined,
}),
).toEqual({
provider: "codex",
model: "gpt-5.4-mini",
});
});
it("preserves the selected provider and resolves saved custom models", () => {
expect(
resolveAppModelSelectionState({
customCodexModels: [],
customClaudeModels: ["claude/custom-haiku"],
textGenerationModelSelection: {
provider: "claudeAgent",
model: "claude/custom-haiku",
},
}),
).toEqual({
provider: "claudeAgent",
model: "claude/custom-haiku",
});
});
it("normalizes provider options against the resolved model capabilities", () => {
expect(
resolveAppModelSelectionState({
customCodexModels: [],
customClaudeModels: [],
textGenerationModelSelection: {
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
effort: "max",
thinking: false,
fastMode: true,
},
},
}),
).toEqual({
provider: "claudeAgent",
model: "claude-haiku-4-5",
options: {
thinking: false,
},
decode(
JSON.stringify({
codexBinaryPath: "/usr/local/bin/codex",
confirmThreadDelete: false,
}),
),
).toMatchObject({
codexBinaryPath: "/usr/local/bin/codex",
codexHomePath: "",
defaultThreadEnvMode: "local",
confirmThreadDelete: false,
enableAssistantStreaming: false,
timestampFormat: DEFAULT_TIMESTAMP_FORMAT,
customCodexModels: [],
customClaudeModels: [],
});
});
});
+169 -36
View File
@@ -1,50 +1,183 @@
/**
* App Settings - Backward-compatible shim.
*
* Re-exports the unified settings hook (`useSettings` / `useUpdateSettings`)
* as `useAppSettings()` so existing consumers continue to work without
* modification. New code should import from `~/hooks/useSettings` directly.
*
* Also re-exports type aliases and schema constants consumed by components
* that only need the type (e.g. `TimestampFormat`).
*/
import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
import { useSettings, useUpdateSettings, type UnifiedSettings } from "./hooks/useSettings";
import {
DEFAULT_CLIENT_SETTINGS,
type ClientSettings,
type TimestampFormat,
type SidebarProjectSortOrder,
type SidebarThreadSortOrder,
DEFAULT_TIMESTAMP_FORMAT,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
} from "./clientSettings";
import { useCallback } from "react";
import { Option, Schema } from "effect";
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
import { getDefaultModel, getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
import { useLocalStorage } from "./hooks/useLocalStorage";
import { EnvMode } from "./components/BranchToolbar.logic";
// ── Re-exports for downstream type consumers ─────────────────────────
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
export type { TimestampFormat, SidebarProjectSortOrder, SidebarThreadSortOrder };
export {
DEFAULT_TIMESTAMP_FORMAT,
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
export type TimestampFormat = typeof TimestampFormat.Type;
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
};
export type { UnifiedSettings };
// ── Backward-compat type alias ───────────────────────────────────────
const withDefaults =
<
S extends Schema.Top & Schema.WithoutConstructorDefault,
D extends S["~type.make.in"] & S["Encoded"],
>(
fallback: () => D,
) =>
(schema: S) =>
schema.pipe(
Schema.withConstructorDefault(() => Option.some(fallback())),
Schema.withDecodingDefault(() => fallback()),
);
export type AppSettings = UnifiedSettings;
export const AppSettingsSchema = Schema.Struct({
codexBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
codexHomePath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
defaultThreadEnvMode: EnvMode.pipe(withDefaults(() => "local" as const satisfies EnvMode)),
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
enableAssistantStreaming: Schema.Boolean.pipe(withDefaults(() => false)),
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
customCodexModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
customClaudeModels: Schema.Array(Schema.String).pipe(withDefaults(() => [])),
textGenerationModel: Schema.optional(TrimmedNonEmptyString),
});
export type AppSettings = typeof AppSettingsSchema.Type;
export interface AppModelOption {
slug: string;
name: string;
isCustom: boolean;
}
// ── Backward-compat hook ─────────────────────────────────────────────
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
export function normalizeCustomModelSlugs(
models: Iterable<string | null | undefined>,
provider: ProviderKind = "codex",
): string[] {
const normalizedModels: string[] = [];
const seen = new Set<string>();
const builtInModelSlugs = BUILT_IN_MODEL_SLUGS_BY_PROVIDER[provider];
for (const candidate of models) {
const normalized = normalizeModelSlug(candidate, provider);
if (
!normalized ||
normalized.length > MAX_CUSTOM_MODEL_LENGTH ||
builtInModelSlugs.has(normalized) ||
seen.has(normalized)
) {
continue;
}
seen.add(normalized);
normalizedModels.push(normalized);
if (normalizedModels.length >= MAX_CUSTOM_MODEL_COUNT) {
break;
}
}
return normalizedModels;
}
function normalizeAppSettings(settings: AppSettings): AppSettings {
return {
...settings,
customCodexModels: normalizeCustomModelSlugs(settings.customCodexModels, "codex"),
customClaudeModels: normalizeCustomModelSlugs(settings.customClaudeModels, "claudeAgent"),
};
}
export function getAppModelOptions(
provider: ProviderKind,
customModels: readonly string[],
selectedModel?: string | null,
): AppModelOption[] {
const options: AppModelOption[] = getModelOptions(provider).map(({ slug, name }) => ({
slug,
name,
isCustom: false,
}));
const seen = new Set(options.map((option) => option.slug));
for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
if (seen.has(slug)) {
continue;
}
seen.add(slug);
options.push({
slug,
name: slug,
isCustom: true,
});
}
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
if (normalizedSelectedModel && !seen.has(normalizedSelectedModel)) {
options.push({
slug: normalizedSelectedModel,
name: normalizedSelectedModel,
isCustom: true,
});
}
return options;
}
export function resolveAppModelSelection(
provider: ProviderKind,
customModels: readonly string[],
selectedModel: string | null | undefined,
): string {
const options = getAppModelOptions(provider, customModels, selectedModel);
const trimmedSelectedModel = selectedModel?.trim();
if (trimmedSelectedModel) {
const direct = options.find((option) => option.slug === trimmedSelectedModel);
if (direct) {
return direct.slug;
}
const byName = options.find(
(option) => option.name.toLowerCase() === trimmedSelectedModel.toLowerCase(),
);
if (byName) {
return byName.slug;
}
}
const normalizedSelectedModel = normalizeModelSlug(selectedModel, provider);
if (!normalizedSelectedModel) {
return getDefaultModel(provider);
}
return (
options.find((option) => option.slug === normalizedSelectedModel)?.slug ??
getDefaultModel(provider)
);
}
export function useAppSettings() {
const settings = useSettings();
const { updateSettings, resetSettings, defaults } = useUpdateSettings();
const [settings, setSettings] = useLocalStorage(
APP_SETTINGS_STORAGE_KEY,
DEFAULT_APP_SETTINGS,
AppSettingsSchema,
);
const updateSettings = useCallback(
(patch: Partial<AppSettings>) => {
setSettings((prev) => normalizeAppSettings({ ...prev, ...patch }));
},
[setSettings],
);
const resetSettings = useCallback(() => {
setSettings(DEFAULT_APP_SETTINGS);
}, [setSettings]);
return {
settings,
updateSettings: (patch: Partial<AppSettings>) => updateSettings(patch),
updateSettings,
resetSettings,
defaults,
defaults: DEFAULT_APP_SETTINGS,
} as const;
}
Loaded 100 of 176 files, more files were not shown because too many files have changed in this diff. Show more