Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8c9d71187 | ||
|
|
3f089a454b | ||
|
|
b225dfaf77 | ||
|
|
ff8d87ddee | ||
|
|
3289a25e57 | ||
|
|
df5bde7e11 | ||
|
|
b3bca04caf | ||
|
|
bf71e0bc5e | ||
|
|
a542a3b168 | ||
|
|
56d13faa1a | ||
|
|
2a435aef66 | ||
|
|
28afb14004 | ||
|
|
8f3515572d | ||
|
|
529315b4c8 | ||
|
|
0a503d0cde | ||
|
|
d4a7e1ac0b | ||
|
|
be1abc88fd | ||
|
|
384f35084e | ||
|
|
1371ce2cce | ||
|
|
d6408a2949 | ||
|
|
e823f8f14e | ||
|
|
2b08d86696 |
No files matched your search
@@ -24,32 +24,32 @@ jobs:
|
||||
{
|
||||
name: "size:XS",
|
||||
color: "0e8a16",
|
||||
description: "0-9 changed lines (additions + deletions).",
|
||||
description: "0-9 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:S",
|
||||
color: "5ebd3e",
|
||||
description: "10-29 changed lines (additions + deletions).",
|
||||
description: "10-29 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:M",
|
||||
color: "fbca04",
|
||||
description: "30-99 changed lines (additions + deletions).",
|
||||
description: "30-99 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:L",
|
||||
color: "fe7d37",
|
||||
description: "100-499 changed lines (additions + deletions).",
|
||||
description: "100-499 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XL",
|
||||
color: "d93f0b",
|
||||
description: "500-999 changed lines (additions + deletions).",
|
||||
description: "500-999 effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
{
|
||||
name: "size:XXL",
|
||||
color: "b60205",
|
||||
description: "1,000+ changed lines (additions + deletions).",
|
||||
description: "1,000+ effective changed lines (test files excluded in mixed PRs).",
|
||||
},
|
||||
];
|
||||
|
||||
@@ -131,12 +131,18 @@ 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 resolveSizeLabel = (totalChangedLines) => {
|
||||
if (totalChangedLines < 10) {
|
||||
@@ -162,6 +168,42 @@ 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({
|
||||
@@ -199,4 +241,15 @@ jobs:
|
||||
});
|
||||
}
|
||||
|
||||
core.info(`PR #${issueNumber}: ${changedLines} changed lines -> ${nextLabelName}`);
|
||||
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})`,
|
||||
);
|
||||
+2
-1
@@ -18,4 +18,5 @@ apps/web/.playwright
|
||||
apps/web/playwright-report
|
||||
apps/web/src/components/__screenshots__
|
||||
.vitest-*
|
||||
__screenshots__/
|
||||
__screenshots__/
|
||||
.tanstack
|
||||
@@ -6,21 +6,24 @@ 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. |
|
||||
| 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. |
|
||||
|
||||
> 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,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.13",
|
||||
"version": "0.0.14",
|
||||
"private": true,
|
||||
"main": "dist-electron/main.js",
|
||||
"scripts": {
|
||||
|
||||
+42
-17
@@ -56,6 +56,7 @@ 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 DESKTOP_SCHEME = "t3";
|
||||
@@ -113,6 +114,17 @@ 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`);
|
||||
@@ -918,17 +930,6 @@ 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_HOME: BASE_DIR,
|
||||
T3CODE_AUTH_TOKEN: backendAuthToken,
|
||||
};
|
||||
}
|
||||
|
||||
function scheduleBackendRestart(reason: string): void {
|
||||
if (isQuitting || restartTimer) return;
|
||||
|
||||
@@ -952,16 +953,35 @@ function startBackend(): void {
|
||||
}
|
||||
|
||||
const captureBackendLogs = app.isPackaged && backendLogSink !== null;
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry], {
|
||||
const child = ChildProcess.spawn(process.execPath, [backendEntry, "--bootstrap-fd", "3"], {
|
||||
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: {
|
||||
...backendEnv(),
|
||||
...backendChildEnv(),
|
||||
ELECTRON_RUN_AS_NODE: "1",
|
||||
},
|
||||
stdio: captureBackendLogs ? ["ignore", "pipe", "pipe"] : "inherit",
|
||||
stdio: captureBackendLogs
|
||||
? ["ignore", "pipe", "pipe", "pipe"]
|
||||
: ["ignore", "inherit", "inherit", "pipe"],
|
||||
});
|
||||
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) => {
|
||||
@@ -1072,6 +1092,11 @@ 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;
|
||||
@@ -1320,9 +1345,9 @@ async function bootstrap(): Promise<void> {
|
||||
);
|
||||
writeDesktopLogHeader(`reserved backend port via NetService port=${backendPort}`);
|
||||
backendAuthToken = Crypto.randomBytes(24).toString("hex");
|
||||
backendWsUrl = `ws://127.0.0.1:${backendPort}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
process.env.T3CODE_DESKTOP_WS_URL = backendWsUrl;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket url=${backendWsUrl}`);
|
||||
const baseUrl = `ws://127.0.0.1:${backendPort}`;
|
||||
backendWsUrl = `${baseUrl}/?token=${encodeURIComponent(backendAuthToken)}`;
|
||||
writeDesktopLogHeader(`bootstrap resolved websocket endpoint baseUrl=${baseUrl}`);
|
||||
|
||||
registerIpcHandlers();
|
||||
writeDesktopLogHeader("bootstrap ipc handlers registered");
|
||||
|
||||
@@ -11,10 +11,13 @@ 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 wsUrl = process.env.T3CODE_DESKTOP_WS_URL ?? null;
|
||||
const GET_WS_URL_CHANNEL = "desktop:get-ws-url";
|
||||
|
||||
contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
getWsUrl: () => wsUrl,
|
||||
getWsUrl: () => {
|
||||
const result = ipcRenderer.sendSync(GET_WS_URL_CHANNEL);
|
||||
return typeof result === "string" ? result : null;
|
||||
},
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
|
||||
@@ -67,6 +67,7 @@ import {
|
||||
type TestProviderAdapterHarness,
|
||||
} from "./TestProviderAdapter.integration.ts";
|
||||
import { deriveServerPaths, ServerConfig } from "../src/config.ts";
|
||||
import { ServerSettingsService } from "../src/serverSettings.ts";
|
||||
|
||||
function runGit(cwd: string, args: ReadonlyArray<string>) {
|
||||
return execFileSync("git", args, {
|
||||
@@ -295,8 +296,10 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
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]) =>
|
||||
@@ -309,6 +312,7 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
Layer.provideMerge(gitCoreLayer),
|
||||
Layer.provideMerge(textGenerationLayer),
|
||||
Layer.provideMerge(serverSettingsLayer),
|
||||
);
|
||||
const checkpointReactorLayer = CheckpointReactorLive.pipe(
|
||||
Layer.provideMerge(runtimeServicesLayer),
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
ProjectId,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import { Effect, Option, Schema } from "effect";
|
||||
@@ -115,7 +116,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel,
|
||||
defaultModelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -125,7 +129,10 @@ const seedProjectAndThread = (harness: OrchestrationIntegrationHarness) =>
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: defaultModel,
|
||||
modelSelection: {
|
||||
provider,
|
||||
model: defaultModel,
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -139,7 +146,7 @@ const startTurn = (input: {
|
||||
readonly commandId: string;
|
||||
readonly messageId: string;
|
||||
readonly text: string;
|
||||
readonly provider?: IntegrationProvider;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
}) =>
|
||||
input.harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
@@ -151,7 +158,11 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
...(input.provider !== undefined ? { provider: input.provider } : {}),
|
||||
...(input.modelSelection !== undefined
|
||||
? {
|
||||
modelSelection: input.modelSelection,
|
||||
}
|
||||
: {}),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: nowIso(),
|
||||
@@ -254,7 +265,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModel: "gpt-5.3-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -264,7 +278,10 @@ it.live.skipIf(!process.env.CODEX_BINARY_PATH)(
|
||||
threadId: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Integration Thread",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -922,7 +939,10 @@ 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",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
@@ -976,7 +996,10 @@ 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",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
@@ -1083,7 +1106,10 @@ it.live("forwards claudeAgent approval responses to the provider session", () =>
|
||||
commandId: "cmd-turn-start-claude-approval",
|
||||
messageId: "msg-user-claude-approval",
|
||||
text: "Need approval",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(THREAD_ID, (entry) =>
|
||||
@@ -1152,7 +1178,10 @@ 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",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
const thread = yield* harness.waitForThread(
|
||||
@@ -1222,7 +1251,10 @@ 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",
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
|
||||
yield* harness.waitForThread(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.13",
|
||||
"version": "0.0.14",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
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())),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
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,
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
@@ -43,7 +43,10 @@ function makeSnapshot(input: {
|
||||
id: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -19,6 +19,7 @@ export interface ServerDerivedPaths {
|
||||
readonly stateDir: string;
|
||||
readonly dbPath: string;
|
||||
readonly keybindingsConfigPath: string;
|
||||
readonly settingsPath: string;
|
||||
readonly worktreesDir: string;
|
||||
readonly attachmentsDir: string;
|
||||
readonly logsDir: string;
|
||||
@@ -60,6 +61,7 @@ export const deriveServerPaths = Effect.fn(function* (
|
||||
stateDir,
|
||||
dbPath,
|
||||
keybindingsConfigPath: join(stateDir, "keybindings.json"),
|
||||
settingsPath: join(stateDir, "settings.json"),
|
||||
worktreesDir: join(baseDir, "worktrees"),
|
||||
attachmentsDir,
|
||||
logsDir,
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
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");
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* 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,14 +1,21 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import { Effect, FileSystem, Layer, Path, Result } 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-",
|
||||
@@ -38,6 +45,18 @@ 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"',
|
||||
@@ -49,6 +68,18 @@ 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',
|
||||
@@ -82,6 +113,9 @@ function withFakeCodexEnv<A, E, R>(
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: string;
|
||||
},
|
||||
@@ -97,6 +131,9 @@ 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;
|
||||
|
||||
@@ -122,6 +159,24 @@ 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 {
|
||||
@@ -141,6 +196,9 @@ function withFakeCodexEnv<A, E, R>(
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousRequireImage,
|
||||
previousRequireFastServiceTier,
|
||||
previousRequireReasoningEffort,
|
||||
previousForbidReasoningEffort,
|
||||
previousStdinMustContain,
|
||||
previousStdinMustNotContain,
|
||||
};
|
||||
@@ -174,6 +232,27 @@ 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 {
|
||||
@@ -208,6 +287,7 @@ 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);
|
||||
@@ -218,6 +298,63 @@ 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(
|
||||
{
|
||||
@@ -237,6 +374,7 @@ 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");
|
||||
@@ -263,6 +401,7 @@ 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");
|
||||
@@ -286,6 +425,7 @@ 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");
|
||||
@@ -307,6 +447,7 @@ 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");
|
||||
@@ -333,21 +474,20 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
yield* fs.writeFile(attachmentPath, Buffer.from("hello"));
|
||||
|
||||
const textGeneration = yield* TextGeneration;
|
||||
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))));
|
||||
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,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(generated.branch).toBe("fix/ui-regression");
|
||||
}),
|
||||
@@ -374,6 +514,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const generated = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
@@ -421,6 +562,7 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const result = yield* textGeneration
|
||||
.generateBranchName({
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
cwd: process.cwd(),
|
||||
message: "Fix layout bug from screenshot.",
|
||||
attachments: [
|
||||
@@ -433,17 +575,12 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
},
|
||||
],
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("missing --image input");
|
||||
expect(Result.isFailure(result)).toBe(true);
|
||||
if (Result.isFailure(result)) {
|
||||
expect(result.failure).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.failure.message).toContain("missing --image input");
|
||||
}
|
||||
}),
|
||||
),
|
||||
@@ -465,18 +602,14 @@ it.layer(CodexTextGenerationTestLayer)("CodexTextGenerationLive", (it) => {
|
||||
.generateBranchName({
|
||||
cwd: process.cwd(),
|
||||
message: "Fix websocket reconnect flake",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
})
|
||||
.pipe(
|
||||
Effect.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
.pipe(Effect.result);
|
||||
|
||||
expect(result._tag).toBe("Left");
|
||||
if (result._tag === "Left") {
|
||||
expect(result.left).toBeInstanceOf(TextGenerationError);
|
||||
expect(result.left.message).toContain("Codex returned invalid structured output");
|
||||
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");
|
||||
}
|
||||
}),
|
||||
),
|
||||
@@ -498,18 +631,16 @@ 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.match({
|
||||
onFailure: (error) => ({ _tag: "Left" as const, left: error }),
|
||||
onSuccess: (value) => ({ _tag: "Right" as const, right: value }),
|
||||
}),
|
||||
);
|
||||
.pipe(Effect.result);
|
||||
|
||||
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");
|
||||
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",
|
||||
);
|
||||
}
|
||||
}),
|
||||
),
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Stream } from "effect";
|
||||
import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { CodexModelSelection } from "@t3tools/contracts";
|
||||
import { normalizeCodexModelOptions } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
@@ -11,95 +12,31 @@ 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_REASONING_EFFORT = "low";
|
||||
const CODEX_GIT_TEXT_GENERATION_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>;
|
||||
@@ -109,39 +46,37 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
operation: string,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
): Effect.Effect<string, TextGenerationError> =>
|
||||
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";
|
||||
stream.pipe(
|
||||
Stream.decodeText(),
|
||||
Stream.runFold(
|
||||
() => "",
|
||||
(acc, chunk) => acc + chunk,
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCliError("codex", operation, cause, "Failed to collect process output"),
|
||||
),
|
||||
);
|
||||
|
||||
const writeTempFile = (
|
||||
operation: string,
|
||||
prefix: string,
|
||||
content: string,
|
||||
): 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),
|
||||
);
|
||||
): 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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const safeUnlink = (filePath: string): Effect.Effect<void, never> =>
|
||||
@@ -187,7 +122,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson,
|
||||
imagePaths = [],
|
||||
cleanupPaths = [],
|
||||
model,
|
||||
modelSelection,
|
||||
}: {
|
||||
operation: "generateCommitMessage" | "generatePrContent" | "generateBranchName";
|
||||
cwd: string;
|
||||
@@ -195,28 +130,40 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
outputSchemaJson: S;
|
||||
imagePaths?: ReadonlyArray<string>;
|
||||
cleanupPaths?: ReadonlyArray<string>;
|
||||
model?: string;
|
||||
modelSelection: CodexModelSelection;
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const schemaPath = yield* writeTempFile(
|
||||
operation,
|
||||
"codex-schema",
|
||||
JSON.stringify(toCodexOutputJsonSchema(outputSchemaJson)),
|
||||
JSON.stringify(toJsonSchemaObject(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(
|
||||
"codex",
|
||||
codexSettings?.binaryPath || "codex",
|
||||
[
|
||||
"exec",
|
||||
"--ephemeral",
|
||||
"-s",
|
||||
"read-only",
|
||||
"--model",
|
||||
model ?? DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
modelSelection.model,
|
||||
"--config",
|
||||
`model_reasoning_effort="${CODEX_REASONING_EFFORT}"`,
|
||||
`model_reasoning_effort="${reasoningEffort}"`,
|
||||
...(normalizedOptions?.fastMode ? ["--config", `service_tier="fast"`] : []),
|
||||
"--output-schema",
|
||||
schemaPath,
|
||||
"--output-last-message",
|
||||
@@ -225,10 +172,11 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
"-",
|
||||
],
|
||||
{
|
||||
env: codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
stream: Stream.make(new TextEncoder().encode(prompt)),
|
||||
stream: Stream.encodeText(Stream.make(prompt)),
|
||||
},
|
||||
},
|
||||
);
|
||||
@@ -237,7 +185,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
.spawn(command)
|
||||
.pipe(
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to spawn Codex CLI process"),
|
||||
normalizeCliError("codex", operation, cause, "Failed to spawn Codex CLI process"),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -246,9 +194,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
readStreamAsString(operation, child.stdout),
|
||||
readStreamAsString(operation, child.stderr),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError((cause) =>
|
||||
normalizeCodexError(operation, cause, "Failed to read Codex CLI exit code"),
|
||||
normalizeCliError("codex", operation, cause, "Failed to read Codex CLI exit code"),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -314,153 +261,104 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
}).pipe(Effect.ensuring(cleanup));
|
||||
});
|
||||
|
||||
const generateCommitMessage: TextGenerationShape["generateCommitMessage"] = (input) => {
|
||||
const wantsBranch = input.includeBranch === true;
|
||||
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 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 (input.modelSelection.provider !== "codex") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateCommitMessage",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const outputSchemaJson = wantsBranch
|
||||
? Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
branch: Schema.String,
|
||||
})
|
||||
: Schema.Struct({
|
||||
subject: Schema.String,
|
||||
body: Schema.String,
|
||||
});
|
||||
|
||||
return runCodexJson({
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateCommitMessage",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
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,
|
||||
),
|
||||
);
|
||||
};
|
||||
outputSchemaJson: outputSchema,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
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");
|
||||
return {
|
||||
subject: sanitizeCommitSubject(generated.subject),
|
||||
body: generated.body.trim(),
|
||||
...("branch" in generated && typeof generated.branch === "string"
|
||||
? { branch: sanitizeFeatureBranchName(generated.branch) }
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
|
||||
return runCodexJson({
|
||||
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({
|
||||
operation: "generatePrContent",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
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 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",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: Schema.Struct({
|
||||
branch: Schema.String,
|
||||
}),
|
||||
imagePaths,
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
} satisfies BranchNameGenerationResult;
|
||||
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,
|
||||
);
|
||||
const { prompt, outputSchema } = buildBranchNamePrompt({
|
||||
message: input.message,
|
||||
attachments: input.attachments,
|
||||
});
|
||||
|
||||
if (input.modelSelection.provider !== "codex") {
|
||||
return yield* new TextGenerationError({
|
||||
operation: "generateBranchName",
|
||||
detail: "Invalid model selection.",
|
||||
});
|
||||
}
|
||||
|
||||
const generated = yield* runCodexJson({
|
||||
operation: "generateBranchName",
|
||||
cwd: input.cwd,
|
||||
prompt,
|
||||
outputSchemaJson: outputSchema,
|
||||
imagePaths,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
|
||||
return {
|
||||
branch: sanitizeBranchFragment(generated.branch),
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
generateCommitMessage,
|
||||
|
||||
@@ -8,7 +8,12 @@ import {
|
||||
Layer,
|
||||
Option,
|
||||
Path,
|
||||
PlatformError,
|
||||
Ref,
|
||||
Result,
|
||||
Schema,
|
||||
Scope,
|
||||
Semaphore,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
@@ -16,11 +21,14 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { GitCommandError } from "../Errors.ts";
|
||||
import {
|
||||
GitCore,
|
||||
type ExecuteGitProgress,
|
||||
type GitCommitOptions,
|
||||
type GitCoreShape,
|
||||
type ExecuteGitInput,
|
||||
type ExecuteGitResult,
|
||||
} from "../Services/GitCore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
|
||||
const DEFAULT_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_MAX_OUTPUT_BYTES = 1_000_000;
|
||||
@@ -29,6 +37,11 @@ const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5);
|
||||
const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048;
|
||||
const DEFAULT_BASE_BRANCH_CANDIDATES = ["main", "master"] as const;
|
||||
|
||||
type TraceTailState = {
|
||||
processedChars: number;
|
||||
remainder: string;
|
||||
};
|
||||
|
||||
class StatusUpstreamRefreshCacheKey extends Data.Class<{
|
||||
cwd: string;
|
||||
upstreamRef: string;
|
||||
@@ -40,6 +53,7 @@ interface ExecuteGitOptions {
|
||||
timeoutMs?: number | undefined;
|
||||
allowNonZeroExit?: boolean | undefined;
|
||||
fallbackErrorMessage?: string | undefined;
|
||||
progress?: ExecuteGitProgress | undefined;
|
||||
}
|
||||
|
||||
function parseBranchAb(value: string): { ahead: number; behind: number } {
|
||||
@@ -257,14 +271,201 @@ function toGitCommandError(
|
||||
});
|
||||
}
|
||||
|
||||
interface Trace2Monitor {
|
||||
readonly env: NodeJS.ProcessEnv;
|
||||
readonly flush: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
function trace2ChildKey(record: Record<string, unknown>): string | null {
|
||||
const childId = record.child_id;
|
||||
if (typeof childId === "number" || typeof childId === "string") {
|
||||
return String(childId);
|
||||
}
|
||||
const hookName = record.hook_name;
|
||||
return typeof hookName === "string" && hookName.trim().length > 0 ? hookName.trim() : null;
|
||||
}
|
||||
|
||||
const Trace2Record = Schema.Record(Schema.String, Schema.Unknown);
|
||||
|
||||
const createTrace2Monitor = Effect.fn(function* (
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
progress: ExecuteGitProgress | undefined,
|
||||
): Effect.fn.Return<
|
||||
Trace2Monitor,
|
||||
PlatformError.PlatformError,
|
||||
Scope.Scope | FileSystem.FileSystem | Path.Path
|
||||
> {
|
||||
if (!progress?.onHookStarted && !progress?.onHookFinished) {
|
||||
return {
|
||||
env: {},
|
||||
flush: Effect.void,
|
||||
};
|
||||
}
|
||||
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const traceFilePath = yield* fs.makeTempFileScoped({
|
||||
prefix: `t3code-git-trace2-${process.pid}-`,
|
||||
suffix: ".json",
|
||||
});
|
||||
const hookStartByChildKey = new Map<string, { hookName: string; startedAtMs: number }>();
|
||||
const traceTailState = yield* Ref.make<TraceTailState>({
|
||||
processedChars: 0,
|
||||
remainder: "",
|
||||
});
|
||||
|
||||
const handleTraceLine = (line: string) =>
|
||||
Effect.gen(function* () {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const traceRecord = decodeJsonResult(Trace2Record)(trimmedLine);
|
||||
if (Result.isFailure(traceRecord)) {
|
||||
yield* Effect.logDebug(
|
||||
`GitCore.trace2: failed to parse trace line for ${quoteGitCommand(input.args)} in ${input.cwd}`,
|
||||
traceRecord.failure,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (traceRecord.success.child_class !== "hook") {
|
||||
return;
|
||||
}
|
||||
|
||||
const event = traceRecord.success.event;
|
||||
const childKey = trace2ChildKey(traceRecord.success);
|
||||
if (childKey === null) {
|
||||
return;
|
||||
}
|
||||
const started = hookStartByChildKey.get(childKey);
|
||||
const hookNameFromEvent =
|
||||
typeof traceRecord.success.hook_name === "string"
|
||||
? traceRecord.success.hook_name.trim()
|
||||
: "";
|
||||
const hookName = hookNameFromEvent.length > 0 ? hookNameFromEvent : (started?.hookName ?? "");
|
||||
if (hookName.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event === "child_start") {
|
||||
hookStartByChildKey.set(childKey, { hookName, startedAtMs: Date.now() });
|
||||
if (progress.onHookStarted) {
|
||||
yield* progress.onHookStarted(hookName);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (event === "child_exit") {
|
||||
hookStartByChildKey.delete(childKey);
|
||||
if (progress.onHookFinished) {
|
||||
const code = traceRecord.success.code;
|
||||
yield* progress.onHookFinished({
|
||||
hookName: started?.hookName ?? hookName,
|
||||
exitCode: typeof code === "number" && Number.isInteger(code) ? code : null,
|
||||
durationMs: started ? Math.max(0, Date.now() - started.startedAtMs) : null,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const deltaMutex = yield* Semaphore.make(1);
|
||||
const readTraceDelta = deltaMutex.withPermit(
|
||||
fs.readFileString(traceFilePath).pipe(
|
||||
Effect.flatMap((contents) =>
|
||||
Effect.uninterruptible(
|
||||
Ref.modify(traceTailState, ({ processedChars, remainder }) => {
|
||||
if (contents.length <= processedChars) {
|
||||
return [[], { processedChars, remainder }];
|
||||
}
|
||||
|
||||
const appended = contents.slice(processedChars);
|
||||
const combined = remainder + appended;
|
||||
const lines = combined.split("\n");
|
||||
const nextRemainder = lines.pop() ?? "";
|
||||
|
||||
return [
|
||||
lines.map((line) => line.replace(/\r$/, "")),
|
||||
{
|
||||
processedChars: contents.length,
|
||||
remainder: nextRemainder,
|
||||
},
|
||||
];
|
||||
}).pipe(
|
||||
Effect.flatMap((lines) => Effect.forEach(lines, handleTraceLine, { discard: true })),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.ignore({ log: true }),
|
||||
),
|
||||
);
|
||||
const traceFileName = path.basename(traceFilePath);
|
||||
yield* Stream.runForEach(fs.watch(traceFilePath), (event) => {
|
||||
const eventPath = event.path;
|
||||
const isTargetTraceEvent =
|
||||
eventPath === traceFilePath ||
|
||||
eventPath === traceFileName ||
|
||||
path.basename(eventPath) === traceFileName;
|
||||
if (!isTargetTraceEvent) return Effect.void;
|
||||
return readTraceDelta;
|
||||
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkScoped);
|
||||
|
||||
yield* Effect.addFinalizer(() =>
|
||||
Effect.gen(function* () {
|
||||
yield* readTraceDelta;
|
||||
const finalLine = yield* Ref.modify(traceTailState, ({ processedChars, remainder }) => [
|
||||
remainder.trim(),
|
||||
{
|
||||
processedChars,
|
||||
remainder: "",
|
||||
},
|
||||
]);
|
||||
if (finalLine.length > 0) {
|
||||
yield* handleTraceLine(finalLine);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
env: {
|
||||
GIT_TRACE2_EVENT: traceFilePath,
|
||||
},
|
||||
flush: readTraceDelta,
|
||||
};
|
||||
});
|
||||
|
||||
const collectOutput = Effect.fn(function* <E>(
|
||||
input: Pick<ExecuteGitInput, "operation" | "cwd" | "args">,
|
||||
stream: Stream.Stream<Uint8Array, E>,
|
||||
maxOutputBytes: number,
|
||||
onLine: ((line: string) => Effect.Effect<void, never>) | undefined,
|
||||
): Effect.fn.Return<string, GitCommandError> {
|
||||
const decoder = new TextDecoder();
|
||||
let bytes = 0;
|
||||
let text = "";
|
||||
let lineBuffer = "";
|
||||
|
||||
const emitCompleteLines = (flush: boolean) =>
|
||||
Effect.gen(function* () {
|
||||
let newlineIndex = lineBuffer.indexOf("\n");
|
||||
while (newlineIndex >= 0) {
|
||||
const line = lineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
|
||||
lineBuffer = lineBuffer.slice(newlineIndex + 1);
|
||||
if (line.length > 0 && onLine) {
|
||||
yield* onLine(line);
|
||||
}
|
||||
newlineIndex = lineBuffer.indexOf("\n");
|
||||
}
|
||||
|
||||
if (flush) {
|
||||
const trailing = lineBuffer.replace(/\r$/, "");
|
||||
lineBuffer = "";
|
||||
if (trailing.length > 0 && onLine) {
|
||||
yield* onLine(trailing);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
yield* Stream.runForEach(stream, (chunk) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -277,11 +478,17 @@ const collectOutput = Effect.fn(function* <E>(
|
||||
detail: `${quoteGitCommand(input.args)} output exceeded ${maxOutputBytes} bytes and was truncated.`,
|
||||
});
|
||||
}
|
||||
text += decoder.decode(chunk, { stream: true });
|
||||
const decoded = decoder.decode(chunk, { stream: true });
|
||||
text += decoded;
|
||||
lineBuffer += decoded;
|
||||
yield* emitCompleteLines(false);
|
||||
}),
|
||||
).pipe(Effect.mapError(toGitCommandError(input, "output stream failed.")));
|
||||
|
||||
text += decoder.decode();
|
||||
const remainder = decoder.decode();
|
||||
text += remainder;
|
||||
lineBuffer += remainder;
|
||||
yield* emitCompleteLines(true);
|
||||
return text;
|
||||
});
|
||||
|
||||
@@ -306,19 +513,38 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
const maxOutputBytes = input.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
||||
|
||||
const commandEffect = Effect.gen(function* () {
|
||||
const trace2Monitor = yield* createTrace2Monitor(commandInput, input.progress).pipe(
|
||||
Effect.provideService(Path.Path, path),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to create trace2 monitor.")),
|
||||
);
|
||||
const child = yield* commandSpawner
|
||||
.spawn(
|
||||
ChildProcess.make("git", commandInput.args, {
|
||||
cwd: commandInput.cwd,
|
||||
...(input.env ? { env: input.env } : {}),
|
||||
env: {
|
||||
...process.env,
|
||||
...input.env,
|
||||
...trace2Monitor.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),
|
||||
collectOutput(
|
||||
commandInput,
|
||||
child.stdout,
|
||||
maxOutputBytes,
|
||||
input.progress?.onStdoutLine,
|
||||
),
|
||||
collectOutput(
|
||||
commandInput,
|
||||
child.stderr,
|
||||
maxOutputBytes,
|
||||
input.progress?.onStderrLine,
|
||||
),
|
||||
child.exitCode.pipe(
|
||||
Effect.map((value) => Number(value)),
|
||||
Effect.mapError(toGitCommandError(commandInput, "failed to report exit code.")),
|
||||
@@ -326,6 +552,7 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
],
|
||||
{ concurrency: "unbounded" },
|
||||
);
|
||||
yield* trace2Monitor.flush;
|
||||
|
||||
if (!input.allowNonZeroExit && exitCode !== 0) {
|
||||
const trimmedStderr = stderr.trim();
|
||||
@@ -376,6 +603,7 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
args,
|
||||
allowNonZeroExit: true,
|
||||
...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(options.progress ? { progress: options.progress } : {}),
|
||||
}).pipe(
|
||||
Effect.flatMap((result) => {
|
||||
if (options.allowNonZeroExit || result.code === 0) {
|
||||
@@ -947,14 +1175,37 @@ export const makeGitCore = (options?: { executeOverride?: GitCoreShape["execute"
|
||||
};
|
||||
});
|
||||
|
||||
const commit: GitCoreShape["commit"] = (cwd, subject, body) =>
|
||||
const commit: GitCoreShape["commit"] = (cwd, subject, body, options?: GitCommitOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const args = ["commit", "-m", subject];
|
||||
const trimmedBody = body.trim();
|
||||
if (trimmedBody.length > 0) {
|
||||
args.push("-m", trimmedBody);
|
||||
}
|
||||
yield* runGit("GitCore.commit.commit", cwd, args);
|
||||
const progress = options?.progress
|
||||
? {
|
||||
...(options.progress.onOutputLine
|
||||
? {
|
||||
onStdoutLine: (line: string) =>
|
||||
options.progress?.onOutputLine?.({ stream: "stdout", text: line }) ??
|
||||
Effect.void,
|
||||
onStderrLine: (line: string) =>
|
||||
options.progress?.onOutputLine?.({ stream: "stderr", text: line }) ??
|
||||
Effect.void,
|
||||
}
|
||||
: {}),
|
||||
...(options.progress.onHookStarted
|
||||
? { onHookStarted: options.progress.onHookStarted }
|
||||
: {}),
|
||||
...(options.progress.onHookFinished
|
||||
? { onHookFinished: options.progress.onHookFinished }
|
||||
: {}),
|
||||
}
|
||||
: null;
|
||||
yield* executeGit("GitCore.commit.commit", cwd, args, {
|
||||
...(options?.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),
|
||||
...(progress ? { progress } : {}),
|
||||
}).pipe(Effect.asVoid);
|
||||
const commitSha = yield* runGitStdout("GitCore.commit.revParseHead", cwd, [
|
||||
"rev-parse",
|
||||
"HEAD",
|
||||
|
||||
@@ -6,6 +6,7 @@ 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";
|
||||
@@ -20,6 +21,11 @@ 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[];
|
||||
prListByHeadSelector?: Record<string, string>;
|
||||
@@ -449,12 +455,21 @@ 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);
|
||||
return manager.runStackedAction(
|
||||
{
|
||||
...input,
|
||||
actionId: input.actionId ?? "test-action-id",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
},
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
function resolvePullRequest(manager: GitManagerShape, input: { cwd: string; reference: string }) {
|
||||
@@ -1941,4 +1956,117 @@ 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",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -2,6 +2,7 @@ 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,
|
||||
@@ -9,11 +10,21 @@ import {
|
||||
} from "@t3tools/shared/git";
|
||||
|
||||
import { GitManagerError } from "../Errors.ts";
|
||||
import { GitManager, type GitManagerShape } from "../Services/GitManager.ts";
|
||||
import {
|
||||
GitManager,
|
||||
type GitActionProgressReporter,
|
||||
type GitManagerShape,
|
||||
type GitRunStackedActionOptions,
|
||||
} 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;
|
||||
@@ -200,6 +211,17 @@ 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;
|
||||
@@ -337,6 +359,29 @@ 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,
|
||||
@@ -639,7 +684,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
/** When true, also produce a semantic feature branch name. */
|
||||
includeBranch?: boolean;
|
||||
filePaths?: readonly string[];
|
||||
model?: string;
|
||||
modelSelection: ModelSelection;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* gitCore.prepareCommitContext(input.cwd, input.filePaths);
|
||||
@@ -666,7 +711,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
stagedSummary: limitContext(context.stagedSummary, 8_000),
|
||||
stagedPatch: limitContext(context.stagedPatch, 50_000),
|
||||
...(input.includeBranch ? { includeBranch: true } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
modelSelection: input.modelSelection,
|
||||
})
|
||||
.pipe(Effect.map((result) => sanitizeCommitMessage(result)));
|
||||
|
||||
@@ -679,28 +724,112 @@ 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[],
|
||||
model?: string,
|
||||
progressReporter?: GitActionProgressReporter,
|
||||
actionId?: string,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const suggestion =
|
||||
preResolvedSuggestion ??
|
||||
(yield* resolveCommitAndBranchSuggestion({
|
||||
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({
|
||||
cwd,
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
}));
|
||||
modelSelection,
|
||||
});
|
||||
}
|
||||
if (!suggestion) {
|
||||
return { status: "skipped_no_changes" as const };
|
||||
}
|
||||
|
||||
const { commitSha } = yield* gitCore.commit(cwd, suggestion.subject, suggestion.body);
|
||||
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;
|
||||
}
|
||||
return {
|
||||
status: "created" as const,
|
||||
commitSha,
|
||||
@@ -708,7 +837,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
};
|
||||
});
|
||||
|
||||
const runPrStep = (cwd: string, fallbackBranch: string | null, model?: string) =>
|
||||
const runPrStep = (modelSelection: ModelSelection, cwd: string, fallbackBranch: string | null) =>
|
||||
Effect.gen(function* () {
|
||||
const details = yield* gitCore.statusDetails(cwd);
|
||||
const branch = details.branch ?? fallbackBranch;
|
||||
@@ -752,7 +881,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),
|
||||
...(model ? { model } : {}),
|
||||
modelSelection,
|
||||
});
|
||||
|
||||
const bodyFile = path.join(tempDir, `t3code-pr-body-${process.pid}-${randomUUID()}.md`);
|
||||
@@ -973,11 +1102,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({
|
||||
@@ -986,7 +1115,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
...(model ? { model } : {}),
|
||||
modelSelection,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
@@ -1010,66 +1139,135 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
});
|
||||
|
||||
const runStackedAction: GitManagerShape["runStackedAction"] = Effect.fnUntraced(
|
||||
function* (input) {
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
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;
|
||||
|
||||
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 runAction = Effect.gen(function* () {
|
||||
yield* progress.emit({
|
||||
kind: "action_started",
|
||||
phases,
|
||||
});
|
||||
|
||||
let branchStep: { status: "created" | "skipped_not_requested"; name?: string };
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
const wantsPush = input.action !== "commit";
|
||||
const wantsPr = input.action === "commit_push_pr";
|
||||
|
||||
if (input.featureBranch) {
|
||||
const result = yield* runFeatureBranchStep(
|
||||
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,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.action,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
options?.progressReporter,
|
||||
progress.actionId,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
preResolvedCommitSuggestion = result.resolvedCommitSuggestion;
|
||||
} else {
|
||||
branchStep = { status: "skipped_not_requested" as const };
|
||||
}
|
||||
|
||||
const currentBranch = branchStep.name ?? initialStatus.branch;
|
||||
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 };
|
||||
|
||||
const commit = yield* runCommitStep(
|
||||
input.cwd,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
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 };
|
||||
|
||||
const result = {
|
||||
action: input.action,
|
||||
branch: branchStep,
|
||||
commit,
|
||||
push,
|
||||
pr,
|
||||
};
|
||||
yield* progress.emit({
|
||||
kind: "action_finished",
|
||||
result,
|
||||
});
|
||||
return result;
|
||||
});
|
||||
|
||||
return yield* runAction.pipe(
|
||||
Effect.catch((error) =>
|
||||
progress
|
||||
.emit({
|
||||
kind: "action_failed",
|
||||
phase: currentPhase,
|
||||
message: error.message,
|
||||
})
|
||||
.pipe(Effect.flatMap(() => Effect.fail(error))),
|
||||
),
|
||||
);
|
||||
|
||||
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,72 @@
|
||||
/**
|
||||
* 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));
|
||||
@@ -0,0 +1,150 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* 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 };
|
||||
}
|
||||
@@ -32,6 +32,7 @@ export interface ExecuteGitInput {
|
||||
readonly allowNonZeroExit?: boolean;
|
||||
readonly timeoutMs?: number;
|
||||
readonly maxOutputBytes?: number;
|
||||
readonly progress?: ExecuteGitProgress;
|
||||
}
|
||||
|
||||
export interface ExecuteGitResult {
|
||||
@@ -49,6 +50,35 @@ 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,6 +162,7 @@ export interface GitCoreShape {
|
||||
cwd: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
options?: GitCommitOptions,
|
||||
) => Effect.Effect<{ commitSha: string }, GitCommandError>;
|
||||
|
||||
/**
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
* @module GitManager
|
||||
*/
|
||||
import {
|
||||
GitActionProgressEvent,
|
||||
GitPreparePullRequestThreadInput,
|
||||
GitPreparePullRequestThreadResult,
|
||||
GitPullRequestRefInput,
|
||||
@@ -20,6 +21,15 @@ 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.
|
||||
*/
|
||||
@@ -51,6 +61,7 @@ export interface GitManagerShape {
|
||||
*/
|
||||
readonly runStackedAction: (
|
||||
input: GitRunStackedActionInput,
|
||||
options?: GitRunStackedActionOptions,
|
||||
) => Effect.Effect<GitRunStackedActionResult, GitManagerServiceError>;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,10 +8,13 @@
|
||||
*/
|
||||
import { ServiceMap } from "effect";
|
||||
import type { Effect } from "effect";
|
||||
import type { ChatAttachment } from "@t3tools/contracts";
|
||||
import type { ChatAttachment, ModelSelection } 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;
|
||||
@@ -19,8 +22,8 @@ export interface CommitMessageGenerationInput {
|
||||
stagedPatch: string;
|
||||
/** When true, the model also returns a semantic branch name for the change. */
|
||||
includeBranch?: boolean;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface CommitMessageGenerationResult {
|
||||
@@ -37,8 +40,8 @@ export interface PrContentGenerationInput {
|
||||
commitSummary: string;
|
||||
diffSummary: string;
|
||||
diffPatch: string;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface PrContentGenerationResult {
|
||||
@@ -50,8 +53,8 @@ export interface BranchNameGenerationInput {
|
||||
cwd: string;
|
||||
message: string;
|
||||
attachments?: ReadonlyArray<ChatAttachment> | undefined;
|
||||
/** Model to use for generation. Defaults to gpt-5.4-mini if not specified. */
|
||||
model?: string;
|
||||
/** What model and provider to use for generation. */
|
||||
modelSelection: ModelSelection;
|
||||
}
|
||||
|
||||
export interface BranchNameGenerationResult {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export function isGitRepository(cwd: string): boolean {
|
||||
return existsSync(join(cwd, ".git"));
|
||||
}
|
||||
@@ -4,7 +4,9 @@ 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";
|
||||
@@ -15,7 +17,9 @@ 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);
|
||||
@@ -51,6 +55,13 @@ 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,
|
||||
@@ -151,6 +162,99 @@ 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));
|
||||
|
||||
+138
-30
@@ -27,12 +27,28 @@ 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>;
|
||||
@@ -41,6 +57,7 @@ interface CliInput {
|
||||
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>;
|
||||
}
|
||||
@@ -91,12 +108,8 @@ export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
|
||||
const CliEnvConfig = Config.all({
|
||||
mode: Config.string("T3CODE_MODE").pipe(
|
||||
Config.option,
|
||||
Config.map(
|
||||
Option.match<RuntimeMode, string>({
|
||||
onNone: () => "web",
|
||||
onSome: (value) => (value === "desktop" ? "desktop" : "web"),
|
||||
}),
|
||||
),
|
||||
Config.map(Option.map((value) => (value === "desktop" ? "desktop" : "web"))),
|
||||
Config.map(Option.getOrUndefined),
|
||||
),
|
||||
port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
|
||||
@@ -110,6 +123,10 @@ 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),
|
||||
@@ -123,6 +140,14 @@ 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,
|
||||
@@ -136,39 +161,115 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
),
|
||||
);
|
||||
|
||||
const mode = Option.getOrElse(input.mode, () => env.mode);
|
||||
const bootstrapFd = Option.getOrUndefined(input.bootstrapFd) ?? env.bootstrapFd;
|
||||
const bootstrapEnvelope =
|
||||
bootstrapFd !== undefined
|
||||
? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
|
||||
: Option.none();
|
||||
|
||||
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 mode: RuntimeMode = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.mode,
|
||||
Option.fromUndefinedOr(env.mode),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.mode), isRuntimeMode),
|
||||
),
|
||||
),
|
||||
() => "web",
|
||||
);
|
||||
const port = yield* Option.match(
|
||||
resolveOptionPrecedence(
|
||||
input.port,
|
||||
Option.fromUndefinedOr(env.port),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.filter(Option.fromUndefinedOr(bootstrap.port), isValidPort),
|
||||
),
|
||||
),
|
||||
{
|
||||
onSome: (value) => Effect.succeed(value),
|
||||
onNone: () => {
|
||||
if (mode === "desktop") {
|
||||
return Effect.succeed(DEFAULT_PORT);
|
||||
}
|
||||
return findAvailablePort(DEFAULT_PORT);
|
||||
},
|
||||
},
|
||||
});
|
||||
);
|
||||
|
||||
const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
|
||||
const baseDir = yield* resolveBaseDir(Option.getOrUndefined(input.t3Home) ?? env.t3Home);
|
||||
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, env.noBrowser ?? mode === "desktop");
|
||||
const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
|
||||
const noBrowser = resolveBooleanFlag(
|
||||
input.noBrowser,
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.noBrowser),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.noBrowser),
|
||||
),
|
||||
),
|
||||
() => mode === "desktop",
|
||||
),
|
||||
);
|
||||
const authToken = resolveOptionPrecedence(
|
||||
input.authToken,
|
||||
Option.fromUndefinedOr(env.authToken),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.authToken),
|
||||
),
|
||||
);
|
||||
const autoBootstrapProjectFromCwd = resolveBooleanFlag(
|
||||
input.autoBootstrapProjectFromCwd,
|
||||
env.autoBootstrapProjectFromCwd ?? mode === "web",
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
|
||||
),
|
||||
),
|
||||
() => mode === "web",
|
||||
),
|
||||
);
|
||||
const logWebSocketEvents = resolveBooleanFlag(
|
||||
input.logWebSocketEvents,
|
||||
env.logWebSocketEvents ?? Boolean(devUrl),
|
||||
Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
Option.fromUndefinedOr(env.logWebSocketEvents),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) =>
|
||||
Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
|
||||
),
|
||||
),
|
||||
() => Boolean(devUrl),
|
||||
),
|
||||
);
|
||||
const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
|
||||
const host =
|
||||
Option.getOrUndefined(input.host) ??
|
||||
env.host ??
|
||||
(mode === "desktop" ? "127.0.0.1" : undefined);
|
||||
const host = Option.getOrElse(
|
||||
resolveOptionPrecedence(
|
||||
input.host,
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
mode,
|
||||
@@ -180,7 +281,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
staticDir,
|
||||
devUrl,
|
||||
noBrowser,
|
||||
authToken,
|
||||
authToken: Option.getOrUndefined(authToken),
|
||||
autoBootstrapProjectFromCwd,
|
||||
logWebSocketEvents,
|
||||
} satisfies ServerConfigShape;
|
||||
@@ -197,6 +298,7 @@ const LayerLive = (input: CliInput) =>
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
|
||||
@@ -287,7 +389,7 @@ const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
const portFlag = Flag.integer("port").pipe(
|
||||
Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
|
||||
Flag.withSchema(PortSchema),
|
||||
Flag.withDescription("Port for the HTTP/WebSocket server."),
|
||||
Flag.optional,
|
||||
);
|
||||
@@ -313,6 +415,11 @@ 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.",
|
||||
@@ -335,6 +442,7 @@ export const t3Cli = Command.make("t3", {
|
||||
devUrl: devUrlFlag,
|
||||
noBrowser: noBrowserFlag,
|
||||
authToken: authTokenFlag,
|
||||
bootstrapFd: bootstrapFdFlag,
|
||||
autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
|
||||
logWebSocketEvents: logWebSocketEventsFlag,
|
||||
}).pipe(
|
||||
|
||||
@@ -282,7 +282,10 @@ describe("CheckpointReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Test Project",
|
||||
workspaceRoot: options?.projectWorkspaceRoot ?? cwd,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -293,7 +296,10 @@ describe("CheckpointReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "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/isRepo.ts";
|
||||
import { isGitRepository } from "../../git/Utils.ts";
|
||||
|
||||
type ReactorInput =
|
||||
| {
|
||||
|
||||
@@ -72,7 +72,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -83,7 +86,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -126,7 +132,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "Replay Project",
|
||||
workspaceRoot: "/tmp/project-replay",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -137,7 +146,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-replay"),
|
||||
projectId: asProjectId("project-replay"),
|
||||
title: "replay",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -178,7 +190,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "Stream Project",
|
||||
workspaceRoot: "/tmp/project-stream",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -199,7 +214,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-stream"),
|
||||
projectId: asProjectId("project-stream"),
|
||||
title: "domain-stream",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -233,7 +251,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn Diff Project",
|
||||
workspaceRoot: "/tmp/project-turn-diff",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -244,7 +265,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-turn-diff"),
|
||||
projectId: asProjectId("project-turn-diff"),
|
||||
title: "Turn diff thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -344,7 +368,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "Flaky Project",
|
||||
workspaceRoot: "/tmp/project-flaky",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -357,7 +384,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-fail"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-fail",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -374,7 +404,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-flaky-ok"),
|
||||
projectId: asProjectId("project-flaky"),
|
||||
title: "flaky-ok",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -428,7 +461,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "Atomic Project",
|
||||
workspaceRoot: "/tmp/project-atomic",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -439,7 +475,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-atomic"),
|
||||
projectId: asProjectId("project-atomic"),
|
||||
title: "atomic",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -563,7 +602,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "Sync Project",
|
||||
workspaceRoot: "/tmp/project-sync",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -574,7 +616,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-sync"),
|
||||
projectId: asProjectId("project-sync"),
|
||||
title: "sync-before",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -642,7 +687,10 @@ describe("OrchestrationEngine", () => {
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "Duplicate Project",
|
||||
workspaceRoot: "/tmp/project-duplicate",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -654,7 +702,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -671,7 +722,10 @@ describe("OrchestrationEngine", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-duplicate"),
|
||||
projectId: asProjectId("project-duplicate"),
|
||||
title: "duplicate",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -68,7 +68,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -89,7 +89,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -337,7 +340,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Project Clear Attachments",
|
||||
workspaceRoot: "/tmp/project-clear-attachments",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -358,7 +361,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-clear-attachments"),
|
||||
projectId: ProjectId.makeUnsafe("project-clear-attachments"),
|
||||
title: "Thread Clear Attachments",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -462,7 +468,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Project Overwrite",
|
||||
workspaceRoot: "/tmp/project-overwrite",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -483,7 +489,10 @@ it.layer(
|
||||
threadId: ThreadId.makeUnsafe("thread-overwrite"),
|
||||
projectId: ProjectId.makeUnsafe("project-overwrite"),
|
||||
title: "Thread Overwrite",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -607,7 +616,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Project Rollback",
|
||||
workspaceRoot: "/tmp/project-rollback",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -628,7 +637,10 @@ it.layer(
|
||||
threadId: ThreadId.makeUnsafe("thread-rollback"),
|
||||
projectId: ProjectId.makeUnsafe("project-rollback"),
|
||||
title: "Thread Rollback",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -733,7 +745,7 @@ it.layer(
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Project Revert Files",
|
||||
workspaceRoot: "/tmp/project-revert-files",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -754,7 +766,10 @@ it.layer(
|
||||
threadId,
|
||||
projectId: ProjectId.makeUnsafe("project-revert-files"),
|
||||
title: "Thread Revert Files",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -938,7 +953,7 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Project Delete Files",
|
||||
workspaceRoot: "/tmp/project-delete-files",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -959,7 +974,10 @@ it.layer(Layer.fresh(makeProjectionPipelinePrefixedTestLayer("t3-projection-atta
|
||||
threadId,
|
||||
projectId: ProjectId.makeUnsafe("project-delete-files"),
|
||||
title: "Thread Delete Files",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1098,7 +1116,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -1119,7 +1137,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-a"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1222,7 +1243,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Project Empty",
|
||||
workspaceRoot: "/tmp/project-empty",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -1243,7 +1264,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-empty"),
|
||||
projectId: ProjectId.makeUnsafe("project-empty"),
|
||||
title: "Thread Empty",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1359,7 +1383,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Project Conflict",
|
||||
workspaceRoot: "/tmp/project-conflict",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T13:00:00.000Z",
|
||||
updatedAt: "2026-02-26T13:00:00.000Z",
|
||||
@@ -1380,7 +1404,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-conflict"),
|
||||
projectId: ProjectId.makeUnsafe("project-conflict"),
|
||||
title: "Thread Conflict",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1500,7 +1527,7 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Project Revert",
|
||||
workspaceRoot: "/tmp/project-revert",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: "2026-02-26T12:00:00.000Z",
|
||||
updatedAt: "2026-02-26T12:00:00.000Z",
|
||||
@@ -1521,7 +1548,10 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
|
||||
threadId: ThreadId.makeUnsafe("thread-revert"),
|
||||
projectId: ProjectId.makeUnsafe("project-revert"),
|
||||
title: "Thread Revert",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -1837,7 +1867,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-live"),
|
||||
title: "Live Project",
|
||||
workspaceRoot: "/tmp/project-live",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -1872,7 +1905,10 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-scripts"),
|
||||
title: "Scripts Project",
|
||||
workspaceRoot: "/tmp/project-scripts",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
|
||||
@@ -1889,16 +1925,19 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
],
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
});
|
||||
|
||||
const projectRows = yield* sql<{
|
||||
readonly scriptsJson: string;
|
||||
readonly defaultModel: string;
|
||||
readonly defaultModelSelection: string;
|
||||
}>`
|
||||
SELECT
|
||||
scripts_json AS "scriptsJson",
|
||||
default_model AS "defaultModel"
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-scripts'
|
||||
`;
|
||||
@@ -1906,7 +1945,7 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
{
|
||||
scriptsJson:
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: '{"provider":"codex","model":"gpt-5"}',
|
||||
},
|
||||
]);
|
||||
}),
|
||||
|
||||
@@ -362,7 +362,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
workspaceRoot: event.payload.workspaceRoot,
|
||||
defaultModel: event.payload.defaultModel,
|
||||
defaultModelSelection: event.payload.defaultModelSelection,
|
||||
scripts: event.payload.scripts,
|
||||
createdAt: event.payload.createdAt,
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -383,8 +383,8 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
...(event.payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: event.payload.workspaceRoot }
|
||||
: {}),
|
||||
...(event.payload.defaultModel !== undefined
|
||||
? { defaultModel: event.payload.defaultModel }
|
||||
...(event.payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: event.payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(event.payload.scripts !== undefined ? { scripts: event.payload.scripts } : {}),
|
||||
updatedAt: event.payload.updatedAt,
|
||||
@@ -420,7 +420,7 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
projectId: event.payload.projectId,
|
||||
title: event.payload.title,
|
||||
model: event.payload.model,
|
||||
modelSelection: event.payload.modelSelection,
|
||||
runtimeMode: event.payload.runtimeMode,
|
||||
interactionMode: event.payload.interactionMode,
|
||||
branch: event.payload.branch,
|
||||
@@ -442,7 +442,9 @@ const makeOrchestrationProjectionPipeline = Effect.gen(function* () {
|
||||
yield* projectionThreadRepository.upsert({
|
||||
...existingRow.value,
|
||||
...(event.payload.title !== undefined ? { title: event.payload.title } : {}),
|
||||
...(event.payload.model !== undefined ? { model: event.payload.model } : {}),
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
...(event.payload.branch !== undefined ? { branch: event.payload.branch } : {}),
|
||||
...(event.payload.worktreePath !== undefined
|
||||
? { worktreePath: event.payload.worktreePath }
|
||||
|
||||
@@ -34,7 +34,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_model,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
@@ -44,7 +44,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'gpt-5-codex',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
'[{"id":"script-1","name":"Build","command":"bun run build","icon":"build","runOnWorktreeCreate":false}]',
|
||||
'2026-02-24T00:00:00.000Z',
|
||||
'2026-02-24T00:00:01.000Z',
|
||||
@@ -57,7 +57,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
model_selection_json,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
@@ -69,7 +69,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'gpt-5-codex',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
@@ -234,7 +234,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
id: asProjectId("project-1"),
|
||||
title: "Project 1",
|
||||
workspaceRoot: "/tmp/project-1",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [
|
||||
{
|
||||
id: "script-1",
|
||||
@@ -254,7 +257,10 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
ModelSelection,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -45,6 +46,7 @@ import {
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
@@ -55,7 +57,11 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread;
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
@@ -141,7 +147,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -160,7 +166,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -531,22 +537,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const projects: Array<OrchestrationProject> = projectRows.map((row) => ({
|
||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModel: row.defaultModel,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}));
|
||||
|
||||
const threads: Array<OrchestrationThread> = threadRows.map((row) => ({
|
||||
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
model: row.model,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
|
||||
@@ -2,7 +2,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import type { ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import type { ModelSelection, ProviderRuntimeEvent, ProviderSession } from "@t3tools/contracts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
@@ -34,6 +34,7 @@ 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 =>
|
||||
@@ -93,37 +94,27 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
async function createHarness(input?: {
|
||||
readonly baseDir?: string;
|
||||
readonly threadModel?: string;
|
||||
readonly threadModelSelection?: ModelSelection;
|
||||
readonly sessionModelSwitch?: "unsupported" | "in-session";
|
||||
}) {
|
||||
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);
|
||||
createdStateDirs.add(stateDir);
|
||||
const threadModel = input?.threadModel ?? "gpt-5-codex";
|
||||
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 &&
|
||||
@@ -132,7 +123,7 @@ describe("ProviderCommandReactor", () => {
|
||||
? ThreadId.makeUnsafe(input.threadId)
|
||||
: ThreadId.makeUnsafe(`thread-${sessionIndex}`);
|
||||
const session: ProviderSession = {
|
||||
provider,
|
||||
provider: modelSelection.provider,
|
||||
status: "ready" as const,
|
||||
runtimeMode:
|
||||
typeof input === "object" &&
|
||||
@@ -141,7 +132,7 @@ describe("ProviderCommandReactor", () => {
|
||||
(input.runtimeMode === "approval-required" || input.runtimeMode === "full-access")
|
||||
? input.runtimeMode
|
||||
: "full-access",
|
||||
...(model !== undefined ? { model } : {}),
|
||||
...(modelSelection.model !== undefined ? { model: modelSelection.model } : {}),
|
||||
threadId,
|
||||
resumeCursor: resumeCursor ?? { opaque: `resume-${sessionIndex}` },
|
||||
createdAt: now,
|
||||
@@ -203,9 +194,9 @@ describe("ProviderCommandReactor", () => {
|
||||
respondToUserInput: respondToUserInput as ProviderServiceShape["respondToUserInput"],
|
||||
stopSession: stopSession as ProviderServiceShape["stopSession"],
|
||||
listSessions: () => Effect.succeed(runtimeSessions),
|
||||
getCapabilities: (provider) =>
|
||||
getCapabilities: (_provider) =>
|
||||
Effect.succeed({
|
||||
sessionModelSwitch: provider === "codex" ? "in-session" : "in-session",
|
||||
sessionModelSwitch: input?.sessionModelSwitch ?? "in-session",
|
||||
}),
|
||||
rollbackConversation: () => unsupported(),
|
||||
streamEvents: Stream.fromPubSub(runtimeEventPubSub),
|
||||
@@ -224,6 +215,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(NodeServices.layer),
|
||||
);
|
||||
@@ -242,7 +234,7 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModel: threadModel,
|
||||
defaultModelSelection: modelSelection,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -253,7 +245,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: threadModel,
|
||||
modelSelection: modelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -303,7 +295,10 @@ 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",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
|
||||
@@ -328,10 +323,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -345,9 +340,10 @@ 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({
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -355,9 +351,10 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -366,7 +363,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("forwards claude effort options through session start and turn send", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -380,10 +379,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with effort",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -396,19 +395,20 @@ 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({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -416,7 +416,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("forwards claude fast mode options through session start and turn send", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-opus-4-6" });
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -430,10 +432,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello with fast mode",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -446,19 +448,20 @@ 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({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -504,7 +507,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("rejects a first turn when requested provider conflicts with the thread model", async () => {
|
||||
const harness = await createHarness();
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "codex", model: "gpt-5-codex" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -518,7 +523,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "hello claude",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -552,49 +560,53 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects a turn when the requested model belongs to a different provider", async () => {
|
||||
const harness = await createHarness();
|
||||
it("preserves the active session model when in-session model switching is unsupported", async () => {
|
||||
const harness = await createHarness({ sessionModelSwitch: "unsupported" });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-model-provider-mismatch"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-model-provider-mismatch"),
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
model: "claude-sonnet-4-6",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
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"),
|
||||
);
|
||||
return (
|
||||
thread?.activities.some((activity) => activity.kind === "provider.turn.start.failed") ??
|
||||
false
|
||||
);
|
||||
});
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession).not.toHaveBeenCalled();
|
||||
expect(harness.sendTurn).not.toHaveBeenCalled();
|
||||
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,
|
||||
}),
|
||||
);
|
||||
|
||||
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'"),
|
||||
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",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -646,7 +658,9 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
|
||||
it("restarts claude sessions when claude effort changes", async () => {
|
||||
const harness = await createHarness({ threadModel: "claude-sonnet-4-6" });
|
||||
const harness = await createHarness({
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -660,10 +674,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "first claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
@@ -687,10 +701,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second claude turn",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -703,10 +717,11 @@ 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({
|
||||
provider: "claudeAgent",
|
||||
resumeCursor: { opaque: "resume-1" },
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -800,6 +815,51 @@ 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();
|
||||
@@ -835,7 +895,10 @@ describe("ProviderCommandReactor", () => {
|
||||
text: "second",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "claudeAgent",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
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, Layer, Option, Schema, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Equal, Layer, Option, Schema, Stream } from "effect";
|
||||
import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
|
||||
|
||||
import { resolveThreadWorkspaceCwd } from "../../checkpointing/Utils.ts";
|
||||
@@ -26,7 +24,7 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { inferProviderForModel } from "@t3tools/shared/model";
|
||||
import { ServerSettingsService, deriveProviderStartOptions } from "../../serverSettings.ts";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -76,11 +74,6 @@ 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)) {
|
||||
@@ -144,6 +137,7 @@ 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,
|
||||
@@ -157,8 +151,7 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
const threadModelOptions = new Map<string, ProviderModelOptions>();
|
||||
const threadModelSelections = new Map<string, ModelSelection>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
readonly threadId: ThreadId;
|
||||
@@ -215,10 +208,7 @@ const make = Effect.gen(function* () {
|
||||
threadId: ThreadId,
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -233,26 +223,20 @@ const make = Effect.gen(function* () {
|
||||
)
|
||||
? thread.session.providerName
|
||||
: undefined;
|
||||
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}'.`,
|
||||
});
|
||||
}
|
||||
const requestedModelSelection = options?.modelSelection;
|
||||
const threadProvider: ProviderKind = currentProvider ?? thread.modelSelection.provider;
|
||||
if (
|
||||
options?.model !== undefined &&
|
||||
inferProviderForModel(options.model, threadProvider) !== threadProvider
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== threadProvider
|
||||
) {
|
||||
return yield* new ProviderAdapterRequestError({
|
||||
provider: threadProvider,
|
||||
method: "thread.turn.start",
|
||||
detail: `Model '${options.model}' does not belong to provider '${threadProvider}' for thread '${threadId}'.`,
|
||||
detail: `Thread '${threadId}' is bound to provider '${threadProvider}' and cannot switch to '${requestedModelSelection.provider}'.`,
|
||||
});
|
||||
}
|
||||
const preferredProvider: ProviderKind = currentProvider ?? threadProvider;
|
||||
const desiredModel = options?.model ?? thread.model;
|
||||
const desiredModelSelection = requestedModelSelection ?? thread.modelSelection;
|
||||
const effectiveCwd = resolveThreadWorkspaceCwd({
|
||||
thread,
|
||||
projects: readModel.projects,
|
||||
@@ -267,19 +251,18 @@ const make = Effect.gen(function* () {
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly provider?: ProviderKind;
|
||||
}) =>
|
||||
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,
|
||||
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,
|
||||
});
|
||||
});
|
||||
|
||||
const bindSessionToThread = (session: ProviderSession) =>
|
||||
@@ -303,25 +286,28 @@ const make = Effect.gen(function* () {
|
||||
if (existingSessionThreadId) {
|
||||
const runtimeModeChanged = thread.runtimeMode !== thread.session?.runtimeMode;
|
||||
const providerChanged =
|
||||
options?.provider !== undefined && options.provider !== currentProvider;
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.provider !== currentProvider;
|
||||
const activeSession = yield* resolveActiveSession(existingSessionThreadId);
|
||||
const sessionModelSwitch =
|
||||
currentProvider === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(currentProvider)).sessionModelSwitch;
|
||||
const modelChanged = options?.model !== undefined && options.model !== activeSession?.model;
|
||||
const modelChanged =
|
||||
requestedModelSelection !== undefined &&
|
||||
requestedModelSelection.model !== activeSession?.model;
|
||||
const shouldRestartForModelChange = modelChanged && sessionModelSwitch === "restart-session";
|
||||
const previousModelOptions = threadModelOptions.get(threadId);
|
||||
const shouldRestartForModelOptionsChange =
|
||||
const previousModelSelection = threadModelSelections.get(threadId);
|
||||
const shouldRestartForModelSelectionChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
options?.modelOptions !== undefined &&
|
||||
!sameModelOptions(previousModelOptions, options.modelOptions);
|
||||
requestedModelSelection !== undefined &&
|
||||
!Equal.equals(previousModelSelection, requestedModelSelection);
|
||||
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
!providerChanged &&
|
||||
!shouldRestartForModelChange &&
|
||||
!shouldRestartForModelOptionsChange
|
||||
!shouldRestartForModelSelectionChange
|
||||
) {
|
||||
return existingSessionThreadId;
|
||||
}
|
||||
@@ -334,20 +320,19 @@ const make = Effect.gen(function* () {
|
||||
threadId,
|
||||
existingSessionThreadId,
|
||||
currentProvider,
|
||||
desiredProvider: options?.provider ?? currentProvider,
|
||||
desiredProvider: desiredModelSelection.provider,
|
||||
currentRuntimeMode: thread.session?.runtimeMode,
|
||||
desiredRuntimeMode: thread.runtimeMode,
|
||||
runtimeModeChanged,
|
||||
providerChanged,
|
||||
modelChanged,
|
||||
shouldRestartForModelChange,
|
||||
shouldRestartForModelOptionsChange,
|
||||
shouldRestartForModelSelectionChange,
|
||||
hasResumeCursor: resumeCursor !== undefined,
|
||||
});
|
||||
const restartedSession = yield* startProviderSession({
|
||||
...(resumeCursor !== undefined ? { resumeCursor } : {}),
|
||||
...(options?.provider !== undefined ? { provider: options.provider } : {}),
|
||||
});
|
||||
const restartedSession = yield* startProviderSession(
|
||||
resumeCursor !== undefined ? { resumeCursor } : undefined,
|
||||
);
|
||||
yield* Effect.logInfo("provider command reactor restarted provider session", {
|
||||
threadId,
|
||||
previousSessionId: existingSessionThreadId,
|
||||
@@ -359,9 +344,7 @@ const make = Effect.gen(function* () {
|
||||
return restartedSession.threadId;
|
||||
}
|
||||
|
||||
const startedSession = yield* startProviderSession(
|
||||
options?.provider !== undefined ? { provider: options.provider } : undefined,
|
||||
);
|
||||
const startedSession = yield* startProviderSession(undefined);
|
||||
yield* bindSessionToThread(startedSession);
|
||||
return startedSession.threadId;
|
||||
});
|
||||
@@ -370,10 +353,7 @@ const make = Effect.gen(function* () {
|
||||
readonly threadId: ThreadId;
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly provider?: ProviderKind;
|
||||
readonly model?: string;
|
||||
readonly modelOptions?: ProviderModelOptions;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
@@ -381,17 +361,13 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
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);
|
||||
yield* ensureSessionForThread(
|
||||
input.threadId,
|
||||
input.createdAt,
|
||||
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
|
||||
);
|
||||
if (input.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
const normalizedInput = toNonEmptyProviderInput(input.messageText);
|
||||
const normalizedAttachments = input.attachments ?? [];
|
||||
@@ -404,14 +380,23 @@ const make = Effect.gen(function* () {
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const modelForTurn = sessionModelSwitch === "unsupported" ? activeSession?.model : input.model;
|
||||
const requestedModelSelection =
|
||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported"
|
||||
? activeSession?.model !== undefined
|
||||
? {
|
||||
...requestedModelSelection,
|
||||
model: activeSession.model,
|
||||
}
|
||||
: requestedModelSelection
|
||||
: input.modelSelection;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
threadId: input.threadId,
|
||||
...(normalizedInput ? { input: normalizedInput } : {}),
|
||||
...(normalizedAttachments.length > 0 ? { attachments: normalizedAttachments } : {}),
|
||||
...(modelForTurn !== undefined ? { model: modelForTurn } : {}),
|
||||
...(input.modelOptions !== undefined ? { modelOptions: input.modelOptions } : {}),
|
||||
...(modelForTurn !== undefined ? { modelSelection: modelForTurn } : {}),
|
||||
...(input.interactionMode !== undefined ? { interactionMode: input.interactionMode } : {}),
|
||||
});
|
||||
});
|
||||
@@ -449,7 +434,10 @@ const make = Effect.gen(function* () {
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
modelSelection: yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.textGenerationModelSelection,
|
||||
),
|
||||
})
|
||||
.pipe(
|
||||
Effect.catch((error) =>
|
||||
@@ -524,13 +512,8 @@ const make = Effect.gen(function* () {
|
||||
threadId: event.payload.threadId,
|
||||
messageText: message.text,
|
||||
...(message.attachments !== undefined ? { attachments: message.attachments } : {}),
|
||||
...(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 }
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
@@ -697,14 +680,12 @@ const make = Effect.gen(function* () {
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
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 } : {}),
|
||||
});
|
||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(
|
||||
event.payload.threadId,
|
||||
event.occurredAt,
|
||||
cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {},
|
||||
);
|
||||
return;
|
||||
}
|
||||
case "thread.turn-start-requested":
|
||||
|
||||
@@ -12,10 +12,12 @@ import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderItemId,
|
||||
type ServerSettings,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -38,8 +40,20 @@ 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);
|
||||
@@ -155,7 +169,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
}
|
||||
});
|
||||
|
||||
async function createHarness() {
|
||||
async function createHarness(options?: { serverSettings?: Partial<ServerSettings> }) {
|
||||
const workspaceRoot = makeTempDir("t3-provider-project-");
|
||||
fs.mkdirSync(path.join(workspaceRoot, ".git"));
|
||||
const provider = createProviderServiceHarness();
|
||||
@@ -169,6 +183,7 @@ 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),
|
||||
);
|
||||
@@ -187,7 +202,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
}),
|
||||
);
|
||||
@@ -198,7 +216,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -724,7 +745,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -756,7 +780,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -905,7 +932,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1055,7 +1085,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: sourceThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Source",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: "plan",
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1087,7 +1120,10 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
threadId: targetThreadId,
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Plan Target",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -1336,7 +1372,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
||||
const harness = await createHarness();
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const now = new Date().toISOString();
|
||||
|
||||
await Effect.runPromise(
|
||||
@@ -1350,7 +1386,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
text: "stream please",
|
||||
attachments: [],
|
||||
},
|
||||
assistantDeliveryMode: "streaming",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
@@ -1898,6 +1933,185 @@ 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();
|
||||
|
||||
@@ -8,29 +8,30 @@ import {
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
} from "@t3tools/contracts";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, Ref, Stream } from "effect";
|
||||
import { Cache, Cause, Duration, Effect, Layer, Option, 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/isRepo.ts";
|
||||
import { isGitRepository } from "../../git/Utils.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 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;
|
||||
@@ -101,6 +102,15 @@ 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") {
|
||||
@@ -409,6 +419,48 @@ function runtimeEventToActivities(
|
||||
];
|
||||
}
|
||||
|
||||
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,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "item.updated": {
|
||||
if (!isToolLifecycleItemType(event.payload.itemType)) {
|
||||
return [];
|
||||
@@ -485,10 +537,7 @@ const make = Effect.gen(function* () {
|
||||
const orchestrationEngine = yield* OrchestrationEngineService;
|
||||
const providerService = yield* ProviderService;
|
||||
const projectionTurnRepository = yield* ProjectionTurnRepository;
|
||||
|
||||
const assistantDeliveryModeRef = yield* Ref.make<AssistantDeliveryMode>(
|
||||
DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
);
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
|
||||
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
|
||||
@@ -996,7 +1045,10 @@ const make = Effect.gen(function* () {
|
||||
yield* rememberAssistantMessageId(thread.id, turnId, assistantMessageId);
|
||||
}
|
||||
|
||||
const assistantDeliveryMode = yield* Ref.get(assistantDeliveryModeRef);
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||
);
|
||||
if (assistantDeliveryMode === "buffered") {
|
||||
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
|
||||
if (spillChunk.length > 0) {
|
||||
@@ -1204,11 +1256,7 @@ const make = Effect.gen(function* () {
|
||||
).pipe(Effect.asVoid);
|
||||
});
|
||||
|
||||
const processDomainEvent = (event: TurnStartRequestedDomainEvent) =>
|
||||
Ref.set(
|
||||
assistantDeliveryModeRef,
|
||||
event.payload.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
);
|
||||
const processDomainEvent = (_event: TurnStartRequestedDomainEvent) => Effect.void;
|
||||
|
||||
const processInput = (input: RuntimeIngestionInput) =>
|
||||
input.source === "runtime" ? processRuntimeEvent(input.event) : processDomainEvent(input.event);
|
||||
|
||||
@@ -28,7 +28,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Project A",
|
||||
workspaceRoot: "/tmp/project-a",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -38,7 +41,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Project B",
|
||||
workspaceRoot: "/tmp/project-b",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -50,7 +56,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "Thread A",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -69,7 +78,10 @@ const readModel: OrchestrationReadModel = {
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
projectId: ProjectId.makeUnsafe("project-b"),
|
||||
title: "Thread B",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -144,7 +156,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-3"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "new",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -165,7 +180,10 @@ describe("commandInvariants", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: ProjectId.makeUnsafe("project-a"),
|
||||
title: "dup",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "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",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -113,7 +113,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -136,7 +136,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -159,10 +162,10 @@ describe("decider project scripts", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -189,10 +192,10 @@ describe("decider project scripts", () => {
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -220,7 +223,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -243,7 +246,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -299,7 +305,7 @@ describe("decider project scripts", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Project",
|
||||
workspaceRoot: "/tmp/project",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: null,
|
||||
scripts: [],
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
@@ -322,7 +328,10 @@ describe("decider project scripts", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
|
||||
@@ -14,7 +14,6 @@ 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"],
|
||||
@@ -77,7 +76,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
workspaceRoot: command.workspaceRoot,
|
||||
defaultModel: command.defaultModel ?? null,
|
||||
defaultModelSelection: command.defaultModelSelection ?? null,
|
||||
scripts: [],
|
||||
createdAt: command.createdAt,
|
||||
updatedAt: command.createdAt,
|
||||
@@ -104,7 +103,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
projectId: command.projectId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.workspaceRoot !== undefined ? { workspaceRoot: command.workspaceRoot } : {}),
|
||||
...(command.defaultModel !== undefined ? { defaultModel: command.defaultModel } : {}),
|
||||
...(command.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: command.defaultModelSelection }
|
||||
: {}),
|
||||
...(command.scripts !== undefined ? { scripts: command.scripts } : {}),
|
||||
updatedAt: occurredAt,
|
||||
},
|
||||
@@ -156,7 +157,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
threadId: command.threadId,
|
||||
projectId: command.projectId,
|
||||
title: command.title,
|
||||
model: command.model,
|
||||
modelSelection: command.modelSelection,
|
||||
runtimeMode: command.runtimeMode,
|
||||
interactionMode: command.interactionMode,
|
||||
branch: command.branch,
|
||||
@@ -207,7 +208,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
...(command.title !== undefined ? { title: command.title } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.branch !== undefined ? { branch: command.branch } : {}),
|
||||
...(command.worktreePath !== undefined ? { worktreePath: command.worktreePath } : {}),
|
||||
updatedAt: occurredAt,
|
||||
@@ -323,13 +326,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
payload: {
|
||||
threadId: command.threadId,
|
||||
messageId: command.message.messageId,
|
||||
...(command.provider !== undefined ? { provider: command.provider } : {}),
|
||||
...(command.model !== undefined ? { model: command.model } : {}),
|
||||
...(command.modelOptions !== undefined ? { modelOptions: command.modelOptions } : {}),
|
||||
...(command.providerOptions !== undefined
|
||||
? { providerOptions: command.providerOptions }
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
runtimeMode: targetThread.runtimeMode,
|
||||
interactionMode: targetThread.interactionMode,
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
|
||||
@@ -56,7 +56,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -73,7 +76,10 @@ describe("orchestration projector", () => {
|
||||
id: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -110,7 +116,10 @@ describe("orchestration projector", () => {
|
||||
// missing required threadId
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: now,
|
||||
@@ -170,7 +179,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -233,7 +245,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -287,7 +302,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -371,7 +389,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -583,7 +604,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-revert",
|
||||
projectId: "project-1",
|
||||
title: "demo",
|
||||
model: "gpt-5.3-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
@@ -733,7 +757,10 @@ describe("orchestration projector", () => {
|
||||
threadId: "thread-capped",
|
||||
projectId: "project-1",
|
||||
title: "capped",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
|
||||
@@ -181,7 +181,7 @@ export function projectEvent(
|
||||
id: payload.projectId,
|
||||
title: payload.title,
|
||||
workspaceRoot: payload.workspaceRoot,
|
||||
defaultModel: payload.defaultModel,
|
||||
defaultModelSelection: payload.defaultModelSelection,
|
||||
scripts: payload.scripts,
|
||||
createdAt: payload.createdAt,
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -211,8 +211,8 @@ export function projectEvent(
|
||||
...(payload.workspaceRoot !== undefined
|
||||
? { workspaceRoot: payload.workspaceRoot }
|
||||
: {}),
|
||||
...(payload.defaultModel !== undefined
|
||||
? { defaultModel: payload.defaultModel }
|
||||
...(payload.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: payload.defaultModelSelection }
|
||||
: {}),
|
||||
...(payload.scripts !== undefined ? { scripts: payload.scripts } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
@@ -252,7 +252,7 @@ export function projectEvent(
|
||||
id: payload.threadId,
|
||||
projectId: payload.projectId,
|
||||
title: payload.title,
|
||||
model: payload.model,
|
||||
modelSelection: payload.modelSelection,
|
||||
runtimeMode: payload.runtimeMode,
|
||||
interactionMode: payload.interactionMode,
|
||||
branch: payload.branch,
|
||||
@@ -295,7 +295,9 @@ export function projectEvent(
|
||||
...nextBase,
|
||||
threads: updateThread(nextBase.threads, payload.threadId, {
|
||||
...(payload.title !== undefined ? { title: payload.title } : {}),
|
||||
...(payload.model !== undefined ? { model: payload.model } : {}),
|
||||
...(payload.modelSelection !== undefined
|
||||
? { modelSelection: payload.modelSelection }
|
||||
: {}),
|
||||
...(payload.branch !== undefined ? { branch: payload.branch } : {}),
|
||||
...(payload.worktreePath !== undefined ? { worktreePath: payload.worktreePath } : {}),
|
||||
updatedAt: payload.updatedAt,
|
||||
|
||||
@@ -35,7 +35,7 @@ layer("OrchestrationEventStore", (it) => {
|
||||
projectId: ProjectId.makeUnsafe("project-roundtrip"),
|
||||
title: "Roundtrip Project",
|
||||
workspaceRoot: "/tmp/project-roundtrip",
|
||||
defaultModel: null,
|
||||
defaultModelSelection: 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, Option, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionProjectInput,
|
||||
GetProjectionProjectInput,
|
||||
@@ -11,69 +11,64 @@ import {
|
||||
ProjectionProjectRepository,
|
||||
type ProjectionProjectRepositoryShape,
|
||||
} from "../Services/ProjectionProjects.ts";
|
||||
import { ProjectScript } from "@t3tools/contracts";
|
||||
|
||||
// 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)) }),
|
||||
const ProjectionProjectDbRow = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
|
||||
function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: string) {
|
||||
return (cause: unknown) =>
|
||||
Schema.isSchemaError(cause)
|
||||
? toPersistenceDecodeError(decodeOperation)(cause)
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;
|
||||
|
||||
const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
const upsertProjectionProjectRow = SqlSchema.void({
|
||||
Request: ProjectionProjectDbRowSchema,
|
||||
Request: ProjectionProject,
|
||||
execute: (row) =>
|
||||
sql`
|
||||
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
|
||||
`,
|
||||
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
|
||||
`,
|
||||
});
|
||||
|
||||
const getProjectionProjectRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionProjectInput,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -85,14 +80,14 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionProjectRows = SqlSchema.findAll({
|
||||
Request: Schema.Void,
|
||||
Result: ProjectionProjectDbRowSchema,
|
||||
Result: ProjectionProjectDbRow,
|
||||
execute: () =>
|
||||
sql`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_model AS "defaultModel",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -113,40 +108,17 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
|
||||
const upsert: ProjectionProjectRepositoryShape["upsert"] = (row) =>
|
||||
upsertProjectionProjectRow(row).pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.upsert:query",
|
||||
"ProjectionProjectRepository.upsert:encodeRequest",
|
||||
),
|
||||
),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.upsert:query")),
|
||||
);
|
||||
|
||||
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
|
||||
getProjectionProjectRow(input).pipe(
|
||||
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>)),
|
||||
}),
|
||||
),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
|
||||
);
|
||||
|
||||
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
|
||||
listProjectionProjectRows().pipe(
|
||||
Effect.mapError(
|
||||
toPersistenceSqlOrDecodeError(
|
||||
"ProjectionProjectRepository.listAll:query",
|
||||
"ProjectionProjectRepository.listAll:decodeRows",
|
||||
),
|
||||
),
|
||||
Effect.map((rows) => rows as ReadonlyArray<Schema.Schema.Type<typeof ProjectionProject>>),
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
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",
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer } from "effect";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
@@ -11,6 +11,14 @@ 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;
|
||||
@@ -23,7 +31,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
model,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
@@ -37,7 +45,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.model},
|
||||
${JSON.stringify(row.modelSelection)},
|
||||
${row.runtimeMode},
|
||||
${row.interactionMode},
|
||||
${row.branch},
|
||||
@@ -51,7 +59,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
project_id = excluded.project_id,
|
||||
title = excluded.title,
|
||||
model = excluded.model,
|
||||
model_selection_json = excluded.model_selection_json,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
branch = excluded.branch,
|
||||
@@ -65,14 +73,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
|
||||
const getProjectionThreadRow = SqlSchema.findOneOption({
|
||||
Request: GetProjectionThreadInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ threadId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -88,14 +96,14 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
|
||||
const listProjectionThreadRows = SqlSchema.findAll({
|
||||
Request: ListProjectionThreadsByProjectInput,
|
||||
Result: ProjectionThread,
|
||||
Result: ProjectionThreadDbRow,
|
||||
execute: ({ projectId }) =>
|
||||
sql`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
model,
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
|
||||
@@ -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();
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
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";
|
||||
@@ -27,7 +28,7 @@ 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 { Effect } from "effect";
|
||||
import Migration0016 from "./Migrations/016_CanonicalizeModelSelections.ts";
|
||||
|
||||
/**
|
||||
* Migration loader with all migrations defined inline.
|
||||
@@ -39,23 +40,33 @@ import { Effect } from "effect";
|
||||
* Uses Migrator.fromRecord which parses the key format and
|
||||
* returns migrations sorted by ID.
|
||||
*/
|
||||
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,
|
||||
});
|
||||
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]),
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Migrator run function - no schema dumping needed
|
||||
@@ -63,6 +74,10 @@ const loader = Migrator.fromRecord({
|
||||
*/
|
||||
const run = Migrator.make({});
|
||||
|
||||
export interface RunMigrationsOptions {
|
||||
readonly toMigrationInclusive?: number | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run all pending migrations.
|
||||
*
|
||||
@@ -73,11 +88,19 @@ const run = Migrator.make({});
|
||||
*
|
||||
* @returns Effect containing array of executed migrations
|
||||
*/
|
||||
export const runMigrations = Effect.gen(function* () {
|
||||
yield* Effect.log("Running migrations...");
|
||||
yield* run({ loader });
|
||||
yield* Effect.log("Migrations ran successfully");
|
||||
});
|
||||
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.log(
|
||||
toMigrationInclusive === undefined
|
||||
? "Running all migrations..."
|
||||
: `Running migrations 1 through ${toMigrationInclusive}...`,
|
||||
);
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
yield* Effect.log("Migrations ran successfully").pipe(
|
||||
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
|
||||
);
|
||||
return executedMigrations;
|
||||
});
|
||||
|
||||
/**
|
||||
* Layer that runs migrations when the layer is built.
|
||||
@@ -96,4 +119,4 @@ export const runMigrations = Effect.gen(function* () {
|
||||
* )
|
||||
* ```
|
||||
*/
|
||||
export const MigrationsLive = Layer.effectDiscard(runMigrations);
|
||||
export const MigrationsLive = Layer.effectDiscard(runMigrations());
|
||||
@@ -0,0 +1,357 @@
|
||||
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",
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
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
|
||||
`;
|
||||
});
|
||||
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* @module ProjectionProjectRepository
|
||||
*/
|
||||
import { IsoDateTime, ProjectId, ProjectScript } from "@t3tools/contracts";
|
||||
import { IsoDateTime, ModelSelection, 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,
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelSelection: Schema.NullOr(ModelSelection),
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
*/
|
||||
import {
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
@@ -23,7 +24,7 @@ export const ProjectionThread = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: Schema.String,
|
||||
model: Schema.String,
|
||||
modelSelection: ModelSelection,
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
branch: Schema.NullOr(Schema.String),
|
||||
|
||||
@@ -332,13 +332,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -356,13 +357,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -380,13 +382,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -404,13 +407,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -430,13 +434,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -454,13 +459,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -480,13 +486,14 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
@@ -504,22 +511,24 @@ describe("ClaudeAdapterLive", () => {
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
runtimeMode: "full-access",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "ultrathink",
|
||||
},
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "Investigate the edge cases",
|
||||
attachments: [],
|
||||
model: "claude-sonnet-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "ultrathink",
|
||||
},
|
||||
},
|
||||
@@ -613,7 +622,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
const session = yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-5",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-5",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
@@ -1153,12 +1165,79 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("stopSession does not throw into the SDK prompt consumer", () => {
|
||||
// The SDK consumes user messages via `for await (... of prompt)`.
|
||||
// Stopping a session must end that loop cleanly — not throw an error.
|
||||
//
|
||||
// FakeClaudeQuery.close() masks this by resolving pending iterators
|
||||
// before the shutdown propagates. Override it to match real SDK behavior
|
||||
// where close() does not resolve the prompt consumer.
|
||||
const query = new FakeClaudeQuery();
|
||||
(query as { close: () => void }).close = () => {
|
||||
query.closeCalls += 1;
|
||||
};
|
||||
|
||||
let promptConsumerError: unknown = undefined;
|
||||
|
||||
const layer = makeClaudeAdapterLive({
|
||||
createQuery: (input) => {
|
||||
// Simulate the SDK consuming the prompt iterable
|
||||
(async () => {
|
||||
try {
|
||||
for await (const _message of input.prompt) {
|
||||
/* SDK processes user messages */
|
||||
}
|
||||
} catch (error) {
|
||||
promptConsumerError = error;
|
||||
}
|
||||
})();
|
||||
return query;
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = Effect.runFork(
|
||||
Stream.runForEach(adapter.streamEvents, () => Effect.void),
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.stopSession(THREAD_ID);
|
||||
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.yieldNow;
|
||||
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 50)));
|
||||
|
||||
runtimeEventsFiber.interruptUnsafe();
|
||||
|
||||
assert.equal(
|
||||
promptConsumerError,
|
||||
undefined,
|
||||
`Prompt consumer should not receive a thrown error on session stop, ` +
|
||||
`but got: "${promptConsumerError instanceof Error ? promptConsumerError.message : String(promptConsumerError)}"`,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("forwards Claude task progress summaries for subagent updates", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1200,6 +1279,127 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits thread token usage updates from Claude task progress", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "task-usage-1",
|
||||
description: "Thinking through the patch",
|
||||
usage: {
|
||||
total_tokens: 321,
|
||||
tool_uses: 2,
|
||||
duration_ms: 654,
|
||||
},
|
||||
session_id: "sdk-session-task-usage",
|
||||
uuid: "task-usage-progress-1",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
const progressEvent = runtimeEvents.find((event) => event.type === "task.progress");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 321,
|
||||
lastUsedTokens: 321,
|
||||
toolUses: 2,
|
||||
durationMs: 654,
|
||||
},
|
||||
});
|
||||
}
|
||||
assert.equal(progressEvent?.type, "task.progress");
|
||||
if (usageEvent && progressEvent) {
|
||||
assert.notStrictEqual(usageEvent.eventId, progressEvent.eventId);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits Claude context window on result completion usage snapshots", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage",
|
||||
usage: {
|
||||
input_tokens: 4,
|
||||
cache_creation_input_tokens: 2715,
|
||||
cache_read_input_tokens: 21144,
|
||||
output_tokens: 679,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 24542,
|
||||
lastUsedTokens: 24542,
|
||||
inputTokens: 23863,
|
||||
outputTokens: 679,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
@@ -2172,7 +2372,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
yield* adapter.sendTurn({
|
||||
threadId: session.threadId,
|
||||
input: "hello",
|
||||
model: "claude-opus-4-6",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
},
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type ProviderRuntimeTurnStatus,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type ProviderUserInputAnswers,
|
||||
type RuntimeContentStreamKind,
|
||||
RuntimeItemId,
|
||||
@@ -37,15 +38,13 @@ import {
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type UserInputQuestion,
|
||||
ClaudeCodeEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
hasEffortLevel,
|
||||
applyClaudePromptEffortPrefix,
|
||||
getEffectiveClaudeCodeEffort,
|
||||
getReasoningEffortOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
getModelCapabilities,
|
||||
trimOrNull,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
Cause,
|
||||
@@ -156,6 +155,8 @@ interface ClaudeSessionContext {
|
||||
}>;
|
||||
readonly inFlightTools: Map<number, ToolInFlight>;
|
||||
turnState: ClaudeTurnState | undefined;
|
||||
lastKnownContextWindow: number | undefined;
|
||||
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
|
||||
lastAssistantUuid: string | undefined;
|
||||
lastThreadStartedId: string | undefined;
|
||||
stopped: boolean;
|
||||
@@ -209,6 +210,15 @@ function normalizeClaudeStreamMessages(cause: Cause.Cause<Error>): ReadonlyArray
|
||||
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 (
|
||||
@@ -259,6 +269,82 @@ 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;
|
||||
}
|
||||
@@ -434,15 +520,16 @@ const CLAUDE_SETTING_SOURCES = [
|
||||
] as const satisfies ReadonlyArray<SettingSource>;
|
||||
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
input.modelOptions?.claudeAgent?.effort ?? null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
|
||||
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);
|
||||
const promptEffort =
|
||||
requestedEffort === "ultrathink" && supportsClaudeUltrathinkKeyword(input.model)
|
||||
requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0
|
||||
? "ultrathink"
|
||||
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
: requestedEffort && hasEffortLevel(caps, requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
|
||||
@@ -1287,8 +1374,53 @@ 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",
|
||||
@@ -1356,6 +1488,22 @@ 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",
|
||||
@@ -1925,6 +2073,25 @@ 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,
|
||||
type: "task.progress",
|
||||
@@ -1938,6 +2105,25 @@ 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,
|
||||
type: "task.completed",
|
||||
@@ -2258,6 +2444,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
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,
|
||||
);
|
||||
|
||||
@@ -2539,21 +2728,16 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
);
|
||||
|
||||
const providerOptions = input.providerOptions?.claudeAgent;
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
input.modelOptions?.claudeAgent?.effort ?? null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions("claudeAgent", input.model);
|
||||
const modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null);
|
||||
const caps = getModelCapabilities("claudeAgent", modelSelection?.model);
|
||||
const effort =
|
||||
requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
const fastMode =
|
||||
input.modelOptions?.claudeAgent?.fastMode === true && supportsClaudeFastMode(input.model);
|
||||
requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
const thinking =
|
||||
typeof input.modelOptions?.claudeAgent?.thinking === "boolean" &&
|
||||
supportsClaudeThinkingToggle(input.model)
|
||||
? input.modelOptions.claudeAgent.thinking
|
||||
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
|
||||
? modelSelection.options.thinking
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
|
||||
const permissionMode =
|
||||
@@ -2566,7 +2750,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
pathToClaudeCodeExecutable: providerOptions?.binaryPath ?? "claude",
|
||||
settingSources: [...CLAUDE_SETTING_SOURCES],
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
@@ -2607,7 +2791,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
status: "ready",
|
||||
runtimeMode: input.runtimeMode,
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
...(threadId ? { threadId } : {}),
|
||||
resumeCursor: {
|
||||
...(threadId ? { threadId } : {}),
|
||||
@@ -2634,6 +2818,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
turns: [],
|
||||
inFlightTools,
|
||||
turnState: undefined,
|
||||
lastKnownContextWindow: undefined,
|
||||
lastKnownTokenUsage: undefined,
|
||||
lastAssistantUuid: resumeState?.resumeSessionAt,
|
||||
lastThreadStartedId: undefined,
|
||||
stopped: false,
|
||||
@@ -2661,7 +2847,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
threadId,
|
||||
payload: {
|
||||
config: {
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
@@ -2707,6 +2893,8 @@ 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
|
||||
@@ -2714,9 +2902,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
yield* completeTurn(context, "completed");
|
||||
}
|
||||
|
||||
if (input.model) {
|
||||
if (modelSelection?.model) {
|
||||
yield* Effect.tryPromise({
|
||||
try: () => context.query.setModel(input.model),
|
||||
try: () => context.query.setModel(modelSelection.model),
|
||||
catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause),
|
||||
});
|
||||
}
|
||||
@@ -2766,7 +2954,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
createdAt: turnStartedStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId,
|
||||
payload: input.model ? { model: input.model } : {},
|
||||
payload: modelSelection?.model ? { model: modelSelection.model } : {},
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
|
||||
@@ -188,9 +188,10 @@ validationLayer("CodexAdapterLive validation", (it) => {
|
||||
yield* adapter.startSession({
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
@@ -256,9 +257,10 @@ sessionErrorLayer("CodexAdapterLive session errors", (it) => {
|
||||
adapter.sendTurn({
|
||||
threadId: asThreadId("sess-missing"),
|
||||
input: "hello",
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -839,6 +841,70 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
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,6 +11,7 @@ import {
|
||||
type CanonicalRequestType,
|
||||
type ProviderEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
@@ -109,6 +110,48 @@ 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;
|
||||
}
|
||||
@@ -708,12 +751,17 @@ 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: event.payload ?? {},
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -1313,8 +1361,12 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
runtimeMode: input.runtimeMode,
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
|
||||
...(input.modelSelection?.provider === "codex"
|
||||
? { model: input.modelSelection.model }
|
||||
: {}),
|
||||
...(input.modelSelection?.provider === "codex" && input.modelSelection.options?.fastMode
|
||||
? { serviceTier: "fast" }
|
||||
: {}),
|
||||
};
|
||||
|
||||
return Effect.tryPromise({
|
||||
@@ -1370,11 +1422,17 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
const managerInput = {
|
||||
threadId: input.threadId,
|
||||
...(input.input !== undefined ? { input: input.input } : {}),
|
||||
...(input.model !== undefined ? { model: input.model } : {}),
|
||||
...(input.modelOptions?.codex?.reasoningEffort !== undefined
|
||||
? { effort: input.modelOptions.codex.reasoningEffort }
|
||||
...(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.modelOptions?.codex?.fastMode ? { serviceTier: "fast" } : {}),
|
||||
...(input.interactionMode !== undefined
|
||||
? { interactionMode: input.interactionMode }
|
||||
: {}),
|
||||
|
||||
@@ -633,8 +633,10 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
provider: "claudeAgent",
|
||||
threadId: asThreadId("thread-claude-send-turn"),
|
||||
cwd: "/tmp/project-claude-send-turn",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
},
|
||||
@@ -658,14 +660,16 @@ routing.layer("ProviderServiceLive routing", (it) => {
|
||||
const startPayload = resumedStartInput as {
|
||||
provider?: string;
|
||||
cwd?: string;
|
||||
modelOptions?: unknown;
|
||||
modelSelection?: unknown;
|
||||
resumeCursor?: unknown;
|
||||
threadId?: string;
|
||||
};
|
||||
assert.equal(startPayload.provider, "claudeAgent");
|
||||
assert.equal(startPayload.cwd, "/tmp/project-claude-send-turn");
|
||||
assert.deepEqual(startPayload.modelOptions, {
|
||||
claudeAgent: {
|
||||
assert.deepEqual(startPayload.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
* @module ProviderServiceLive
|
||||
*/
|
||||
import {
|
||||
ModelSelection,
|
||||
NonNegativeInt,
|
||||
ThreadId,
|
||||
ProviderInterruptTurnInput,
|
||||
@@ -89,7 +90,7 @@ function toRuntimeStatus(session: ProviderSession): "starting" | "running" | "st
|
||||
function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly modelSelection?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
@@ -100,7 +101,7 @@ function toRuntimePayloadFromSession(
|
||||
model: session.model ?? null,
|
||||
activeTurnId: session.activeTurnId ?? null,
|
||||
lastError: session.lastError ?? null,
|
||||
...(extra?.modelOptions !== undefined ? { modelOptions: extra.modelOptions } : {}),
|
||||
...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
|
||||
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
|
||||
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
|
||||
...(extra?.lastRuntimeEventAt !== undefined
|
||||
@@ -109,15 +110,14 @@ function toRuntimePayloadFromSession(
|
||||
};
|
||||
}
|
||||
|
||||
function readPersistedModelOptions(
|
||||
function readPersistedModelSelection(
|
||||
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
|
||||
): Record<string, unknown> | undefined {
|
||||
): ModelSelection | undefined {
|
||||
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
|
||||
return 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>;
|
||||
const raw = "modelSelection" in runtimePayload ? runtimePayload.modelSelection : undefined;
|
||||
return Schema.is(ModelSelection)(raw) ? raw : undefined;
|
||||
}
|
||||
|
||||
function readPersistedProviderOptions(
|
||||
@@ -172,7 +172,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
session: ProviderSession,
|
||||
threadId: ThreadId,
|
||||
extra?: {
|
||||
readonly modelOptions?: unknown;
|
||||
readonly modelSelection?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
@@ -238,14 +238,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
|
||||
const persistedModelOptions = readPersistedModelOptions(input.binding.runtimePayload);
|
||||
const persistedModelSelection = readPersistedModelSelection(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 } : {}),
|
||||
...(persistedModelOptions ? { modelOptions: persistedModelOptions } : {}),
|
||||
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
|
||||
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
|
||||
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
|
||||
runtimeMode: input.binding.runtimeMode ?? "full-access",
|
||||
@@ -328,7 +328,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
}
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelOptions: input.modelOptions,
|
||||
modelSelection: input.modelSelection,
|
||||
providerOptions: input.providerOptions,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
@@ -336,7 +336,9 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
runtimeMode: input.runtimeMode,
|
||||
hasResumeCursor: session.resumeCursor !== undefined,
|
||||
hasCwd: typeof input.cwd === "string" && input.cwd.trim().length > 0,
|
||||
hasModel: typeof input.model === "string" && input.model.trim().length > 0,
|
||||
hasModel:
|
||||
typeof input.modelSelection?.model === "string" &&
|
||||
input.modelSelection.model.trim().length > 0,
|
||||
});
|
||||
|
||||
return session;
|
||||
@@ -372,6 +374,7 @@ 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(),
|
||||
@@ -379,7 +382,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
});
|
||||
yield* analytics.record("provider.turn.sent", {
|
||||
provider: routed.adapter.provider,
|
||||
model: input.model,
|
||||
model: input.modelSelection?.model,
|
||||
interactionMode: input.interactionMode,
|
||||
attachmentCount: input.attachments.length,
|
||||
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
|
||||
|
||||
@@ -30,7 +30,7 @@ import { KeybindingsLive } from "./keybindings";
|
||||
import { GitManagerLive } from "./git/Layers/GitManager";
|
||||
import { GitCoreLive } from "./git/Layers/GitCore";
|
||||
import { GitHubCliLive } from "./git/Layers/GitHubCli";
|
||||
import { CodexTextGenerationLive } from "./git/Layers/CodexTextGeneration";
|
||||
import { RoutingTextGenerationLive } from "./git/Layers/RoutingTextGeneration";
|
||||
import { PtyAdapter } from "./terminal/Services/PTY";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
|
||||
@@ -85,7 +85,7 @@ export function makeServerProviderLayer(): Layer.Layer<
|
||||
}
|
||||
|
||||
export function makeServerRuntimeServicesLayer() {
|
||||
const textGenerationLayer = CodexTextGenerationLive;
|
||||
const textGenerationLayer = RoutingTextGenerationLive;
|
||||
const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(GitCoreLive));
|
||||
|
||||
const orchestrationLayer = OrchestrationEngineLive.pipe(
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
/**
|
||||
* 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);
|
||||
@@ -469,6 +469,89 @@ 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());
|
||||
|
||||
@@ -254,6 +254,180 @@ 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, "_");
|
||||
}
|
||||
@@ -378,6 +552,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history,
|
||||
pendingHistoryControlSequence: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -407,10 +582,12 @@ 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;
|
||||
@@ -469,6 +646,7 @@ 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({
|
||||
@@ -497,6 +675,7 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
status: "starting",
|
||||
pid: null,
|
||||
history: "",
|
||||
pendingHistoryControlSequence: "",
|
||||
exitCode: null,
|
||||
exitSignal: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
@@ -520,6 +699,7 @@ 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);
|
||||
@@ -694,9 +874,16 @@ export class TerminalManagerRuntime extends EventEmitter<TerminalManagerEvents>
|
||||
}
|
||||
|
||||
private onProcessData(session: TerminalSessionState, data: string): void {
|
||||
session.history = capHistory(`${session.history}${data}`, this.historyLineLimit);
|
||||
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.updatedAt = new Date().toISOString();
|
||||
this.queuePersist(session.threadId, session.terminalId, session.history);
|
||||
this.emitEvent({
|
||||
type: "output",
|
||||
threadId: session.threadId,
|
||||
@@ -713,6 +900,7 @@ 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();
|
||||
@@ -736,6 +924,7 @@ 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();
|
||||
|
||||
@@ -32,6 +32,7 @@ export interface TerminalSessionState {
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
|
||||
@@ -53,6 +53,7 @@ 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);
|
||||
@@ -545,6 +546,7 @@ 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),
|
||||
@@ -703,13 +705,19 @@ describe("WebSocket Server", () => {
|
||||
id: string;
|
||||
workspaceRoot: string;
|
||||
title: string;
|
||||
defaultModel: string | null;
|
||||
defaultModelSelection: {
|
||||
provider: string;
|
||||
model: string;
|
||||
} | null;
|
||||
}>;
|
||||
threads: Array<{
|
||||
id: string;
|
||||
projectId: string;
|
||||
title: string;
|
||||
model: string;
|
||||
modelSelection: {
|
||||
provider: string;
|
||||
model: string;
|
||||
};
|
||||
branch: string | null;
|
||||
worktreePath: string | null;
|
||||
}>;
|
||||
@@ -725,7 +733,10 @@ describe("WebSocket Server", () => {
|
||||
id: bootstrapProjectId,
|
||||
workspaceRoot: "/test/bootstrap-workspace",
|
||||
title: "bootstrap-workspace",
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
}),
|
||||
]),
|
||||
);
|
||||
@@ -735,7 +746,10 @@ describe("WebSocket Server", () => {
|
||||
id: bootstrapThreadId,
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
}),
|
||||
@@ -1192,7 +1206,10 @@ describe("WebSocket Server", () => {
|
||||
projectId: "project-diff",
|
||||
title: "Diff Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
expect(createProjectResponse.error).toBeUndefined();
|
||||
@@ -1202,7 +1219,10 @@ describe("WebSocket Server", () => {
|
||||
threadId: "thread-diff",
|
||||
projectId: "project-diff",
|
||||
title: "Diff Thread",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -1270,7 +1290,10 @@ describe("WebSocket Server", () => {
|
||||
projectId: "project-1",
|
||||
title: "WS Project",
|
||||
workspaceRoot,
|
||||
defaultModel: "gpt-5-codex",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
createdAt,
|
||||
});
|
||||
expect(createProjectResponse.error).toBeUndefined();
|
||||
@@ -1280,7 +1303,10 @@ describe("WebSocket Server", () => {
|
||||
threadId: "thread-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread 1",
|
||||
model: "gpt-5-codex",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
@@ -1811,15 +1837,106 @@ 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({
|
||||
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",
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
action: "commit",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
});
|
||||
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 () => {
|
||||
|
||||
@@ -49,6 +49,7 @@ 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";
|
||||
@@ -216,6 +217,7 @@ export type ServerRuntimeServices =
|
||||
| GitCore
|
||||
| TerminalManager
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
|
||||
@@ -253,6 +255,7 @@ 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;
|
||||
@@ -295,6 +298,11 @@ 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;
|
||||
@@ -618,6 +626,14 @@ 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;
|
||||
|
||||
@@ -631,25 +647,31 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
(project) => project.workspaceRoot === cwd && project.deletedAt === null,
|
||||
);
|
||||
let bootstrapProjectId: ProjectId;
|
||||
let bootstrapProjectDefaultModel: string;
|
||||
let bootstrapProjectDefaultModelSelection;
|
||||
|
||||
if (!existingProject) {
|
||||
const createdAt = new Date().toISOString();
|
||||
bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
|
||||
const bootstrapProjectTitle = path.basename(cwd) || "project";
|
||||
bootstrapProjectDefaultModel = "gpt-5-codex";
|
||||
bootstrapProjectDefaultModelSelection = {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.makeUnsafe(crypto.randomUUID()),
|
||||
projectId: bootstrapProjectId,
|
||||
title: bootstrapProjectTitle,
|
||||
workspaceRoot: cwd,
|
||||
defaultModel: bootstrapProjectDefaultModel,
|
||||
defaultModelSelection: bootstrapProjectDefaultModelSelection,
|
||||
createdAt,
|
||||
});
|
||||
} else {
|
||||
bootstrapProjectId = existingProject.id;
|
||||
bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
|
||||
bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
|
||||
provider: "codex" as const,
|
||||
model: "gpt-5-codex",
|
||||
};
|
||||
}
|
||||
|
||||
const existingThread = snapshot.threads.find(
|
||||
@@ -664,7 +686,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
threadId,
|
||||
projectId: bootstrapProjectId,
|
||||
title: "New thread",
|
||||
model: bootstrapProjectDefaultModel,
|
||||
modelSelection: bootstrapProjectDefaultModelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "full-access",
|
||||
branch: null,
|
||||
@@ -704,7 +726,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
|
||||
);
|
||||
|
||||
const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
|
||||
const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) {
|
||||
switch (request.body._tag) {
|
||||
case ORCHESTRATION_WS_METHODS.getSnapshot:
|
||||
return yield* projectionReadModelQuery.getSnapshot();
|
||||
@@ -793,7 +815,13 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
|
||||
case WS_METHODS.gitRunStackedAction: {
|
||||
const body = stripRequestTag(request.body);
|
||||
return yield* gitManager.runStackedAction(body);
|
||||
return yield* gitManager.runStackedAction(body, {
|
||||
actionId: body.actionId,
|
||||
progressReporter: {
|
||||
publish: (event) =>
|
||||
pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
case WS_METHODS.gitResolvePullRequest: {
|
||||
@@ -866,8 +894,9 @@ 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,
|
||||
@@ -875,7 +904,9 @@ 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);
|
||||
@@ -883,6 +914,15 @@ 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({
|
||||
@@ -915,7 +955,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
});
|
||||
}
|
||||
|
||||
const result = yield* Effect.exit(routeRequest(request.success));
|
||||
const result = yield* Effect.exit(routeRequest(ws, request.success));
|
||||
if (Exit.isFailure(result)) {
|
||||
return yield* sendWsResponse({
|
||||
id: request.success.id,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/web",
|
||||
"version": "0.0.13",
|
||||
"version": "0.0.14",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
@@ -19,6 +19,7 @@
|
||||
"@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:*",
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { Schema } from "effect";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
AppSettingsSchema,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
} from "./appSettings";
|
||||
import {
|
||||
getAppModelOptions,
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
@@ -12,8 +14,9 @@ import {
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
normalizeCustomModelSlugs,
|
||||
patchCustomModels,
|
||||
resolveAppModelSelectionState,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
} from "./modelSelection";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
@@ -110,6 +113,16 @@ 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"]);
|
||||
@@ -197,26 +210,57 @@ describe("provider-indexed custom model settings", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("AppSettingsSchema", () => {
|
||||
it("fills decoding defaults for persisted settings that predate newer keys", () => {
|
||||
const decode = Schema.decodeSync(Schema.fromJsonString(AppSettingsSchema));
|
||||
|
||||
describe("resolveAppModelSelectionState", () => {
|
||||
it("falls back to the default git-writing codex selection", () => {
|
||||
expect(
|
||||
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: [],
|
||||
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,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
+35
-233
@@ -1,248 +1,50 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
import { TrimmedNonEmptyString, type ProviderKind } from "@t3tools/contracts";
|
||||
/**
|
||||
* 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 {
|
||||
getDefaultModel,
|
||||
getModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveSelectableModel,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useLocalStorage } from "./hooks/useLocalStorage";
|
||||
import { EnvMode } from "./components/BranchToolbar.logic";
|
||||
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";
|
||||
|
||||
const APP_SETTINGS_STORAGE_KEY = "t3code:app-settings:v1";
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
// ── Re-exports for downstream type consumers ─────────────────────────
|
||||
|
||||
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
|
||||
export type TimestampFormat = typeof TimestampFormat.Type;
|
||||
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
||||
type CustomModelSettingsKey = "customCodexModels" | "customClaudeModels";
|
||||
export type ProviderCustomModelConfig = {
|
||||
provider: ProviderKind;
|
||||
settingsKey: CustomModelSettingsKey;
|
||||
defaultSettingsKey: CustomModelSettingsKey;
|
||||
title: string;
|
||||
description: string;
|
||||
placeholder: string;
|
||||
example: string;
|
||||
export type { TimestampFormat, SidebarProjectSortOrder, SidebarThreadSortOrder };
|
||||
export {
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
};
|
||||
export type { UnifiedSettings };
|
||||
|
||||
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)),
|
||||
};
|
||||
// ── 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;
|
||||
}
|
||||
|
||||
const DEFAULT_APP_SETTINGS = AppSettingsSchema.makeUnsafe({});
|
||||
const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConfig> = {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
settingsKey: "customCodexModels",
|
||||
defaultSettingsKey: "customCodexModels",
|
||||
title: "Codex",
|
||||
description: "Save additional Codex model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-codex-model-slug",
|
||||
example: "gpt-6.7-codex-ultra-preview",
|
||||
},
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
settingsKey: "customClaudeModels",
|
||||
defaultSettingsKey: "customClaudeModels",
|
||||
title: "Claude",
|
||||
description: "Save additional Claude model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-claude-model-slug",
|
||||
example: "claude-sonnet-5-0",
|
||||
},
|
||||
};
|
||||
export const MODEL_PROVIDER_SETTINGS = Object.values(PROVIDER_CUSTOM_MODEL_CONFIG);
|
||||
|
||||
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 getCustomModelsForProvider(
|
||||
settings: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return settings[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey];
|
||||
}
|
||||
|
||||
export function getDefaultCustomModelsForProvider(
|
||||
defaults: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return defaults[PROVIDER_CUSTOM_MODEL_CONFIG[provider].defaultSettingsKey];
|
||||
}
|
||||
|
||||
export function patchCustomModels(
|
||||
provider: ProviderKind,
|
||||
models: string[],
|
||||
): Partial<Pick<AppSettings, CustomModelSettingsKey>> {
|
||||
return {
|
||||
[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey]: models,
|
||||
};
|
||||
}
|
||||
|
||||
export function getCustomModelsByProvider(
|
||||
settings: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
): Record<ProviderKind, readonly string[]> {
|
||||
return {
|
||||
codex: getCustomModelsForProvider(settings, "codex"),
|
||||
claudeAgent: getCustomModelsForProvider(settings, "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));
|
||||
const trimmedSelectedModel = selectedModel?.trim().toLowerCase();
|
||||
|
||||
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);
|
||||
const selectedModelMatchesExistingName =
|
||||
typeof trimmedSelectedModel === "string" &&
|
||||
options.some((option) => option.name.toLowerCase() === trimmedSelectedModel);
|
||||
if (
|
||||
normalizedSelectedModel &&
|
||||
!seen.has(normalizedSelectedModel) &&
|
||||
!selectedModelMatchesExistingName
|
||||
) {
|
||||
options.push({
|
||||
slug: normalizedSelectedModel,
|
||||
name: normalizedSelectedModel,
|
||||
isCustom: true,
|
||||
});
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
export function resolveAppModelSelection(
|
||||
provider: ProviderKind,
|
||||
customModels: Record<ProviderKind, readonly string[]>,
|
||||
selectedModel: string | null | undefined,
|
||||
): string {
|
||||
const customModelsForProvider = customModels[provider];
|
||||
const options = getAppModelOptions(provider, customModelsForProvider, selectedModel);
|
||||
return resolveSelectableModel(provider, selectedModel, options) ?? getDefaultModel(provider);
|
||||
}
|
||||
|
||||
export function getCustomModelOptionsByProvider(
|
||||
settings: Pick<AppSettings, CustomModelSettingsKey>,
|
||||
): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
const customModelsByProvider = getCustomModelsByProvider(settings);
|
||||
return {
|
||||
codex: getAppModelOptions("codex", customModelsByProvider.codex),
|
||||
claudeAgent: getAppModelOptions("claudeAgent", customModelsByProvider.claudeAgent),
|
||||
};
|
||||
}
|
||||
// ── Backward-compat hook ─────────────────────────────────────────────
|
||||
|
||||
export function useAppSettings() {
|
||||
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]);
|
||||
const settings = useSettings();
|
||||
const { updateSettings, resetSettings, defaults } = useUpdateSettings();
|
||||
|
||||
return {
|
||||
settings,
|
||||
updateSettings,
|
||||
updateSettings: (patch: Partial<AppSettings>) => updateSettings(patch),
|
||||
resetSettings,
|
||||
defaults: DEFAULT_APP_SETTINGS,
|
||||
defaults,
|
||||
} as const;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* Client-only settings - persisted in localStorage.
|
||||
*
|
||||
* These settings affect only the frontend UX and never need to be read by
|
||||
* the server. Server-authoritative settings live in `ServerSettings`
|
||||
* (defined in `@t3tools/contracts/server`).
|
||||
*/
|
||||
import { Option, Schema } from "effect";
|
||||
|
||||
export const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||
|
||||
export const TimestampFormat = Schema.Literals(["locale", "12-hour", "24-hour"]);
|
||||
export type TimestampFormat = typeof TimestampFormat.Type;
|
||||
export const DEFAULT_TIMESTAMP_FORMAT: TimestampFormat = "locale";
|
||||
|
||||
export const SidebarProjectSortOrder = Schema.Literals(["updated_at", "created_at", "manual"]);
|
||||
export type SidebarProjectSortOrder = typeof SidebarProjectSortOrder.Type;
|
||||
export const DEFAULT_SIDEBAR_PROJECT_SORT_ORDER: SidebarProjectSortOrder = "updated_at";
|
||||
|
||||
export const SidebarThreadSortOrder = Schema.Literals(["updated_at", "created_at"]);
|
||||
export type SidebarThreadSortOrder = typeof SidebarThreadSortOrder.Type;
|
||||
export const DEFAULT_SIDEBAR_THREAD_SORT_ORDER: SidebarThreadSortOrder = "updated_at";
|
||||
|
||||
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 const ClientSettingsSchema = Schema.Struct({
|
||||
confirmThreadDelete: Schema.Boolean.pipe(withDefaults(() => true)),
|
||||
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
|
||||
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
|
||||
withDefaults(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
|
||||
),
|
||||
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
|
||||
withDefaults(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
|
||||
),
|
||||
timestampFormat: TimestampFormat.pipe(withDefaults(() => DEFAULT_TIMESTAMP_FORMAT)),
|
||||
});
|
||||
export type ClientSettings = typeof ClientSettingsSchema.Type;
|
||||
|
||||
export const DEFAULT_CLIENT_SETTINGS: ClientSettings = ClientSettingsSchema.makeUnsafe({});
|
||||
@@ -24,6 +24,7 @@ import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import {
|
||||
INLINE_TERMINAL_CONTEXT_PLACEHOLDER,
|
||||
type TerminalContextDraft,
|
||||
removeInlineTerminalContextPlaceholder,
|
||||
} from "../lib/terminalContext";
|
||||
import { isMacPlatform } from "../lib/utils";
|
||||
import { getRouter } from "../router";
|
||||
@@ -89,6 +90,7 @@ interface UserRowMeasurement {
|
||||
}
|
||||
|
||||
interface MountedChatView {
|
||||
[Symbol.asyncDispose]: () => Promise<void>;
|
||||
cleanup: () => Promise<void>;
|
||||
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
|
||||
setViewport: (viewport: ViewportSpec) => Promise<void>;
|
||||
@@ -115,6 +117,15 @@ function createBaseServerConfig(): ServerConfig {
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
settings: {
|
||||
claude: { binaryPath: "" },
|
||||
codex: { binaryPath: "", homePath: "" },
|
||||
enableAssistantStreaming: false,
|
||||
defaultThreadEnvMode: "local" as const,
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -220,7 +231,10 @@ function createSnapshotForTargetUser(options: {
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
@@ -232,7 +246,10 @@ function createSnapshotForTargetUser(options: {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Browser test thread",
|
||||
model: "gpt-5",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: "main",
|
||||
@@ -286,7 +303,10 @@ function addThreadToSnapshot(
|
||||
id: threadId,
|
||||
projectId: PROJECT_ID,
|
||||
title: "New thread",
|
||||
model: "gpt-5",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: "main",
|
||||
@@ -324,6 +344,18 @@ function createDraftOnlySnapshot(): OrchestrationReadModel {
|
||||
};
|
||||
}
|
||||
|
||||
function withProjectScripts(
|
||||
snapshot: OrchestrationReadModel,
|
||||
scripts: OrchestrationReadModel["projects"][number]["scripts"],
|
||||
): OrchestrationReadModel {
|
||||
return {
|
||||
...snapshot,
|
||||
projects: snapshot.projects.map((project) =>
|
||||
project.id === PROJECT_ID ? { ...project, scripts: Array.from(scripts) } : project,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-plan-target" as MessageId,
|
||||
@@ -575,6 +607,58 @@ async function waitForInteractionModeButton(
|
||||
);
|
||||
}
|
||||
|
||||
async function waitForServerConfigToApply(): Promise<void> {
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(wsRequests.some((request) => request._tag === WS_METHODS.serverGetConfig)).toBe(true);
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
await waitForLayout();
|
||||
}
|
||||
|
||||
function dispatchChatNewShortcut(): void {
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async function triggerChatNewShortcutUntilPath(
|
||||
router: ReturnType<typeof getRouter>,
|
||||
predicate: (pathname: string) => boolean,
|
||||
errorMessage: string,
|
||||
): Promise<string> {
|
||||
let pathname = router.state.location.pathname;
|
||||
const deadline = Date.now() + 8_000;
|
||||
while (Date.now() < deadline) {
|
||||
dispatchChatNewShortcut();
|
||||
await waitForLayout();
|
||||
pathname = router.state.location.pathname;
|
||||
if (predicate(pathname)) {
|
||||
return pathname;
|
||||
}
|
||||
}
|
||||
throw new Error(`${errorMessage} Last path: ${pathname}`);
|
||||
}
|
||||
|
||||
async function waitForNewThreadShortcutLabel(): Promise<void> {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
await newThreadButton.hover();
|
||||
const shortcutLabel = isMacPlatform(navigator.platform)
|
||||
? "New thread (⇧⌘O)"
|
||||
: "New thread (Ctrl+Shift+O)";
|
||||
await expect.element(page.getByText(shortcutLabel)).toBeInTheDocument();
|
||||
}
|
||||
|
||||
async function waitForImagesToLoad(scope: ParentNode): Promise<void> {
|
||||
const images = Array.from(scope.querySelectorAll("img"));
|
||||
if (images.length === 0) {
|
||||
@@ -691,11 +775,14 @@ async function mountChatView(options: {
|
||||
|
||||
await waitForLayout();
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
measureUserRow: async (targetMessageId: MessageId) => measureUserRow({ host, targetMessageId }),
|
||||
setViewport: async (viewport: ViewportSpec) => {
|
||||
await setViewport(viewport);
|
||||
@@ -752,8 +839,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
@@ -980,6 +1067,145 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("runs project scripts from local draft threads at the project cwd", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
|
||||
{
|
||||
id: "lint",
|
||||
name: "Lint",
|
||||
command: "bun run lint",
|
||||
icon: "lint",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
try {
|
||||
const runButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.title === "Run Lint",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Run Lint button.",
|
||||
);
|
||||
runButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.terminalOpen,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalOpen,
|
||||
threadId: THREAD_ID,
|
||||
cwd: "/repo/project",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
},
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const writeRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.terminalWrite,
|
||||
);
|
||||
expect(writeRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalWrite,
|
||||
threadId: THREAD_ID,
|
||||
data: "bun run lint\r",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("runs project scripts from worktree draft threads at the worktree cwd", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: "feature/draft",
|
||||
worktreePath: "/repo/worktrees/feature-draft",
|
||||
envMode: "worktree",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
|
||||
{
|
||||
id: "test",
|
||||
name: "Test",
|
||||
command: "bun run test",
|
||||
icon: "test",
|
||||
runOnWorktreeCreate: false,
|
||||
},
|
||||
]),
|
||||
});
|
||||
|
||||
try {
|
||||
const runButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.title === "Run Test",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Run Test button.",
|
||||
);
|
||||
runButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.terminalOpen,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalOpen,
|
||||
threadId: THREAD_ID,
|
||||
cwd: "/repo/worktrees/feature-draft",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktrees/feature-draft",
|
||||
},
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -1045,7 +1271,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps backspaced terminal context pills removed when a new one is added", async () => {
|
||||
it("keeps removed terminal context pills removed when a new one is added", async () => {
|
||||
const removedLabel = "Terminal 1 lines 1-2";
|
||||
const addedLabel = "Terminal 2 lines 9-10";
|
||||
useComposerDraftStore.getState().addTerminalContext(
|
||||
@@ -1075,15 +1301,11 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
composerEditor.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "Backspace",
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
const store = useComposerDraftStore.getState();
|
||||
const currentPrompt = store.draftsByThreadId[THREAD_ID]?.prompt ?? "";
|
||||
const nextPrompt = removeInlineTerminalContextPlaceholder(currentPrompt, 0);
|
||||
store.setPrompt(THREAD_ID, nextPrompt.prompt);
|
||||
store.removeTerminalContext(THREAD_ID, "ctx-removed");
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
@@ -1283,13 +1505,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1314,13 +1540,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
provider: "codex",
|
||||
modelOptions: {
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
@@ -1329,13 +1558,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("hydrates the provider alongside a sticky claude model", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "claude-opus-4-6",
|
||||
stickyModelOptions: {
|
||||
stickyModelSelectionByProvider: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "claudeAgent",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1360,16 +1593,18 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
modelSelectionByProvider: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "claudeAgent",
|
||||
});
|
||||
await expect.element(page.getByText("Claude Opus 4.6")).toBeInTheDocument();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
@@ -1405,13 +1640,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("prefers draft state over sticky composer settings and defaults", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1436,17 +1675,22 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const threadId = threadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
model: "gpt-5.3-codex",
|
||||
modelOptions: {
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().setModel(threadId, "gpt-5.4");
|
||||
useComposerDraftStore.getState().setModelOptions(threadId, {
|
||||
codex: {
|
||||
useComposerDraftStore.getState().setModelSelection(threadId, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
@@ -1460,13 +1704,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
"New-thread should reuse the existing project draft thread.",
|
||||
);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
model: "gpt-5.4",
|
||||
modelOptions: {
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
@@ -1505,19 +1753,12 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
try {
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitForURL(
|
||||
await waitForNewThreadShortcutLabel();
|
||||
await waitForServerConfigToApply();
|
||||
const composerEditor = await waitForComposerEditor();
|
||||
composerEditor.focus();
|
||||
await waitForLayout();
|
||||
await triggerChatNewShortcutUntilPath(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path),
|
||||
"Route should have changed to a new draft thread UUID from the shortcut.",
|
||||
@@ -1526,7 +1767,6 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("creates a fresh draft after the previous draft thread is promoted", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -1561,6 +1801,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
try {
|
||||
const newThreadButton = page.getByTestId("new-thread-button");
|
||||
await expect.element(newThreadButton).toBeInTheDocument();
|
||||
await waitForNewThreadShortcutLabel();
|
||||
await waitForServerConfigToApply();
|
||||
await newThreadButton.click();
|
||||
|
||||
const promotedThreadPath = await waitForURL(
|
||||
@@ -1574,19 +1816,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
|
||||
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
|
||||
|
||||
const useMetaForMod = isMacPlatform(navigator.platform);
|
||||
window.dispatchEvent(
|
||||
new KeyboardEvent("keydown", {
|
||||
key: "o",
|
||||
shiftKey: true,
|
||||
metaKey: useMetaForMod,
|
||||
ctrlKey: !useMetaForMod,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
}),
|
||||
);
|
||||
|
||||
const freshThreadPath = await waitForURL(
|
||||
const freshThreadPath = await triggerChatNewShortcutUntilPath(
|
||||
mounted.router,
|
||||
(path) => UUID_ROUTE_RE.test(path) && path !== promotedThreadPath,
|
||||
"Shortcut should create a fresh draft instead of reusing the promoted thread.",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ProjectId, type ThreadId } from "@t3tools/contracts";
|
||||
import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts";
|
||||
import { type ChatMessage, type Thread } from "../types";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
|
||||
@@ -17,7 +17,7 @@ export const LastInvokedScriptByProjectSchema = Schema.Record(ProjectId, Schema.
|
||||
export function buildLocalDraftThread(
|
||||
threadId: ThreadId,
|
||||
draftThread: DraftThreadState,
|
||||
fallbackModel: string,
|
||||
fallbackModelSelection: ModelSelection,
|
||||
error: string | null,
|
||||
): Thread {
|
||||
return {
|
||||
@@ -25,7 +25,7 @@ export function buildLocalDraftThread(
|
||||
codexThreadId: null,
|
||||
projectId: draftThread.projectId,
|
||||
title: "New thread",
|
||||
model: fallbackModel,
|
||||
modelSelection: fallbackModelSelection,
|
||||
runtimeMode: draftThread.runtimeMode,
|
||||
interactionMode: draftThread.interactionMode,
|
||||
session: null,
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ClaudeCodeEffort,
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
@@ -23,9 +24,8 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultModel,
|
||||
getModelCapabilities,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
@@ -112,6 +112,7 @@ import { type NewProjectScriptInput } from "./ProjectScriptsControl";
|
||||
import {
|
||||
commandForProjectScript,
|
||||
nextProjectScriptId,
|
||||
projectScriptCwd,
|
||||
projectScriptRuntimeEnv,
|
||||
projectScriptIdFromCommand,
|
||||
setupProjectScript,
|
||||
@@ -119,18 +120,19 @@ import {
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import {
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
resolveAppModelSelection,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
} from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
type PersistedComposerImageAttachment,
|
||||
useComposerDraftStore,
|
||||
useEffectiveComposerModelState,
|
||||
useComposerThreadDraft,
|
||||
} from "../composerDraftStore";
|
||||
import {
|
||||
@@ -141,12 +143,14 @@ import {
|
||||
type TerminalContextDraft,
|
||||
type TerminalContextSelection,
|
||||
} from "../lib/terminalContext";
|
||||
import { deriveLatestContextWindowSnapshot } from "../lib/contextWindow";
|
||||
import { shouldUseCompactComposerFooter } from "./composerFooterLayout";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
|
||||
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
|
||||
import { MessagesTimeline } from "./chat/MessagesTimeline";
|
||||
import { ChatHeader } from "./chat/ChatHeader";
|
||||
import { ContextWindowMeter } from "./chat/ContextWindowMeter";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/ExpandedImagePreview";
|
||||
import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker";
|
||||
import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu";
|
||||
@@ -192,10 +196,12 @@ const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnsw
|
||||
|
||||
function formatOutgoingPrompt(params: {
|
||||
provider: ProviderKind;
|
||||
model: string | null;
|
||||
effort: string | null;
|
||||
text: string;
|
||||
}): string {
|
||||
if (params.provider === "claudeAgent" && params.effort === "ultrathink") {
|
||||
const caps = getModelCapabilities(params.provider, params.model);
|
||||
if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) {
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
}
|
||||
return params.text;
|
||||
@@ -244,7 +250,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
const { settings } = useAppSettings();
|
||||
const setStickyComposerModel = useComposerDraftStore((store) => store.setStickyModel);
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
(store) => store.setStickyModelSelection,
|
||||
);
|
||||
const timestampFormat = settings.timestampFormat;
|
||||
const navigate = useNavigate();
|
||||
const rawSearch = useSearch({
|
||||
@@ -269,8 +277,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
|
||||
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const setComposerDraftProvider = useComposerDraftStore((store) => store.setProvider);
|
||||
const setComposerDraftModel = useComposerDraftStore((store) => store.setModel);
|
||||
const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);
|
||||
const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);
|
||||
const setComposerDraftInteractionMode = useComposerDraftStore(
|
||||
(store) => store.setInteractionMode,
|
||||
@@ -463,11 +470,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
? buildLocalDraftThread(
|
||||
threadId,
|
||||
draftThread,
|
||||
fallbackDraftProject?.model ?? DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
fallbackDraftProject?.defaultModelSelection ?? {
|
||||
provider: "codex",
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
localDraftError,
|
||||
)
|
||||
: undefined,
|
||||
[draftThread, fallbackDraftProject?.model, localDraftError, threadId],
|
||||
[draftThread, fallbackDraftProject?.defaultModelSelection, localDraftError, threadId],
|
||||
);
|
||||
const activeThread = serverThread ?? localDraftThread;
|
||||
const runtimeMode =
|
||||
@@ -480,6 +490,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const diffOpen = rawSearch.diff === "1";
|
||||
const activeThreadId = activeThread?.id ?? null;
|
||||
const activeLatestTurn = activeThread?.latestTurn ?? null;
|
||||
const activeContextWindow = useMemo(
|
||||
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
|
||||
[activeThread?.activities],
|
||||
);
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
|
||||
|
||||
@@ -582,7 +596,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
|
||||
const sessionProvider = activeThread?.session?.provider ?? null;
|
||||
const selectedProviderByThreadId = composerDraft.provider;
|
||||
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
|
||||
const threadProvider =
|
||||
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
|
||||
const hasThreadStarted = Boolean(
|
||||
activeThread &&
|
||||
(activeThread.latestTurn !== null ||
|
||||
@@ -590,49 +606,42 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThread.session !== null),
|
||||
);
|
||||
const lockedProvider: ProviderKind | null = hasThreadStarted
|
||||
? (sessionProvider ?? selectedProviderByThreadId ?? null)
|
||||
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
const selectedProvider: ProviderKind = lockedProvider ?? selectedProviderByThreadId ?? "codex";
|
||||
const baseThreadModel = resolveModelSlugForProvider(
|
||||
selectedProvider,
|
||||
activeThread?.model ?? activeProject?.model ?? getDefaultModel(selectedProvider),
|
||||
);
|
||||
const selectedProvider: ProviderKind =
|
||||
lockedProvider ?? selectedProviderByThreadId ?? threadProvider ?? "codex";
|
||||
const customModelsByProvider = useMemo(() => getCustomModelsByProvider(settings), [settings]);
|
||||
const selectedModel = useMemo(() => {
|
||||
const draftModel = composerDraft.model;
|
||||
if (!draftModel) {
|
||||
return baseThreadModel;
|
||||
}
|
||||
return resolveAppModelSelection(selectedProvider, customModelsByProvider, draftModel);
|
||||
}, [baseThreadModel, composerDraft.model, customModelsByProvider, selectedProvider]);
|
||||
const draftModelOptions = composerDraft.modelOptions;
|
||||
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadId,
|
||||
selectedProvider,
|
||||
threadModelSelection: activeThread?.modelSelection,
|
||||
projectModelSelection: activeProject?.defaultModelSelection,
|
||||
customModelsByProvider,
|
||||
});
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
prompt,
|
||||
modelOptions: draftModelOptions,
|
||||
modelOptions: composerModelOptions,
|
||||
}),
|
||||
[draftModelOptions, prompt, selectedModel, selectedProvider],
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider],
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
const providerOptionsForDispatch = useMemo(() => {
|
||||
if (!settings.codexBinaryPath && !settings.codexHomePath) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
codex: {
|
||||
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
|
||||
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
|
||||
},
|
||||
};
|
||||
}, [settings.codexBinaryPath, settings.codexHomePath]);
|
||||
const selectedModelSelection = useMemo<ModelSelection>(
|
||||
() => ({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
...(selectedModelOptionsForDispatch ? { options: selectedModelOptionsForDispatch } : {}),
|
||||
}),
|
||||
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
|
||||
);
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => getCustomModelOptionsByProvider(settings),
|
||||
[settings],
|
||||
() => getCustomModelOptionsByProvider(settings, selectedProvider, selectedModel),
|
||||
[settings, selectedProvider, selectedModel],
|
||||
);
|
||||
const selectedModelForPickerWithCustomFallback = useMemo(() => {
|
||||
const currentOptions = modelOptionsByProvider[selectedProvider];
|
||||
@@ -1003,7 +1012,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
latestTurnSettled,
|
||||
timelineEntries,
|
||||
]);
|
||||
const gitCwd = activeThread?.worktreePath ?? activeProject?.cwd ?? null;
|
||||
const gitCwd = activeProject
|
||||
? projectScriptCwd({
|
||||
project: { cwd: activeProject.cwd },
|
||||
worktreePath: activeThread?.worktreePath ?? null,
|
||||
})
|
||||
: null;
|
||||
const composerTriggerKind = composerTrigger?.kind ?? null;
|
||||
const pathTriggerQuery = composerTrigger?.kind === "path" ? composerTrigger.query : "";
|
||||
const isPathTrigger = composerTriggerKind === "path";
|
||||
@@ -1122,6 +1136,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}, [activeProjectCwd, activeThreadWorktreePath]);
|
||||
// Default true while loading to avoid toolbar flicker.
|
||||
const isGitRepo = branchesQuery.data?.isRepo ?? true;
|
||||
const terminalToggleShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.toggle"),
|
||||
[keybindings],
|
||||
);
|
||||
const splitTerminalShortcutLabel = useMemo(
|
||||
() => shortcutLabelForCommand(keybindings, "terminal.split"),
|
||||
[keybindings],
|
||||
@@ -1312,12 +1330,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
worktreePath?: string | null;
|
||||
preferNewTerminal?: boolean;
|
||||
rememberAsLastInvoked?: boolean;
|
||||
allowLocalDraftThread?: boolean;
|
||||
},
|
||||
) => {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThreadId || !activeProject || !activeThread) return;
|
||||
if (!isServerThread && !options?.allowLocalDraftThread) return;
|
||||
if (options?.rememberAsLastInvoked !== false) {
|
||||
setLastInvokedScriptByProjectId((current) => {
|
||||
if (current[activeProject.id] === script.id) return current;
|
||||
@@ -1386,7 +1402,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThread,
|
||||
activeThreadId,
|
||||
gitCwd,
|
||||
isServerThread,
|
||||
setTerminalOpen,
|
||||
setThreadError,
|
||||
storeNewTerminal,
|
||||
@@ -1590,7 +1605,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
async (input: {
|
||||
threadId: ThreadId;
|
||||
createdAt: string;
|
||||
model?: string;
|
||||
modelSelection?: ModelSelection;
|
||||
runtimeMode: RuntimeMode;
|
||||
interactionMode: ProviderInteractionMode;
|
||||
}) => {
|
||||
@@ -1602,12 +1617,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (input.model !== undefined && input.model !== serverThread.model) {
|
||||
if (
|
||||
input.modelSelection !== undefined &&
|
||||
(input.modelSelection.model !== serverThread.modelSelection.model ||
|
||||
input.modelSelection.provider !== serverThread.modelSelection.provider ||
|
||||
JSON.stringify(input.modelSelection.options ?? null) !==
|
||||
JSON.stringify(serverThread.modelSelection.options ?? null))
|
||||
) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.meta.update",
|
||||
commandId: newCommandId(),
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
modelSelection: input.modelSelection,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2437,6 +2458,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
effort: selectedPromptEffort,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
@@ -2538,8 +2560,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
}
|
||||
const title = truncateTitle(titleSeed);
|
||||
let threadCreateModel: ModelSlug =
|
||||
selectedModel || (activeProject.model as ModelSlug) || DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
const threadCreateModelSelection: ModelSelection = {
|
||||
provider: selectedProvider,
|
||||
model:
|
||||
selectedModel ||
|
||||
activeProject.defaultModelSelection?.model ||
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
...(selectedModelSelection.options ? { options: selectedModelSelection.options } : {}),
|
||||
};
|
||||
|
||||
if (isLocalDraftThread) {
|
||||
await api.orchestration.dispatchCommand({
|
||||
@@ -2548,7 +2576,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadId: threadIdForSend,
|
||||
projectId: activeProject.id,
|
||||
title,
|
||||
model: threadCreateModel,
|
||||
modelSelection: threadCreateModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
branch: nextThreadBranch,
|
||||
@@ -2575,7 +2603,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
|
||||
worktreePath: nextThreadWorktreePath,
|
||||
rememberAsLastInvoked: false,
|
||||
allowLocalDraftThread: createdServerThreadForLocalDraft,
|
||||
};
|
||||
if (nextThreadWorktreePath) {
|
||||
setupScriptOptions.cwd = nextThreadWorktreePath;
|
||||
@@ -2598,7 +2625,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await persistThreadSettingsForNextTurn({
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
...(selectedModel ? { model: selectedModel } : {}),
|
||||
...(selectedModel ? { modelSelection: selectedModelSelection } : {}),
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
});
|
||||
@@ -2616,13 +2643,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
text: outgoingMessageText,
|
||||
attachments: turnAttachments,
|
||||
},
|
||||
model: selectedModel || undefined,
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
provider: selectedProvider,
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
modelSelection: selectedModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
createdAt: messageCreatedAt,
|
||||
@@ -2858,6 +2879,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const messageCreatedAt = new Date().toISOString();
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
effort: selectedPromptEffort,
|
||||
text: trimmed,
|
||||
});
|
||||
@@ -2882,7 +2904,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
await persistThreadSettingsForNextTurn({
|
||||
threadId: threadIdForSend,
|
||||
createdAt: messageCreatedAt,
|
||||
...(selectedModel ? { model: selectedModel } : {}),
|
||||
modelSelection: selectedModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
});
|
||||
@@ -2901,13 +2923,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
text: outgoingMessageText,
|
||||
attachments: [],
|
||||
},
|
||||
provider: selectedProvider,
|
||||
model: selectedModel || undefined,
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
modelSelection: selectedModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
...(nextInteractionMode === "default" && activeProposedPlan
|
||||
@@ -2952,13 +2968,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
selectedModelSelection,
|
||||
selectedProvider,
|
||||
setComposerDraftInteractionMode,
|
||||
setThreadError,
|
||||
settings.enableAssistantStreaming,
|
||||
selectedModel,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -2983,15 +2998,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
|
||||
const outgoingImplementationPrompt = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
effort: selectedPromptEffort,
|
||||
text: implementationPrompt,
|
||||
});
|
||||
const nextThreadTitle = truncateTitle(buildPlanImplementationThreadTitle(planMarkdown));
|
||||
const nextThreadModel: ModelSlug =
|
||||
selectedModel ||
|
||||
(activeThread.model as ModelSlug) ||
|
||||
(activeProject.model as ModelSlug) ||
|
||||
DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase("sending-turn");
|
||||
@@ -3007,7 +3019,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadId: nextThreadId,
|
||||
projectId: activeProject.id,
|
||||
title: nextThreadTitle,
|
||||
model: nextThreadModel,
|
||||
modelSelection: nextThreadModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
branch: activeThread.branch,
|
||||
@@ -3025,13 +3037,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
text: outgoingImplementationPrompt,
|
||||
attachments: [],
|
||||
},
|
||||
provider: selectedProvider,
|
||||
model: selectedModel || undefined,
|
||||
...(selectedModelOptionsForDispatch
|
||||
? { modelOptions: selectedModelOptionsForDispatch }
|
||||
: {}),
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
modelSelection: selectedModelSelection,
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
createdAt,
|
||||
@@ -3081,12 +3087,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModel,
|
||||
selectedModelOptionsForDispatch,
|
||||
providerOptionsForDispatch,
|
||||
selectedModelSelection,
|
||||
selectedProvider,
|
||||
settings.enableAssistantStreaming,
|
||||
syncServerReadModel,
|
||||
selectedModel,
|
||||
]);
|
||||
|
||||
const onProviderModelSelect = useCallback(
|
||||
@@ -3097,18 +3101,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const resolvedModel = resolveAppModelSelection(provider, customModelsByProvider, model);
|
||||
setComposerDraftProvider(activeThread.id, provider);
|
||||
setComposerDraftModel(activeThread.id, resolvedModel);
|
||||
setStickyComposerModel(resolvedModel);
|
||||
const nextModelSelection: ModelSelection = {
|
||||
provider,
|
||||
model: resolvedModel,
|
||||
};
|
||||
setComposerDraftModelSelection(activeThread.id, nextModelSelection);
|
||||
setStickyComposerModelSelection(nextModelSelection);
|
||||
scheduleComposerFocus();
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModel,
|
||||
setComposerDraftProvider,
|
||||
setStickyComposerModel,
|
||||
setComposerDraftModelSelection,
|
||||
setStickyComposerModelSelection,
|
||||
customModelsByProvider,
|
||||
],
|
||||
);
|
||||
@@ -3132,12 +3138,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
const providerTraitsPicker = renderProviderTraitsPicker({
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
});
|
||||
const onEnvModeChange = useCallback(
|
||||
@@ -3474,13 +3484,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
activeThreadTitle={activeThread.title}
|
||||
activeProjectName={activeProject?.name}
|
||||
isGitRepo={isGitRepo}
|
||||
openInCwd={activeThread.worktreePath ?? activeProject?.cwd ?? null}
|
||||
openInCwd={gitCwd}
|
||||
activeProjectScripts={activeProject?.scripts}
|
||||
preferredScriptId={
|
||||
activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null
|
||||
}
|
||||
keybindings={keybindings}
|
||||
availableEditors={availableEditors}
|
||||
terminalAvailable={activeProject !== undefined}
|
||||
terminalOpen={terminalState.terminalOpen}
|
||||
terminalToggleShortcutLabel={terminalToggleShortcutLabel}
|
||||
diffToggleShortcutLabel={diffPanelShortcutLabel}
|
||||
gitCwd={gitCwd}
|
||||
diffOpen={diffOpen}
|
||||
@@ -3490,6 +3503,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
onAddProjectScript={saveProjectScript}
|
||||
onUpdateProjectScript={updateProjectScript}
|
||||
onDeleteProjectScript={deleteProjectScript}
|
||||
onToggleTerminal={toggleTerminalVisibility}
|
||||
onToggleDiff={onToggleDiff}
|
||||
/>
|
||||
</header>
|
||||
@@ -3894,6 +3908,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
data-chat-composer-actions="right"
|
||||
className="flex shrink-0 items-center gap-2"
|
||||
>
|
||||
{activeContextWindow ? (
|
||||
<ContextWindowMeter usage={activeContextWindow} />
|
||||
) : null}
|
||||
{isPreparingWorktree ? (
|
||||
<span className="text-muted-foreground/70 text-xs">
|
||||
Preparing worktree...
|
||||
|
||||
@@ -3,7 +3,13 @@ import { FileDiff, type FileDiffMetadata, Virtualizer } from "@pierre/diffs/reac
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useNavigate, useParams, useSearch } from "@tanstack/react-router";
|
||||
import { ThreadId, type TurnId } from "@t3tools/contracts";
|
||||
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
Columns2Icon,
|
||||
Rows3Icon,
|
||||
TextWrapIcon,
|
||||
} from "lucide-react";
|
||||
import {
|
||||
type WheelEvent as ReactWheelEvent,
|
||||
useCallback,
|
||||
@@ -162,8 +168,10 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { settings } = useAppSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
const turnStripRef = useRef<HTMLDivElement>(null);
|
||||
const previousDiffOpenRef = useRef(false);
|
||||
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
|
||||
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
|
||||
const routeThreadId = useParams({
|
||||
@@ -171,6 +179,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
|
||||
});
|
||||
const diffSearch = useSearch({ strict: false, select: (search) => parseDiffRouteSearch(search) });
|
||||
const diffOpen = diffSearch.diff === "1";
|
||||
const activeThreadId = routeThreadId;
|
||||
const activeThread = useStore((store) =>
|
||||
activeThreadId ? store.threads.find((thread) => thread.id === activeThreadId) : undefined,
|
||||
@@ -293,6 +302,13 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
);
|
||||
}, [renderablePatch]);
|
||||
|
||||
useEffect(() => {
|
||||
if (diffOpen && !previousDiffOpenRef.current) {
|
||||
setDiffWordWrap(settings.diffWordWrap);
|
||||
}
|
||||
previousDiffOpenRef.current = diffOpen;
|
||||
}, [diffOpen, settings.diffWordWrap]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedFilePath || !patchViewportRef.current) {
|
||||
return;
|
||||
@@ -490,25 +506,39 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<ToggleGroup
|
||||
className="shrink-0 [-webkit-app-region:no-drag]"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
value={[diffRenderMode]}
|
||||
onValueChange={(value) => {
|
||||
const next = value[0];
|
||||
if (next === "stacked" || next === "split") {
|
||||
setDiffRenderMode(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
||||
<Rows3Icon className="size-3" />
|
||||
<div className="flex shrink-0 items-center gap-1 [-webkit-app-region:no-drag]">
|
||||
<ToggleGroup
|
||||
className="shrink-0"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
value={[diffRenderMode]}
|
||||
onValueChange={(value) => {
|
||||
const next = value[0];
|
||||
if (next === "stacked" || next === "split") {
|
||||
setDiffRenderMode(next);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Toggle aria-label="Stacked diff view" value="stacked">
|
||||
<Rows3Icon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle aria-label="Split diff view" value="split">
|
||||
<Columns2Icon className="size-3" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
<Toggle
|
||||
aria-label={diffWordWrap ? "Disable diff line wrapping" : "Enable diff line wrapping"}
|
||||
title={diffWordWrap ? "Disable line wrapping" : "Enable line wrapping"}
|
||||
variant="outline"
|
||||
size="xs"
|
||||
pressed={diffWordWrap}
|
||||
onPressedChange={(pressed) => {
|
||||
setDiffWordWrap(Boolean(pressed));
|
||||
}}
|
||||
>
|
||||
<TextWrapIcon className="size-3" />
|
||||
</Toggle>
|
||||
<Toggle aria-label="Split diff view" value="split">
|
||||
<Columns2Icon className="size-3" />
|
||||
</Toggle>
|
||||
</ToggleGroup>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -582,6 +612,7 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
options={{
|
||||
diffStyle: diffRenderMode === "split" ? "split" : "unified",
|
||||
lineDiffType: "none",
|
||||
overflow: diffWordWrap ? "wrap" : "scroll",
|
||||
theme: resolveDiffThemeName(resolvedTheme),
|
||||
themeType: resolvedTheme as DiffThemeType,
|
||||
unsafeCSS: DIFF_PANEL_UNSAFE_CSS,
|
||||
@@ -595,7 +626,14 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
<div className="h-full overflow-auto p-2">
|
||||
<div className="space-y-2">
|
||||
<p className="text-[11px] text-muted-foreground/75">{renderablePatch.reason}</p>
|
||||
<pre className="max-h-[72vh] overflow-auto rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90">
|
||||
<pre
|
||||
className={cn(
|
||||
"max-h-[72vh] rounded-md border border-border/70 bg-background/70 p-3 font-mono text-[11px] leading-relaxed text-muted-foreground/90",
|
||||
diffWordWrap
|
||||
? "overflow-auto whitespace-pre-wrap wrap-break-word"
|
||||
: "overflow-auto",
|
||||
)}
|
||||
>
|
||||
{renderablePatch.text}
|
||||
</pre>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import type { GitStackedAction, GitStatusResult, ThreadId } from "@t3tools/contracts";
|
||||
import type {
|
||||
GitActionProgressEvent,
|
||||
GitStackedAction,
|
||||
GitStatusResult,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { useIsMutating, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";
|
||||
import { ChevronDownIcon, CloudUploadIcon, GitCommitIcon, InfoIcon } from "lucide-react";
|
||||
import { GitHubIcon } from "./Icons";
|
||||
import {
|
||||
@@ -43,6 +48,7 @@ import {
|
||||
gitStatusQueryOptions,
|
||||
invalidateGitQueries,
|
||||
} from "~/lib/gitReactQuery";
|
||||
import { randomUUID } from "~/lib/utils";
|
||||
import { resolvePathLinkTarget } from "~/terminal-links";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
|
||||
@@ -63,6 +69,50 @@ interface PendingDefaultBranchAction {
|
||||
|
||||
type GitActionToastId = ReturnType<typeof toastManager.add>;
|
||||
|
||||
interface ActiveGitActionProgress {
|
||||
toastId: GitActionToastId;
|
||||
actionId: string;
|
||||
title: string;
|
||||
phaseStartedAtMs: number | null;
|
||||
hookStartedAtMs: number | null;
|
||||
hookName: string | null;
|
||||
lastOutputLine: string | null;
|
||||
currentPhaseLabel: string | null;
|
||||
}
|
||||
|
||||
interface RunGitActionWithToastInput {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
filePaths?: string[];
|
||||
}
|
||||
|
||||
function formatElapsedDescription(startedAtMs: number | null): string | undefined {
|
||||
if (startedAtMs === null) {
|
||||
return undefined;
|
||||
}
|
||||
const elapsedSeconds = Math.max(0, Math.floor((Date.now() - startedAtMs) / 1000));
|
||||
if (elapsedSeconds < 60) {
|
||||
return `Running for ${elapsedSeconds}s`;
|
||||
}
|
||||
const minutes = Math.floor(elapsedSeconds / 60);
|
||||
const seconds = elapsedSeconds % 60;
|
||||
return `Running for ${minutes}m ${seconds}s`;
|
||||
}
|
||||
|
||||
function resolveProgressDescription(progress: ActiveGitActionProgress): string | undefined {
|
||||
if (progress.lastOutputLine) {
|
||||
return progress.lastOutputLine;
|
||||
}
|
||||
return formatElapsedDescription(progress.hookStartedAtMs ?? progress.phaseStartedAtMs);
|
||||
}
|
||||
|
||||
function getMenuActionDisabledReason({
|
||||
item,
|
||||
gitStatus,
|
||||
@@ -167,6 +217,21 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
const [isEditingFiles, setIsEditingFiles] = useState(false);
|
||||
const [pendingDefaultBranchAction, setPendingDefaultBranchAction] =
|
||||
useState<PendingDefaultBranchAction | null>(null);
|
||||
const activeGitActionProgressRef = useRef<ActiveGitActionProgress | null>(null);
|
||||
|
||||
const updateActiveProgressToast = useCallback(() => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
toastManager.update(progress.toastId, {
|
||||
type: "loading",
|
||||
title: progress.title,
|
||||
description: resolveProgressDescription(progress),
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}, [threadToastData]);
|
||||
|
||||
const { data: gitStatus = null, error: gitStatusError } = useQuery(gitStatusQueryOptions(gitCwd));
|
||||
|
||||
@@ -196,7 +261,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
gitRunStackedActionMutationOptions({
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
model: settings.textGenerationModel ?? null,
|
||||
modelSelection: settings.textGenerationModelSelection,
|
||||
}),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
@@ -232,6 +297,87 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
})
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
return;
|
||||
}
|
||||
|
||||
const applyProgressEvent = (event: GitActionProgressEvent) => {
|
||||
const progress = activeGitActionProgressRef.current;
|
||||
if (!progress) {
|
||||
return;
|
||||
}
|
||||
if (gitCwd && event.cwd !== gitCwd) {
|
||||
return;
|
||||
}
|
||||
if (progress.actionId !== event.actionId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
switch (event.kind) {
|
||||
case "action_started":
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "phase_started":
|
||||
progress.title = event.label;
|
||||
progress.currentPhaseLabel = event.label;
|
||||
progress.phaseStartedAtMs = now;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.hookName = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_started":
|
||||
progress.title = `Running ${event.hookName}...`;
|
||||
progress.hookName = event.hookName;
|
||||
progress.hookStartedAtMs = now;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "hook_output":
|
||||
progress.lastOutputLine = event.text;
|
||||
break;
|
||||
case "hook_finished":
|
||||
progress.title = progress.currentPhaseLabel ?? "Committing...";
|
||||
progress.hookName = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
// Don't clear timestamps here — the HTTP response handler (line 496)
|
||||
// sets activeGitActionProgressRef to null and shows the success toast.
|
||||
// Clearing timestamps early causes the "Running for Xs" description
|
||||
// to disappear before the success state renders, leaving a bare
|
||||
// "Pushing..." toast in the gap between the WS event and HTTP response.
|
||||
return;
|
||||
case "action_failed":
|
||||
// Same reasoning as action_finished — let the HTTP error handler
|
||||
// manage the final toast state to avoid a flash of bare title.
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
};
|
||||
|
||||
return api.git.onActionProgress(applyProgressEvent);
|
||||
}, [gitCwd, updateActiveProgressToast]);
|
||||
|
||||
useEffect(() => {
|
||||
const interval = window.setInterval(() => {
|
||||
if (!activeGitActionProgressRef.current) {
|
||||
return;
|
||||
}
|
||||
updateActiveProgressToast();
|
||||
}, 1000);
|
||||
|
||||
return () => {
|
||||
window.clearInterval(interval);
|
||||
};
|
||||
}, [updateActiveProgressToast]);
|
||||
|
||||
const openExistingPr = useCallback(async () => {
|
||||
const api = readNativeApi();
|
||||
if (!api) {
|
||||
@@ -259,9 +405,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
data: threadToastData,
|
||||
});
|
||||
});
|
||||
}, [gitStatusForActions?.pr?.state, gitStatusForActions?.pr?.url, threadToastData]);
|
||||
}, [gitStatusForActions, threadToastData]);
|
||||
|
||||
const runGitActionWithToast = useCallback(
|
||||
const runGitActionWithToast = useEffectEvent(
|
||||
async ({
|
||||
action,
|
||||
commitMessage,
|
||||
@@ -273,18 +419,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
isDefaultBranchOverride,
|
||||
progressToastId,
|
||||
filePaths,
|
||||
}: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
skipDefaultBranchPrompt?: boolean;
|
||||
statusOverride?: GitStatusResult | null;
|
||||
featureBranch?: boolean;
|
||||
isDefaultBranchOverride?: boolean;
|
||||
progressToastId?: GitActionToastId;
|
||||
filePaths?: string[];
|
||||
}) => {
|
||||
}: RunGitActionWithToastInput) => {
|
||||
const actionStatus = statusOverride ?? gitStatusForActions;
|
||||
const actionBranch = actionStatus?.branch ?? null;
|
||||
const actionIsDefaultBranch =
|
||||
@@ -319,40 +454,40 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
forcePushOnly: forcePushOnlyProgress,
|
||||
featureBranch,
|
||||
});
|
||||
const actionId = randomUUID();
|
||||
const resolvedProgressToastId =
|
||||
progressToastId ??
|
||||
toastManager.add({
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
description: "Waiting for Git...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
|
||||
activeGitActionProgressRef.current = {
|
||||
toastId: resolvedProgressToastId,
|
||||
actionId,
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
phaseStartedAtMs: null,
|
||||
hookStartedAtMs: null,
|
||||
hookName: null,
|
||||
lastOutputLine: null,
|
||||
currentPhaseLabel: progressStages[0] ?? "Running git action...",
|
||||
};
|
||||
|
||||
if (progressToastId) {
|
||||
toastManager.update(progressToastId, {
|
||||
type: "loading",
|
||||
title: progressStages[0] ?? "Running git action...",
|
||||
description: "Waiting for Git...",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}
|
||||
|
||||
let stageIndex = 0;
|
||||
const stageInterval = setInterval(() => {
|
||||
stageIndex = Math.min(stageIndex + 1, progressStages.length - 1);
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
title: progressStages[stageIndex] ?? "Running git action...",
|
||||
type: "loading",
|
||||
timeout: 0,
|
||||
data: threadToastData,
|
||||
});
|
||||
}, 1100);
|
||||
|
||||
const stopProgressUpdates = () => {
|
||||
clearInterval(stageInterval);
|
||||
};
|
||||
|
||||
const promise = runImmediateGitActionMutation.mutateAsync({
|
||||
actionId,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
@@ -361,7 +496,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
|
||||
try {
|
||||
const result = await promise;
|
||||
stopProgressUpdates();
|
||||
activeGitActionProgressRef.current = null;
|
||||
const resultToast = summarizeGitResult(result);
|
||||
|
||||
const existingOpenPrUrl =
|
||||
@@ -437,7 +572,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
: {}),
|
||||
});
|
||||
} catch (err) {
|
||||
stopProgressUpdates();
|
||||
activeGitActionProgressRef.current = null;
|
||||
toastManager.update(resolvedProgressToastId, {
|
||||
type: "error",
|
||||
title: "Action failed",
|
||||
@@ -446,14 +581,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
[
|
||||
isDefaultBranch,
|
||||
runImmediateGitActionMutation,
|
||||
setPendingDefaultBranchAction,
|
||||
threadToastData,
|
||||
gitStatusForActions,
|
||||
],
|
||||
);
|
||||
|
||||
const continuePendingDefaultBranchAction = useCallback(() => {
|
||||
@@ -469,38 +596,23 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, runGitActionWithToast]);
|
||||
|
||||
const checkoutNewBranchAndRunAction = useCallback(
|
||||
(actionParams: {
|
||||
action: GitStackedAction;
|
||||
commitMessage?: string;
|
||||
forcePushOnlyProgress?: boolean;
|
||||
onConfirmed?: () => void;
|
||||
filePaths?: string[];
|
||||
}) => {
|
||||
void runGitActionWithToast({
|
||||
...actionParams,
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
},
|
||||
[runGitActionWithToast],
|
||||
);
|
||||
}, [pendingDefaultBranchAction]);
|
||||
|
||||
const checkoutFeatureBranchAndContinuePendingAction = useCallback(() => {
|
||||
if (!pendingDefaultBranchAction) return;
|
||||
const { action, commitMessage, forcePushOnlyProgress, onConfirmed, filePaths } =
|
||||
pendingDefaultBranchAction;
|
||||
setPendingDefaultBranchAction(null);
|
||||
checkoutNewBranchAndRunAction({
|
||||
void runGitActionWithToast({
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
forcePushOnlyProgress,
|
||||
...(onConfirmed ? { onConfirmed } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [pendingDefaultBranchAction, checkoutNewBranchAndRunAction]);
|
||||
}, [pendingDefaultBranchAction]);
|
||||
|
||||
const runDialogActionOnNewBranch = useCallback(() => {
|
||||
if (!isCommitDialogOpen) return;
|
||||
@@ -511,18 +623,14 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
setExcludedFiles(new Set());
|
||||
setIsEditingFiles(false);
|
||||
|
||||
checkoutNewBranchAndRunAction({
|
||||
void runGitActionWithToast({
|
||||
action: "commit",
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(!allSelected ? { filePaths: selectedFiles.map((f) => f.path) } : {}),
|
||||
featureBranch: true,
|
||||
skipDefaultBranchPrompt: true,
|
||||
});
|
||||
}, [
|
||||
allSelected,
|
||||
isCommitDialogOpen,
|
||||
dialogCommitMessage,
|
||||
checkoutNewBranchAndRunAction,
|
||||
selectedFiles,
|
||||
]);
|
||||
}, [allSelected, isCommitDialogOpen, dialogCommitMessage, selectedFiles]);
|
||||
|
||||
const runQuickAction = useCallback(() => {
|
||||
if (quickAction.kind === "open_pr") {
|
||||
@@ -562,7 +670,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
if (quickAction.action) {
|
||||
void runGitActionWithToast({ action: quickAction.action });
|
||||
}
|
||||
}, [openExistingPr, pullMutation, quickAction, runGitActionWithToast, threadToastData]);
|
||||
}, [openExistingPr, pullMutation, quickAction, threadToastData]);
|
||||
|
||||
const openDialogForMenuItem = useCallback(
|
||||
(item: GitActionMenuItem) => {
|
||||
@@ -583,7 +691,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
setIsEditingFiles(false);
|
||||
setIsCommitDialogOpen(true);
|
||||
},
|
||||
[openExistingPr, runGitActionWithToast, setIsCommitDialogOpen],
|
||||
[openExistingPr, setIsCommitDialogOpen],
|
||||
);
|
||||
|
||||
const runDialogAction = useCallback(() => {
|
||||
@@ -602,7 +710,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
allSelected,
|
||||
dialogCommitMessage,
|
||||
isCommitDialogOpen,
|
||||
runGitActionWithToast,
|
||||
selectedFiles,
|
||||
setDialogCommitMessage,
|
||||
setIsCommitDialogOpen,
|
||||
|
||||
@@ -53,6 +53,15 @@ function createBaseServerConfig(): ServerConfig {
|
||||
},
|
||||
],
|
||||
availableEditors: [],
|
||||
settings: {
|
||||
claude: { binaryPath: "" },
|
||||
codex: { binaryPath: "", homePath: "" },
|
||||
enableAssistantStreaming: false,
|
||||
defaultThreadEnvMode: "local" as const,
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -64,7 +73,10 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
id: PROJECT_ID,
|
||||
title: "Project",
|
||||
workspaceRoot: "/repo/project",
|
||||
defaultModel: "gpt-5",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
scripts: [],
|
||||
createdAt: NOW_ISO,
|
||||
updatedAt: NOW_ISO,
|
||||
@@ -76,7 +88,10 @@ function createMinimalSnapshot(): OrchestrationReadModel {
|
||||
id: THREAD_ID,
|
||||
projectId: PROJECT_ID,
|
||||
title: "Test thread",
|
||||
model: "gpt-5",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5",
|
||||
},
|
||||
interactionMode: "default",
|
||||
runtimeMode: "full-access",
|
||||
branch: "main",
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getFallbackThreadIdAfterDelete,
|
||||
getVisibleThreadsForProject,
|
||||
getProjectSortTimestamp,
|
||||
hasUnseenCompletion,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
resolveThreadRowClassName,
|
||||
resolveThreadStatusPill,
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
} from "./Sidebar.logic";
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
DEFAULT_INTERACTION_MODE,
|
||||
DEFAULT_RUNTIME_MODE,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "../types";
|
||||
|
||||
function makeLatestTurn(overrides?: {
|
||||
completedAt?: string | null;
|
||||
@@ -281,3 +293,417 @@ describe("resolveProjectStatusIndicator", () => {
|
||||
).toMatchObject({ label: "Plan Ready", dotClass: "bg-violet-500" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("getVisibleThreadsForProject", () => {
|
||||
it("includes the active thread even when it falls below the folded preview", () => {
|
||||
const threads = Array.from({ length: 8 }, (_, index) =>
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe(`thread-${index + 1}`),
|
||||
title: `Thread ${index + 1}`,
|
||||
}),
|
||||
);
|
||||
|
||||
const result = getVisibleThreadsForProject({
|
||||
threads,
|
||||
activeThreadId: ThreadId.makeUnsafe("thread-8"),
|
||||
isThreadListExpanded: false,
|
||||
previewLimit: 6,
|
||||
});
|
||||
|
||||
expect(result.hasHiddenThreads).toBe(true);
|
||||
expect(result.visibleThreads.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.makeUnsafe("thread-1"),
|
||||
ThreadId.makeUnsafe("thread-2"),
|
||||
ThreadId.makeUnsafe("thread-3"),
|
||||
ThreadId.makeUnsafe("thread-4"),
|
||||
ThreadId.makeUnsafe("thread-5"),
|
||||
ThreadId.makeUnsafe("thread-6"),
|
||||
ThreadId.makeUnsafe("thread-8"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns all threads when the list is expanded", () => {
|
||||
const threads = Array.from({ length: 8 }, (_, index) =>
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe(`thread-${index + 1}`),
|
||||
}),
|
||||
);
|
||||
|
||||
const result = getVisibleThreadsForProject({
|
||||
threads,
|
||||
activeThreadId: ThreadId.makeUnsafe("thread-8"),
|
||||
isThreadListExpanded: true,
|
||||
previewLimit: 6,
|
||||
});
|
||||
|
||||
expect(result.hasHiddenThreads).toBe(true);
|
||||
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
|
||||
threads.map((thread) => thread.id),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
const { defaultModelSelection, ...rest } = overrides;
|
||||
return {
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Project",
|
||||
cwd: "/tmp/project",
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
...defaultModelSelection,
|
||||
},
|
||||
expanded: true,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
scripts: [],
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
return {
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
codexThreadId: null,
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
...overrides?.modelSelection,
|
||||
},
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
interactionMode: DEFAULT_INTERACTION_MODE,
|
||||
session: null,
|
||||
messages: [],
|
||||
proposedPlans: [],
|
||||
error: null,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
latestTurn: null,
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
turnDiffSummaries: [],
|
||||
activities: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("sortThreadsForSidebar", () => {
|
||||
it("sorts threads by the latest user message in recency mode", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older",
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer",
|
||||
createdAt: "2026-03-09T10:06:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:06:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.makeUnsafe("thread-2"),
|
||||
ThreadId.makeUnsafe("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to thread timestamps when there is no user message", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "assistant",
|
||||
text: "assistant only",
|
||||
createdAt: "2026-03-09T10:02:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:02:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.makeUnsafe("thread-2"),
|
||||
ThreadId.makeUnsafe("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to id ordering when threads have no sortable timestamps", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
createdAt: "" as never,
|
||||
updatedAt: undefined,
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.makeUnsafe("thread-2"),
|
||||
ThreadId.makeUnsafe("thread-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("can sort threads by createdAt when configured", () => {
|
||||
const sorted = sortThreadsForSidebar(
|
||||
[
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-1"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:10:00.000Z",
|
||||
}),
|
||||
],
|
||||
"created_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.makeUnsafe("thread-1"),
|
||||
ThreadId.makeUnsafe("thread-2"),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getFallbackThreadIdAfterDelete", () => {
|
||||
it("returns the top remaining thread in the deleted thread's project sidebar order", () => {
|
||||
const fallbackThreadId = getFallbackThreadIdAfterDelete({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-oldest"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-active"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-newest"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
createdAt: "2026-03-09T10:10:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-other-project"),
|
||||
projectId: ProjectId.makeUnsafe("project-2"),
|
||||
createdAt: "2026-03-09T10:20:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
deletedThreadId: ThreadId.makeUnsafe("thread-active"),
|
||||
sortOrder: "created_at",
|
||||
});
|
||||
|
||||
expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-newest"));
|
||||
});
|
||||
|
||||
it("skips other threads being deleted in the same action", () => {
|
||||
const fallbackThreadId = getFallbackThreadIdAfterDelete({
|
||||
threads: [
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-active"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-newest"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
createdAt: "2026-03-09T10:10:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-next"),
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
createdAt: "2026-03-09T10:07:00.000Z",
|
||||
messages: [],
|
||||
}),
|
||||
],
|
||||
deletedThreadId: ThreadId.makeUnsafe("thread-active"),
|
||||
deletedThreadIds: new Set([
|
||||
ThreadId.makeUnsafe("thread-active"),
|
||||
ThreadId.makeUnsafe("thread-newest"),
|
||||
]),
|
||||
sortOrder: "created_at",
|
||||
});
|
||||
|
||||
expect(fallbackThreadId).toBe(ThreadId.makeUnsafe("thread-next"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("sortProjectsForSidebar", () => {
|
||||
it("sorts projects by the most recent user message across their threads", () => {
|
||||
const projects = [
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "Older project" }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Newer project" }),
|
||||
];
|
||||
const threads = [
|
||||
makeThread({
|
||||
projectId: ProjectId.makeUnsafe("project-1"),
|
||||
updatedAt: "2026-03-09T10:20:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-1" as never,
|
||||
role: "user",
|
||||
text: "older project user message",
|
||||
createdAt: "2026-03-09T10:01:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:01:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
makeThread({
|
||||
id: ThreadId.makeUnsafe("thread-2"),
|
||||
projectId: ProjectId.makeUnsafe("project-2"),
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
messages: [
|
||||
{
|
||||
id: "message-2" as never,
|
||||
role: "user",
|
||||
text: "newer project user message",
|
||||
createdAt: "2026-03-09T10:05:00.000Z",
|
||||
streaming: false,
|
||||
completedAt: "2026-03-09T10:05:00.000Z",
|
||||
},
|
||||
],
|
||||
}),
|
||||
];
|
||||
|
||||
const sorted = sortProjectsForSidebar(projects, threads, "updated_at");
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to project timestamps when a project has no threads", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Older project",
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-2"),
|
||||
name: "Newer project",
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
],
|
||||
[],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to name and id ordering when projects have no sortable timestamps", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-2"),
|
||||
name: "Beta",
|
||||
createdAt: undefined,
|
||||
updatedAt: undefined,
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Alpha",
|
||||
createdAt: undefined,
|
||||
updatedAt: undefined,
|
||||
}),
|
||||
],
|
||||
[],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("preserves manual project ordering", () => {
|
||||
const projects = [
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First" }),
|
||||
];
|
||||
|
||||
const sorted = sortProjectsForSidebar(projects, [], "manual");
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns the project timestamp when no threads are present", () => {
|
||||
const timestamp = getProjectSortTimestamp(
|
||||
makeProject({ updatedAt: "2026-03-09T10:10:00.000Z" }),
|
||||
[],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(timestamp).toBe(Date.parse("2026-03-09T10:10:00.000Z"));
|
||||
});
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../appSettings";
|
||||
import type { Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import {
|
||||
@@ -8,6 +9,13 @@ import {
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
name: string;
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
|
||||
|
||||
export interface ThreadStatusPill {
|
||||
label:
|
||||
@@ -178,3 +186,174 @@ export function resolveProjectStatusIndicator(
|
||||
|
||||
return highestPriorityStatus;
|
||||
}
|
||||
|
||||
export function getVisibleThreadsForProject(input: {
|
||||
threads: readonly Thread[];
|
||||
activeThreadId: Thread["id"] | undefined;
|
||||
isThreadListExpanded: boolean;
|
||||
previewLimit: number;
|
||||
}): {
|
||||
hasHiddenThreads: boolean;
|
||||
visibleThreads: Thread[];
|
||||
} {
|
||||
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
|
||||
const hasHiddenThreads = threads.length > previewLimit;
|
||||
|
||||
if (!hasHiddenThreads || isThreadListExpanded) {
|
||||
return {
|
||||
hasHiddenThreads,
|
||||
visibleThreads: [...threads],
|
||||
};
|
||||
}
|
||||
|
||||
const previewThreads = threads.slice(0, previewLimit);
|
||||
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
|
||||
const activeThread = threads.find((thread) => thread.id === activeThreadId);
|
||||
if (!activeThread) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
|
||||
const visibleThreadIds = new Set([...previewThreads, activeThread].map((thread) => thread.id));
|
||||
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
|
||||
};
|
||||
}
|
||||
|
||||
function toSortableTimestamp(iso: string | undefined): number | null {
|
||||
if (!iso) return null;
|
||||
const ms = Date.parse(iso);
|
||||
return Number.isFinite(ms) ? ms : null;
|
||||
}
|
||||
|
||||
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
|
||||
let latestUserMessageTimestamp: number | null = null;
|
||||
|
||||
for (const message of thread.messages) {
|
||||
if (message.role !== "user") continue;
|
||||
const messageTimestamp = toSortableTimestamp(message.createdAt);
|
||||
if (messageTimestamp === null) continue;
|
||||
latestUserMessageTimestamp =
|
||||
latestUserMessageTimestamp === null
|
||||
? messageTimestamp
|
||||
: Math.max(latestUserMessageTimestamp, messageTimestamp);
|
||||
}
|
||||
|
||||
if (latestUserMessageTimestamp !== null) {
|
||||
return latestUserMessageTimestamp;
|
||||
}
|
||||
|
||||
return toSortableTimestamp(thread.updatedAt ?? thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
function getThreadSortTimestamp(
|
||||
thread: SidebarThreadSortInput,
|
||||
sortOrder: SidebarThreadSortOrder | Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (sortOrder === "created_at") {
|
||||
return toSortableTimestamp(thread.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
return getLatestUserMessageTimestamp(thread);
|
||||
}
|
||||
|
||||
export function sortThreadsForSidebar<
|
||||
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
|
||||
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
|
||||
return threads.toSorted((left, right) => {
|
||||
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
|
||||
const leftTimestamp = getThreadSortTimestamp(left, sortOrder);
|
||||
const byTimestamp =
|
||||
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
|
||||
if (byTimestamp !== 0) return byTimestamp;
|
||||
return right.id.localeCompare(left.id);
|
||||
});
|
||||
}
|
||||
|
||||
export function getFallbackThreadIdAfterDelete<
|
||||
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt" | "messages">,
|
||||
>(input: {
|
||||
threads: readonly T[];
|
||||
deletedThreadId: T["id"];
|
||||
sortOrder: SidebarThreadSortOrder;
|
||||
deletedThreadIds?: ReadonlySet<T["id"]>;
|
||||
}): T["id"] | null {
|
||||
const { deletedThreadId, deletedThreadIds, sortOrder, threads } = input;
|
||||
const deletedThread = threads.find((thread) => thread.id === deletedThreadId);
|
||||
if (!deletedThread) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
sortThreadsForSidebar(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.projectId === deletedThread.projectId &&
|
||||
thread.id !== deletedThreadId &&
|
||||
!deletedThreadIds?.has(thread.id),
|
||||
),
|
||||
sortOrder,
|
||||
)[0]?.id ?? null
|
||||
);
|
||||
}
|
||||
|
||||
export function getProjectSortTimestamp(
|
||||
project: SidebarProject,
|
||||
projectThreads: readonly SidebarThreadSortInput[],
|
||||
sortOrder: Exclude<SidebarProjectSortOrder, "manual">,
|
||||
): number {
|
||||
if (projectThreads.length > 0) {
|
||||
return projectThreads.reduce(
|
||||
(latest, thread) => Math.max(latest, getThreadSortTimestamp(thread, sortOrder)),
|
||||
Number.NEGATIVE_INFINITY,
|
||||
);
|
||||
}
|
||||
|
||||
if (sortOrder === "created_at") {
|
||||
return toSortableTimestamp(project.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
|
||||
}
|
||||
|
||||
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
|
||||
projects: readonly TProject[],
|
||||
threads: readonly TThread[],
|
||||
sortOrder: SidebarProjectSortOrder,
|
||||
): TProject[] {
|
||||
if (sortOrder === "manual") {
|
||||
return [...projects];
|
||||
}
|
||||
|
||||
const threadsByProjectId = new Map<string, TThread[]>();
|
||||
for (const thread of threads) {
|
||||
const existing = threadsByProjectId.get(thread.projectId) ?? [];
|
||||
existing.push(thread);
|
||||
threadsByProjectId.set(thread.projectId, existing);
|
||||
}
|
||||
|
||||
return [...projects].toSorted((left, right) => {
|
||||
const rightTimestamp = getProjectSortTimestamp(
|
||||
right,
|
||||
threadsByProjectId.get(right.id) ?? [],
|
||||
sortOrder,
|
||||
);
|
||||
const leftTimestamp = getProjectSortTimestamp(
|
||||
left,
|
||||
threadsByProjectId.get(left.id) ?? [],
|
||||
sortOrder,
|
||||
);
|
||||
const byTimestamp =
|
||||
rightTimestamp === leftTimestamp ? 0 : rightTimestamp > leftTimestamp ? 1 : -1;
|
||||
if (byTimestamp !== 0) return byTimestamp;
|
||||
return left.name.localeCompare(right.name) || left.id.localeCompare(right.id);
|
||||
});
|
||||
}
|
||||
+547
-396
File diff suppressed because it is too large.
Load diff
@@ -6,7 +6,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import GitActionsControl from "../GitActionsControl";
|
||||
import { DiffIcon } from "lucide-react";
|
||||
import { DiffIcon, TerminalSquareIcon } from "lucide-react";
|
||||
import { Badge } from "../ui/badge";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import ProjectScriptsControl, { type NewProjectScriptInput } from "../ProjectScriptsControl";
|
||||
@@ -24,6 +24,9 @@ interface ChatHeaderProps {
|
||||
preferredScriptId: string | null;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
availableEditors: ReadonlyArray<EditorId>;
|
||||
terminalAvailable: boolean;
|
||||
terminalOpen: boolean;
|
||||
terminalToggleShortcutLabel: string | null;
|
||||
diffToggleShortcutLabel: string | null;
|
||||
gitCwd: string | null;
|
||||
diffOpen: boolean;
|
||||
@@ -31,6 +34,7 @@ interface ChatHeaderProps {
|
||||
onAddProjectScript: (input: NewProjectScriptInput) => Promise<void>;
|
||||
onUpdateProjectScript: (scriptId: string, input: NewProjectScriptInput) => Promise<void>;
|
||||
onDeleteProjectScript: (scriptId: string) => Promise<void>;
|
||||
onToggleTerminal: () => void;
|
||||
onToggleDiff: () => void;
|
||||
}
|
||||
|
||||
@@ -44,6 +48,9 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
preferredScriptId,
|
||||
keybindings,
|
||||
availableEditors,
|
||||
terminalAvailable,
|
||||
terminalOpen,
|
||||
terminalToggleShortcutLabel,
|
||||
diffToggleShortcutLabel,
|
||||
gitCwd,
|
||||
diffOpen,
|
||||
@@ -51,6 +58,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
onAddProjectScript,
|
||||
onUpdateProjectScript,
|
||||
onDeleteProjectScript,
|
||||
onToggleTerminal,
|
||||
onToggleDiff,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
@@ -94,6 +102,30 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
/>
|
||||
)}
|
||||
{activeProjectName && <GitActionsControl gitCwd={gitCwd} activeThreadId={activeThreadId} />}
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<Toggle
|
||||
className="shrink-0"
|
||||
pressed={terminalOpen}
|
||||
onPressedChange={onToggleTerminal}
|
||||
aria-label="Toggle terminal drawer"
|
||||
variant="outline"
|
||||
size="xs"
|
||||
disabled={!terminalAvailable}
|
||||
>
|
||||
<TerminalSquareIcon className="size-3" />
|
||||
</Toggle>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="bottom">
|
||||
{!terminalAvailable
|
||||
? "Terminal is unavailable until this thread has an active project."
|
||||
: terminalToggleShortcutLabel
|
||||
? `Toggle terminal drawer (${terminalToggleShortcutLabel})`
|
||||
: "Toggle terminal drawer"}
|
||||
</TooltipPopup>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
|
||||
@@ -1,197 +0,0 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { ClaudeTraitsPicker } from "./ClaudeTraitsPicker";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountPicker(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
effort?: "low" | "medium" | "high" | "max" | "ultrathink" | null;
|
||||
thinkingEnabled?: boolean | null;
|
||||
fastModeEnabled?: boolean;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-claude-traits");
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: "claudeAgent",
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
...(props?.effort ? { effort: props.effort } : {}),
|
||||
...(props?.thinkingEnabled === false ? { thinking: false } : {}),
|
||||
...(props?.fastModeEnabled ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const screen = await render(
|
||||
<ClaudeTraitsPicker
|
||||
threadId={threadId}
|
||||
model={props?.model ?? "claude-opus-4-6"}
|
||||
onPromptChange={onPromptChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
return {
|
||||
onPromptChange,
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("ClaudeTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
const mounted = await mountPicker();
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus models", async () => {
|
||||
const mounted = await mountPicker({ model: "claude-sonnet-4-6" });
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows a thinking on/off dropdown for Haiku", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-haiku-4-5",
|
||||
thinkingEnabled: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Thinking On");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => {
|
||||
const mounted = await mountPicker({
|
||||
effort: "high",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Ultrathink");
|
||||
expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("persists sticky claude model options when traits change", async () => {
|
||||
const mounted = await mountPicker({
|
||||
model: "claude-opus-4-6",
|
||||
effort: "medium",
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "Max" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toMatchObject({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,272 +0,0 @@
|
||||
import {
|
||||
ProviderKind,
|
||||
type ClaudeCodeEffort,
|
||||
type ClaudeModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeClaudeModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
isClaudeUltrathinkPrompt,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
|
||||
|
||||
const PROVIDER = "claudeAgent" as const satisfies ProviderKind;
|
||||
|
||||
const CLAUDE_EFFORT_LABELS: Record<ClaudeCodeEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
max: "Max",
|
||||
ultrathink: "Ultrathink",
|
||||
};
|
||||
|
||||
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
|
||||
|
||||
function getSelectedClaudeTraits(
|
||||
model: string | null | undefined,
|
||||
prompt: string,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): {
|
||||
effort: Exclude<ClaudeCodeEffort, "ultrathink"> | null;
|
||||
thinkingEnabled: boolean | null;
|
||||
fastModeEnabled: boolean;
|
||||
options: ReadonlyArray<ClaudeCodeEffort>;
|
||||
ultrathinkPromptControlled: boolean;
|
||||
supportsFastMode: boolean;
|
||||
} {
|
||||
const options = getReasoningEffortOptions(PROVIDER, model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER) as Exclude<
|
||||
ClaudeCodeEffort,
|
||||
"ultrathink"
|
||||
>;
|
||||
const resolvedEffort = resolveReasoningEffortForProvider(PROVIDER, modelOptions?.effort);
|
||||
const effort =
|
||||
resolvedEffort && resolvedEffort !== "ultrathink" && options.includes(resolvedEffort)
|
||||
? resolvedEffort
|
||||
: options.includes(defaultReasoningEffort)
|
||||
? defaultReasoningEffort
|
||||
: null;
|
||||
const thinkingEnabled = supportsClaudeThinkingToggle(model)
|
||||
? (modelOptions?.thinking ?? true)
|
||||
: null;
|
||||
const supportsFastMode = supportsClaudeFastMode(model);
|
||||
return {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled: supportsFastMode && modelOptions?.fastMode === true,
|
||||
options,
|
||||
ultrathinkPromptControlled:
|
||||
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt),
|
||||
supportsFastMode,
|
||||
};
|
||||
}
|
||||
|
||||
interface ClaudeTraitsMenuContentProps {
|
||||
threadId: ThreadId;
|
||||
model: string | null | undefined;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}
|
||||
|
||||
export const ClaudeTraitsMenuContent = memo(function ClaudeTraitsMenuContentImpl({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const {
|
||||
effort,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
options,
|
||||
ultrathinkPromptControlled,
|
||||
supportsFastMode,
|
||||
} = getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
(value: ClaudeCodeEffort) => {
|
||||
if (ultrathinkPromptControlled) return;
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
if (nextEffort === "ultrathink") {
|
||||
const nextPrompt =
|
||||
prompt.trim().length === 0
|
||||
? ULTRATHINK_PROMPT_PREFIX
|
||||
: applyClaudePromptEffortPrefix(prompt, "ultrathink");
|
||||
onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
effort: nextEffort,
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
},
|
||||
[
|
||||
ultrathinkPromptControlled,
|
||||
model,
|
||||
modelOptions,
|
||||
onPromptChange,
|
||||
threadId,
|
||||
setProviderModelOptions,
|
||||
options,
|
||||
prompt,
|
||||
],
|
||||
);
|
||||
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{effort ? (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">Effort</div>
|
||||
{ultrathinkPromptControlled ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Remove Ultrathink from the prompt to change effort.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup value={effort} onValueChange={handleEffortChange}>
|
||||
{options.map((option) => (
|
||||
<MenuRadioItem key={option} value={option} disabled={ultrathinkPromptControlled}>
|
||||
{CLAUDE_EFFORT_LABELS[option]}
|
||||
{option === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : thinkingEnabled !== null ? (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
|
||||
<MenuRadioGroup
|
||||
value={thinkingEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
thinking: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="on">On (default)</MenuRadioItem>
|
||||
<MenuRadioItem value="off">Off</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : null}
|
||||
{supportsFastMode ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
threadId,
|
||||
PROVIDER,
|
||||
normalizeClaudeModelOptions(model, {
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export const ClaudeTraitsPicker = memo(function ClaudeTraitsPicker({
|
||||
threadId,
|
||||
model,
|
||||
onPromptChange,
|
||||
}: ClaudeTraitsMenuContentProps) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const draft = useComposerThreadDraft(threadId);
|
||||
const prompt = draft.prompt;
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const { effort, thinkingEnabled, fastModeEnabled, ultrathinkPromptControlled, supportsFastMode } =
|
||||
getSelectedClaudeTraits(model, prompt, modelOptions);
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
: effort
|
||||
? CLAUDE_EFFORT_LABELS[effort]
|
||||
: thinkingEnabled === null
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -1,188 +0,0 @@
|
||||
import "../../index.css";
|
||||
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CodexTraitsPicker } from "./CodexTraitsPicker";
|
||||
import { COMPOSER_DRAFT_STORAGE_KEY, useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountPicker(props: {
|
||||
reasoningEffort?: "low" | "medium" | "high" | "xhigh";
|
||||
fastModeEnabled: boolean;
|
||||
}) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider: "codex",
|
||||
model: null,
|
||||
modelOptions: {
|
||||
codex: {
|
||||
...(props.reasoningEffort ? { reasoningEffort: props.reasoningEffort } : {}),
|
||||
...(props.fastModeEnabled ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[ProjectId.makeUnsafe("project-codex-traits")]: threadId,
|
||||
},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("CodexTraitsPicker", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows Fast in the trigger label when fast mode is active", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: true,
|
||||
});
|
||||
|
||||
try {
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("High · Fast");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Extra High");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("persists sticky codex model options when traits change", async () => {
|
||||
const mounted = await mountPicker({
|
||||
fastModeEnabled: false,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "on" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toMatchObject({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hydrates legacy codex persisted state into modelOptions through the picker", async () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-legacy");
|
||||
localStorage.setItem(
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
JSON.stringify({
|
||||
state: {
|
||||
draftsByThreadId: {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
attachments: [],
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
effort: "xhigh",
|
||||
codexFastMode: true,
|
||||
serviceTier: "fast",
|
||||
},
|
||||
},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
},
|
||||
version: 1,
|
||||
}),
|
||||
);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(<CodexTraitsPicker threadId={threadId} />, { container: host });
|
||||
|
||||
try {
|
||||
await useComposerDraftStore.persist.rehydrate();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Extra High · Fast");
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,147 +0,0 @@
|
||||
import type {
|
||||
CodexModelOptions,
|
||||
CodexReasoningEffort,
|
||||
ProviderKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
normalizeCodexModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { useComposerDraftStore, useComposerThreadDraft } from "../../composerDraftStore";
|
||||
import { Button } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
|
||||
const PROVIDER = "codex" as const satisfies ProviderKind;
|
||||
|
||||
const CODEX_REASONING_LABELS: Record<CodexReasoningEffort, string> = {
|
||||
low: "Low",
|
||||
medium: "Medium",
|
||||
high: "High",
|
||||
xhigh: "Extra High",
|
||||
};
|
||||
|
||||
function getSelectedCodexTraits(modelOptions: CodexModelOptions | null | undefined): {
|
||||
effort: CodexReasoningEffort;
|
||||
fastModeEnabled: boolean;
|
||||
} {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
return {
|
||||
effort:
|
||||
resolveReasoningEffortForProvider(PROVIDER, modelOptions?.reasoningEffort) ??
|
||||
defaultReasoningEffort,
|
||||
fastModeEnabled: modelOptions?.fastMode === true,
|
||||
};
|
||||
}
|
||||
|
||||
function CodexTraitsMenuContentImpl(props: { threadId: ThreadId }) {
|
||||
const draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions = draft.modelOptions?.[PROVIDER];
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const options = getReasoningEffortOptions(PROVIDER);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort(PROVIDER);
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
|
||||
return (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Reasoning</div>
|
||||
<MenuRadioGroup
|
||||
value={effort}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
const nextEffort = options.find((option) => option === value);
|
||||
if (!nextEffort) return;
|
||||
setProviderModelOptions(
|
||||
props.threadId,
|
||||
PROVIDER,
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
reasoningEffort: nextEffort,
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
{options.map((option) => (
|
||||
<MenuRadioItem key={option} value={option}>
|
||||
{CODEX_REASONING_LABELS[option]}
|
||||
{option === defaultReasoningEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
setProviderModelOptions(
|
||||
props.threadId,
|
||||
PROVIDER,
|
||||
normalizeCodexModelOptions({
|
||||
...modelOptions,
|
||||
fastMode: value === "on",
|
||||
}),
|
||||
{ persistSticky: true },
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const CodexTraitsMenuContent = memo(CodexTraitsMenuContentImpl);
|
||||
|
||||
export const CodexTraitsPicker = memo(function CodexTraitsPicker(props: { threadId: ThreadId }) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const modelOptions = useComposerThreadDraft(props.threadId).modelOptions?.codex;
|
||||
const { effort, fastModeEnabled } = getSelectedCodexTraits(modelOptions);
|
||||
const triggerLabel = [CODEX_REASONING_LABELS[effort], ...(fastModeEnabled ? ["Fast"] : [])]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<CodexTraitsMenuContent threadId={props.threadId} />
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ProviderModelOptions, ThreadId } from "@t3tools/contracts";
|
||||
import { DEFAULT_MODEL_BY_PROVIDER, ModelSelection, ThreadId } from "@t3tools/contracts";
|
||||
import "../../index.css";
|
||||
|
||||
import { page } from "vitest/browser";
|
||||
@@ -6,30 +6,31 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";
|
||||
import { ClaudeTraitsMenuContent } from "./ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent } from "./CodexTraitsPicker";
|
||||
import { TraitsMenuContent } from "./TraitsPicker";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
|
||||
async function mountMenu(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
provider?: "codex" | "claudeAgent";
|
||||
modelOptions?: ProviderModelOptions | null;
|
||||
}) {
|
||||
async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: string }) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-compact-menu");
|
||||
const provider = props?.provider ?? "claudeAgent";
|
||||
const provider = props?.modelSelection?.provider ?? "claudeAgent";
|
||||
const draftsByThreadId = {} as ReturnType<
|
||||
typeof useComposerDraftStore.getState
|
||||
>["draftsByThreadId"];
|
||||
const model = props?.modelSelection?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
|
||||
draftsByThreadId[threadId] = {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
provider,
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
modelOptions: props?.modelOptions ?? null,
|
||||
modelSelectionByProvider: {
|
||||
[provider]: {
|
||||
provider,
|
||||
model,
|
||||
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
|
||||
},
|
||||
},
|
||||
activeProvider: provider,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
@@ -41,6 +42,7 @@ async function mountMenu(props?: {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const onPromptChange = vi.fn();
|
||||
const providerOptions = props?.modelSelection?.options;
|
||||
const screen = await render(
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={false}
|
||||
@@ -48,15 +50,14 @@ async function mountMenu(props?: {
|
||||
planSidebarOpen={false}
|
||||
runtimeMode="approval-required"
|
||||
traitsMenuContent={
|
||||
provider === "codex" ? (
|
||||
<CodexTraitsMenuContent threadId={threadId} />
|
||||
) : (
|
||||
<ClaudeTraitsMenuContent
|
||||
threadId={threadId}
|
||||
model={props?.model ?? "claude-opus-4-6"}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
)
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
prompt={props?.prompt ?? ""}
|
||||
modelOptions={providerOptions}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
}
|
||||
onToggleInteractionMode={vi.fn()}
|
||||
onTogglePlanSidebar={vi.fn()}
|
||||
@@ -65,11 +66,14 @@ async function mountMenu(props?: {
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
cleanup: async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
},
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,107 +84,90 @@ describe("CompactComposerControlsMenu", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
const mounted = await mountMenu();
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus Claude models", async () => {
|
||||
const mounted = await mountMenu({ model: "claude-sonnet-4-6" });
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-sonnet-4-6",
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: { provider: "claudeAgent", model: "claude-sonnet-4-6" },
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a Claude thinking on/off section for Haiku", async () => {
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-haiku-4-5",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: { thinking: true },
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink messaging with disabled effort controls", async () => {
|
||||
const mounted = await mountMenu({
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
},
|
||||
await using _ = await mountMenu({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
},
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
await page.getByLabelText("More composer controls").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { cn } from "~/lib/utils";
|
||||
import { type ContextWindowSnapshot, formatContextWindowTokens } from "~/lib/contextWindow";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
|
||||
function formatPercentage(value: number | null): string | null {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return null;
|
||||
}
|
||||
if (value < 10) {
|
||||
return `${value.toFixed(1).replace(/\.0$/, "")}%`;
|
||||
}
|
||||
return `${Math.round(value)}%`;
|
||||
}
|
||||
|
||||
export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
|
||||
const { usage } = props;
|
||||
const usedPercentage = formatPercentage(usage.usedPercentage);
|
||||
const normalizedPercentage = Math.max(0, Math.min(100, usage.usedPercentage ?? 0));
|
||||
const radius = 9.75;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
delay={150}
|
||||
closeDelay={0}
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="group inline-flex items-center justify-center rounded-full transition-opacity hover:opacity-85"
|
||||
aria-label={
|
||||
usage.maxTokens !== null && usedPercentage
|
||||
? `Context window ${usedPercentage} used`
|
||||
: `Context window ${formatContextWindowTokens(usage.usedTokens)} tokens used`
|
||||
}
|
||||
>
|
||||
<span className="relative flex h-6 w-6 items-center justify-center">
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
className="-rotate-90 absolute inset-0 h-full w-full transform-gpu"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<circle
|
||||
cx="12"
|
||||
cy="12"
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="color-mix(in oklab, var(--color-muted) 70%, transparent)"
|
||||
strokeWidth="3"
|
||||
/>
|
||||
<circle
|
||||
cx="12"
|
||||
cy="12"
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="var(--color-muted-foreground)"
|
||||
strokeWidth="3"
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={dashOffset}
|
||||
className="transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none"
|
||||
/>
|
||||
</svg>
|
||||
<span
|
||||
className={cn(
|
||||
"relative flex h-[15px] w-[15px] items-center justify-center rounded-full bg-background text-[8px] font-medium",
|
||||
"text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{usage.usedPercentage !== null
|
||||
? Math.round(usage.usedPercentage)
|
||||
: formatContextWindowTokens(usage.usedTokens)}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<PopoverPopup tooltipStyle side="top" align="end" className="w-max max-w-none px-3 py-2">
|
||||
<div className="space-y-1.5 leading-tight">
|
||||
<div className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
|
||||
Context window
|
||||
</div>
|
||||
{usage.maxTokens !== null && usedPercentage ? (
|
||||
<div className="whitespace-nowrap text-xs font-medium text-foreground">
|
||||
<span>{usedPercentage}</span>
|
||||
<span className="mx-1">⋅</span>
|
||||
<span>{formatContextWindowTokens(usage.usedTokens)}</span>
|
||||
<span>/</span>
|
||||
<span>{formatContextWindowTokens(usage.maxTokens ?? null)} context used</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-foreground">
|
||||
{formatContextWindowTokens(usage.usedTokens)} tokens used so far
|
||||
</div>
|
||||
)}
|
||||
{(usage.totalProcessedTokens ?? null) !== null &&
|
||||
(usage.totalProcessedTokens ?? 0) > usage.usedTokens ? (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Total processed: {formatContextWindowTokens(usage.totalProcessedTokens ?? null)}{" "}
|
||||
tokens
|
||||
</div>
|
||||
) : null}
|
||||
{usage.compactsAutomatically ? (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Automatically compacts its context when needed.
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -96,4 +96,48 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
});
|
||||
|
||||
it("renders context compaction entries in the normal work log", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
label: "Context compacted",
|
||||
tone: "info",
|
||||
},
|
||||
},
|
||||
]}
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Context compacted");
|
||||
expect(markup).toContain("Work log");
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { PROVIDER_DISPLAY_NAMES, type ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
|
||||
import { CircleAlertIcon } from "lucide-react";
|
||||
@@ -12,12 +12,7 @@ export const ProviderHealthBanner = memo(function ProviderHealthBanner({
|
||||
return null;
|
||||
}
|
||||
|
||||
const providerLabel =
|
||||
status.provider === "codex"
|
||||
? "Codex"
|
||||
: status.provider === "claudeAgent"
|
||||
? "Claude"
|
||||
: status.provider;
|
||||
const providerLabel = PROVIDER_DISPLAY_NAMES[status.provider] ?? status.provider;
|
||||
const defaultMessage =
|
||||
status.status === "error"
|
||||
? `${providerLabel} provider is unavailable.`
|
||||
|
||||
@@ -21,6 +21,7 @@ async function mountPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
lockedProvider: ProviderKind | null;
|
||||
triggerVariant?: "ghost" | "outline";
|
||||
}) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
@@ -31,6 +32,7 @@ async function mountPicker(props: {
|
||||
model={props.model}
|
||||
lockedProvider={props.lockedProvider}
|
||||
modelOptionsByProvider={MODEL_OPTIONS_BY_PROVIDER}
|
||||
triggerVariant={props.triggerVariant}
|
||||
onProviderModelChange={onProviderModelChange}
|
||||
/>,
|
||||
{ container: host },
|
||||
@@ -71,6 +73,51 @@ describe("ProviderModelPicker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens provider submenus with a visible gap from the parent menu", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: null,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
const providerTrigger = page.getByRole("menuitem", { name: "Codex" });
|
||||
await providerTrigger.hover();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("GPT-5 Codex");
|
||||
});
|
||||
|
||||
const providerTriggerElement = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="menuitem"]'),
|
||||
).find((element) => element.textContent?.includes("Codex"));
|
||||
if (!providerTriggerElement) {
|
||||
throw new Error("Expected the Codex provider trigger to be mounted.");
|
||||
}
|
||||
|
||||
const providerTriggerRect = providerTriggerElement.getBoundingClientRect();
|
||||
const modelElement = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[role="menuitemradio"]'),
|
||||
).find((element) => element.textContent?.includes("GPT-5 Codex"));
|
||||
if (!modelElement) {
|
||||
throw new Error("Expected the submenu model option to be mounted.");
|
||||
}
|
||||
|
||||
const submenuPopup = modelElement.closest('[data-slot="menu-sub-content"]');
|
||||
if (!(submenuPopup instanceof HTMLElement)) {
|
||||
throw new Error("Expected submenu popup to be mounted.");
|
||||
}
|
||||
|
||||
const submenuRect = submenuPopup.getBoundingClientRect();
|
||||
|
||||
expect(submenuRect.left).toBeGreaterThanOrEqual(providerTriggerRect.right);
|
||||
expect(submenuRect.left - providerTriggerRect.right).toBeGreaterThanOrEqual(2);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows models directly when the provider is locked mid-thread", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
@@ -111,4 +158,24 @@ describe("ProviderModelPicker", () => {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("accepts outline trigger styling", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "codex",
|
||||
model: "gpt-5-codex",
|
||||
lockedProvider: null,
|
||||
triggerVariant: "outline",
|
||||
});
|
||||
|
||||
try {
|
||||
const button = document.querySelector("button");
|
||||
if (!(button instanceof HTMLButtonElement)) {
|
||||
throw new Error("Expected picker trigger button to be rendered.");
|
||||
}
|
||||
expect(button.className).toContain("border-input");
|
||||
expect(button.className).toContain("bg-popover");
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,10 @@
|
||||
import { type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { type ProviderPickerKind, PROVIDER_OPTIONS } from "../../session-logic";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button } from "../ui/button";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
@@ -56,6 +57,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
activeProviderIconClassName?: string;
|
||||
compact?: boolean;
|
||||
disabled?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
@@ -92,10 +95,11 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
variant={props.triggerVariant ?? "ghost"}
|
||||
className={cn(
|
||||
"min-w-0 justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 [&_svg]:mx-0",
|
||||
props.compact ? "max-w-42 shrink-0" : "max-w-48 shrink sm:max-w-56 sm:px-3",
|
||||
props.triggerClassName,
|
||||
)}
|
||||
disabled={props.disabled}
|
||||
/>
|
||||
@@ -153,7 +157,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
/>
|
||||
{option.label}
|
||||
</MenuSubTrigger>
|
||||
<MenuSubPopup className="[--available-height:min(24rem,70vh)]">
|
||||
<MenuSubPopup className="[--available-height:min(24rem,70vh)]" sideOffset={4}>
|
||||
<MenuGroup>
|
||||
<MenuRadioGroup
|
||||
value={props.provider === option.value ? props.model : ""}
|
||||
|
||||
@@ -0,0 +1,382 @@
|
||||
import "../../index.css";
|
||||
|
||||
import {
|
||||
type ModelSelection,
|
||||
ClaudeModelOptions,
|
||||
CodexModelOptions,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
import { useCallback } from "react";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { render } from "vitest-browser-react";
|
||||
|
||||
import { TraitsPicker } from "./TraitsPicker";
|
||||
import {
|
||||
COMPOSER_DRAFT_STORAGE_KEY,
|
||||
ComposerThreadDraftState,
|
||||
useComposerDraftStore,
|
||||
useComposerThreadDraft,
|
||||
useEffectiveComposerModelState,
|
||||
} from "../../composerDraftStore";
|
||||
|
||||
// ── Claude TraitsPicker tests ─────────────────────────────────────────
|
||||
|
||||
const CLAUDE_THREAD_ID = ThreadId.makeUnsafe("thread-claude-traits");
|
||||
|
||||
function ClaudeTraitsPickerHarness(props: {
|
||||
model: string;
|
||||
fallbackModelSelection: ModelSelection | null;
|
||||
triggerVariant?: "ghost" | "outline";
|
||||
}) {
|
||||
const prompt = useComposerThreadDraft(CLAUDE_THREAD_ID).prompt;
|
||||
const setPrompt = useComposerDraftStore((store) => store.setPrompt);
|
||||
const { modelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadId: CLAUDE_THREAD_ID,
|
||||
selectedProvider: "claudeAgent",
|
||||
threadModelSelection: props.fallbackModelSelection,
|
||||
projectModelSelection: null,
|
||||
customModelsByProvider: { codex: [], claudeAgent: [] },
|
||||
});
|
||||
const handlePromptChange = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
setPrompt(CLAUDE_THREAD_ID, nextPrompt);
|
||||
},
|
||||
[setPrompt],
|
||||
);
|
||||
|
||||
return (
|
||||
<TraitsPicker
|
||||
provider="claudeAgent"
|
||||
threadId={CLAUDE_THREAD_ID}
|
||||
model={selectedModel ?? props.model}
|
||||
prompt={prompt}
|
||||
modelOptions={modelOptions?.claudeAgent}
|
||||
onPromptChange={handlePromptChange}
|
||||
triggerVariant={props.triggerVariant}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function mountClaudePicker(props?: {
|
||||
model?: string;
|
||||
prompt?: string;
|
||||
options?: ClaudeModelOptions;
|
||||
fallbackModelOptions?: {
|
||||
effort?: "low" | "medium" | "high" | "max" | "ultrathink";
|
||||
thinking?: boolean;
|
||||
fastMode?: boolean;
|
||||
} | null;
|
||||
skipDraftModelOptions?: boolean;
|
||||
triggerVariant?: "ghost" | "outline";
|
||||
}) {
|
||||
const model = props?.model ?? "claude-opus-4-6";
|
||||
const claudeOptions = !props?.skipDraftModelOptions ? props?.options : undefined;
|
||||
const draftsByThreadId: Record<ThreadId, ComposerThreadDraftState> = {
|
||||
[CLAUDE_THREAD_ID]: {
|
||||
prompt: props?.prompt ?? "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: props?.skipDraftModelOptions
|
||||
? {}
|
||||
: {
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
model,
|
||||
...(claudeOptions && Object.keys(claudeOptions).length > 0
|
||||
? { options: claudeOptions }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
activeProvider: "claudeAgent",
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
},
|
||||
};
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const fallbackModelSelection =
|
||||
props?.fallbackModelOptions !== undefined
|
||||
? ({
|
||||
provider: "claudeAgent",
|
||||
model,
|
||||
options: props.fallbackModelOptions ?? undefined,
|
||||
} satisfies ModelSelection)
|
||||
: null;
|
||||
const screen = await render(
|
||||
<ClaudeTraitsPickerHarness
|
||||
model={model}
|
||||
fallbackModelSelection={fallbackModelSelection}
|
||||
{...(props?.triggerVariant ? { triggerVariant: props.triggerVariant } : {})}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
describe("TraitsPicker (Claude)", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls for Opus", async () => {
|
||||
await using _ = await mountClaudePicker();
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
});
|
||||
|
||||
it("hides fast mode controls for non-Opus models", async () => {
|
||||
await using _ = await mountClaudePicker({ model: "claude-sonnet-4-6" });
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").not.toContain("Fast Mode");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-sonnet-4-6",
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Max");
|
||||
expect(text).toContain("Ultrathink");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows a th inking on/off dropdown for Haiku", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-haiku-4-5",
|
||||
options: { thinking: true },
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Thinking On");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Thinking");
|
||||
expect(text).toContain("On (default)");
|
||||
expect(text).toContain("Off");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows prompt-controlled Ultrathink state with disabled effort controls", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "high" },
|
||||
prompt: "Ultrathink:\nInvestigate this",
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("Ultrathink");
|
||||
expect(document.body.textContent ?? "").not.toContain("Ultrathink · Prompt");
|
||||
});
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Effort");
|
||||
expect(text).toContain("Remove Ultrathink from the prompt to change effort.");
|
||||
expect(text).not.toContain("Fallback Effort");
|
||||
});
|
||||
});
|
||||
|
||||
it("persists sticky claude model options when traits change", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
model: "claude-opus-4-6",
|
||||
options: { effort: "medium", fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "Max" }).click();
|
||||
|
||||
expect(
|
||||
useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent,
|
||||
).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts outline trigger styling", async () => {
|
||||
await using _ = await mountClaudePicker({
|
||||
triggerVariant: "outline",
|
||||
});
|
||||
|
||||
const button = document.querySelector("button");
|
||||
if (!(button instanceof HTMLButtonElement)) {
|
||||
throw new Error("Expected traits trigger button to be rendered.");
|
||||
}
|
||||
expect(button.className).toContain("border-input");
|
||||
expect(button.className).toContain("bg-popover");
|
||||
});
|
||||
});
|
||||
|
||||
// ── Codex TraitsPicker tests ──────────────────────────────────────────
|
||||
|
||||
async function mountCodexPicker(props: { model?: string; options?: CodexModelOptions }) {
|
||||
const threadId = ThreadId.makeUnsafe("thread-codex-traits");
|
||||
const model = props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
const draftsByThreadId: Record<ThreadId, ComposerThreadDraftState> = {
|
||||
[threadId]: {
|
||||
prompt: "",
|
||||
images: [],
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model,
|
||||
...(props.options ? { options: props.options } : {}),
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
},
|
||||
};
|
||||
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[ProjectId.makeUnsafe("project-codex-traits")]: threadId,
|
||||
},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const screen = await render(
|
||||
<TraitsPicker
|
||||
provider="codex"
|
||||
threadId={threadId}
|
||||
model={props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex}
|
||||
prompt=""
|
||||
modelOptions={props.options}
|
||||
onPromptChange={() => {}}
|
||||
/>,
|
||||
{ container: host },
|
||||
);
|
||||
|
||||
const cleanup = async () => {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
|
||||
return {
|
||||
[Symbol.asyncDispose]: cleanup,
|
||||
cleanup,
|
||||
};
|
||||
}
|
||||
|
||||
describe("TraitsPicker (Codex)", () => {
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
localStorage.removeItem(COMPOSER_DRAFT_STORAGE_KEY);
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
});
|
||||
});
|
||||
|
||||
it("shows fast mode controls", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Fast Mode");
|
||||
expect(text).toContain("off");
|
||||
expect(text).toContain("on");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows Fast in the trigger label when fast mode is active", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: true },
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("High · Fast");
|
||||
});
|
||||
});
|
||||
|
||||
it("shows only the provided effort options", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Extra High");
|
||||
});
|
||||
});
|
||||
|
||||
it("persists sticky codex model options when traits change", async () => {
|
||||
await using _ = await mountCodexPicker({
|
||||
options: { fastMode: false },
|
||||
});
|
||||
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitemradio", { name: "on" }).click();
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toMatchObject({
|
||||
provider: "codex",
|
||||
options: { fastMode: true },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,346 @@
|
||||
import {
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelCapabilities,
|
||||
isClaudeUltrathinkPrompt,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
import { ChevronDownIcon } from "lucide-react";
|
||||
import { Button, buttonVariants } from "../ui/button";
|
||||
import {
|
||||
Menu,
|
||||
MenuGroup,
|
||||
MenuPopup,
|
||||
MenuRadioGroup,
|
||||
MenuRadioItem,
|
||||
MenuSeparator as MenuDivider,
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
type ProviderOptions = ProviderModelOptions[ProviderKind];
|
||||
type TraitsPersistence =
|
||||
| {
|
||||
threadId: ThreadId;
|
||||
onModelOptionsChange?: never;
|
||||
}
|
||||
| {
|
||||
threadId?: undefined;
|
||||
onModelOptionsChange: (nextOptions: ProviderOptions | undefined) => void;
|
||||
};
|
||||
|
||||
const ULTRATHINK_PROMPT_PREFIX = "Ultrathink:\n";
|
||||
|
||||
function getRawEffort(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
): string | null {
|
||||
if (provider === "codex") {
|
||||
return trimOrNull((modelOptions as CodexModelOptions | undefined)?.reasoningEffort);
|
||||
}
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort);
|
||||
}
|
||||
|
||||
function buildNextOptions(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
patch: Record<string, unknown>,
|
||||
): ProviderOptions {
|
||||
if (provider === "codex") {
|
||||
return { ...(modelOptions as CodexModelOptions | undefined), ...patch } as CodexModelOptions;
|
||||
}
|
||||
return { ...(modelOptions as ClaudeModelOptions | undefined), ...patch } as ClaudeModelOptions;
|
||||
}
|
||||
|
||||
function getSelectedTraits(
|
||||
provider: ProviderKind,
|
||||
model: string | null | undefined,
|
||||
prompt: string,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
allowPromptInjectedEffort: boolean,
|
||||
) {
|
||||
const caps = getModelCapabilities(provider, model);
|
||||
const effortLevels = allowPromptInjectedEffort
|
||||
? caps.reasoningEffortLevels
|
||||
: caps.reasoningEffortLevels.filter(
|
||||
(option) => !caps.promptInjectedEffortLevels.includes(option.value),
|
||||
);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
// Resolve effort from options (provider-specific key)
|
||||
const resolvedEffort = getRawEffort(provider, modelOptions);
|
||||
|
||||
// Filter out prompt-injected efforts from the "current effort" display
|
||||
const isPromptInjected = resolvedEffort
|
||||
? caps.promptInjectedEffortLevels.includes(resolvedEffort)
|
||||
: false;
|
||||
const effort =
|
||||
resolvedEffort && !isPromptInjected && hasEffortLevel(caps, resolvedEffort)
|
||||
? resolvedEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
|
||||
// Thinking toggle (only for models that support it)
|
||||
const thinkingEnabled = caps.supportsThinkingToggle
|
||||
? ((modelOptions as ClaudeModelOptions | undefined)?.thinking ?? true)
|
||||
: null;
|
||||
|
||||
// Fast mode
|
||||
const fastModeEnabled =
|
||||
caps.supportsFastMode &&
|
||||
(modelOptions as { fastMode?: boolean } | undefined)?.fastMode === true;
|
||||
|
||||
// Prompt-controlled effort (e.g. ultrathink in prompt text)
|
||||
const ultrathinkPromptControlled =
|
||||
allowPromptInjectedEffort &&
|
||||
caps.promptInjectedEffortLevels.length > 0 &&
|
||||
isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
caps,
|
||||
effort,
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
ultrathinkPromptControlled,
|
||||
};
|
||||
}
|
||||
|
||||
export interface TraitsMenuContentProps {
|
||||
provider: ProviderKind;
|
||||
model: string | null | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
modelOptions?: ProviderOptions | null | undefined;
|
||||
allowPromptInjectedEffort?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
}
|
||||
|
||||
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
provider,
|
||||
model,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
modelOptions,
|
||||
allowPromptInjectedEffort = true,
|
||||
...persistence
|
||||
}: TraitsMenuContentProps & TraitsPersistence) {
|
||||
const setProviderModelOptions = useComposerDraftStore((store) => store.setProviderModelOptions);
|
||||
const updateModelOptions = useCallback(
|
||||
(nextOptions: ProviderOptions | undefined) => {
|
||||
if ("onModelOptionsChange" in persistence) {
|
||||
persistence.onModelOptionsChange(nextOptions);
|
||||
return;
|
||||
}
|
||||
setProviderModelOptions(persistence.threadId, provider, nextOptions, { persistSticky: true });
|
||||
},
|
||||
[persistence, provider, setProviderModelOptions],
|
||||
);
|
||||
const {
|
||||
caps,
|
||||
effort,
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
(value: string) => {
|
||||
if (ultrathinkPromptControlled) return;
|
||||
if (!value) return;
|
||||
const nextOption = effortLevels.find((option) => option.value === value);
|
||||
if (!nextOption) return;
|
||||
if (caps.promptInjectedEffortLevels.includes(nextOption.value)) {
|
||||
const nextPrompt =
|
||||
prompt.trim().length === 0
|
||||
? ULTRATHINK_PROMPT_PREFIX
|
||||
: applyClaudePromptEffortPrefix(prompt, "ultrathink");
|
||||
onPromptChange(nextPrompt);
|
||||
return;
|
||||
}
|
||||
const effortKey = provider === "codex" ? "reasoningEffort" : "effort";
|
||||
updateModelOptions(
|
||||
buildNextOptions(provider, modelOptions, { [effortKey]: nextOption.value }),
|
||||
);
|
||||
},
|
||||
[
|
||||
ultrathinkPromptControlled,
|
||||
modelOptions,
|
||||
onPromptChange,
|
||||
updateModelOptions,
|
||||
effortLevels,
|
||||
prompt,
|
||||
caps.promptInjectedEffortLevels,
|
||||
provider,
|
||||
],
|
||||
);
|
||||
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{effort ? (
|
||||
<>
|
||||
<MenuGroup>
|
||||
<div className="px-2 pt-1.5 pb-1 font-medium text-muted-foreground text-xs">Effort</div>
|
||||
{ultrathinkPromptControlled ? (
|
||||
<div className="px-2 pb-1.5 text-muted-foreground/80 text-xs">
|
||||
Remove Ultrathink from the prompt to change effort.
|
||||
</div>
|
||||
) : null}
|
||||
<MenuRadioGroup value={effort} onValueChange={handleEffortChange}>
|
||||
{effortLevels.map((option) => (
|
||||
<MenuRadioItem
|
||||
key={option.value}
|
||||
value={option.value}
|
||||
disabled={ultrathinkPromptControlled}
|
||||
>
|
||||
{option.label}
|
||||
{option.value === defaultEffort ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : thinkingEnabled !== null ? (
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Thinking</div>
|
||||
<MenuRadioGroup
|
||||
value={thinkingEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
updateModelOptions(
|
||||
buildNextOptions(provider, modelOptions, { thinking: value === "on" }),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="on">On (default)</MenuRadioItem>
|
||||
<MenuRadioItem value="off">Off</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
) : null}
|
||||
{caps.supportsFastMode ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">Fast Mode</div>
|
||||
<MenuRadioGroup
|
||||
value={fastModeEnabled ? "on" : "off"}
|
||||
onValueChange={(value) => {
|
||||
updateModelOptions(
|
||||
buildNextOptions(provider, modelOptions, { fastMode: value === "on" }),
|
||||
);
|
||||
}}
|
||||
>
|
||||
<MenuRadioItem value="off">off</MenuRadioItem>
|
||||
<MenuRadioItem value="on">on</MenuRadioItem>
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
model,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
modelOptions,
|
||||
allowPromptInjectedEffort = true,
|
||||
triggerVariant,
|
||||
triggerClassName,
|
||||
...persistence
|
||||
}: TraitsMenuContentProps & TraitsPersistence) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const {
|
||||
caps,
|
||||
effort,
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
|
||||
const effortLabel = effort
|
||||
? (effortLevels.find((l) => l.value === effort)?.label ?? effort)
|
||||
: null;
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
: effortLabel
|
||||
? effortLabel
|
||||
: thinkingEnabled === null
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(caps.supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
|
||||
const isCodexStyle = provider === "codex";
|
||||
|
||||
return (
|
||||
<Menu
|
||||
open={isMenuOpen}
|
||||
onOpenChange={(open) => {
|
||||
setIsMenuOpen(open);
|
||||
}}
|
||||
>
|
||||
<MenuTrigger
|
||||
render={
|
||||
<Button
|
||||
size="sm"
|
||||
variant={triggerVariant ?? "ghost"}
|
||||
className={cn(
|
||||
isCodexStyle
|
||||
? "min-w-0 max-w-40 shrink justify-start overflow-hidden whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:max-w-48 sm:px-3 [&_svg]:mx-0"
|
||||
: "shrink-0 whitespace-nowrap px-2 text-muted-foreground/70 hover:text-foreground/80 sm:px-3",
|
||||
triggerClassName,
|
||||
)}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{isCodexStyle ? (
|
||||
<span className="flex min-w-0 w-full items-center gap-2 overflow-hidden">
|
||||
{triggerLabel}
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 shrink-0 opacity-60" />
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<span>{triggerLabel}</span>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-3 opacity-60" />
|
||||
</>
|
||||
)}
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="start">
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
model={model}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
modelOptions={modelOptions}
|
||||
allowPromptInjectedEffort={allowPromptInjectedEffort}
|
||||
{...persistence}
|
||||
/>
|
||||
</MenuPopup>
|
||||
</Menu>
|
||||
);
|
||||
});
|
||||
@@ -34,12 +34,51 @@ describe("getComposerProviderState", () => {
|
||||
provider: "codex",
|
||||
promptEffort: "low",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves codex fast mode when it is the only active option", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit codex default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("returns Claude defaults for effort-capable models", () => {
|
||||
@@ -73,9 +112,7 @@ describe("getComposerProviderState", () => {
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "medium",
|
||||
modelOptionsForDispatch: {
|
||||
claudeAgent: {
|
||||
effort: "medium",
|
||||
},
|
||||
effort: "medium",
|
||||
},
|
||||
composerFrameClassName: "ultrathink-frame",
|
||||
composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]",
|
||||
@@ -100,50 +137,49 @@ describe("getComposerProviderState", () => {
|
||||
provider: "claudeAgent",
|
||||
promptEffort: null,
|
||||
modelOptionsForDispatch: {
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores codex options while resolving Claude state", () => {
|
||||
it("preserves Claude fast mode when it is the only active option", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
claudeAgent: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit Claude default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores Claude options while resolving codex state", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "Ultrathink:\nThis should not matter",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -5,17 +5,16 @@ import {
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultReasoningEffort,
|
||||
getReasoningEffortOptions,
|
||||
getModelCapabilities,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
resolveReasoningEffortForProvider,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
} from "@t3tools/shared/model";
|
||||
import type { ReactNode } from "react";
|
||||
import { ClaudeTraitsMenuContent, ClaudeTraitsPicker } from "./ClaudeTraitsPicker";
|
||||
import { CodexTraitsMenuContent, CodexTraitsPicker } from "./CodexTraitsPicker";
|
||||
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
|
||||
|
||||
export type ComposerProviderStateInput = {
|
||||
provider: ProviderKind;
|
||||
@@ -27,7 +26,7 @@ export type ComposerProviderStateInput = {
|
||||
export type ComposerProviderState = {
|
||||
provider: ProviderKind;
|
||||
promptEffort: string | null;
|
||||
modelOptionsForDispatch: ProviderModelOptions | undefined;
|
||||
modelOptionsForDispatch: ProviderModelOptions[ProviderKind] | undefined;
|
||||
composerFrameClassName?: string;
|
||||
composerSurfaceClassName?: string;
|
||||
modelPickerIconClassName?: string;
|
||||
@@ -38,70 +37,114 @@ type ProviderRegistryEntry = {
|
||||
renderTraitsMenuContent: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) => ReactNode;
|
||||
renderTraitsPicker: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) => ReactNode;
|
||||
};
|
||||
|
||||
function getProviderStateFromCapabilities(
|
||||
input: ComposerProviderStateInput,
|
||||
): ComposerProviderState {
|
||||
const { provider, model, prompt, modelOptions } = input;
|
||||
const caps = getModelCapabilities(provider, model);
|
||||
const providerOptions = modelOptions?.[provider];
|
||||
|
||||
// Resolve effort
|
||||
const rawEffort = providerOptions
|
||||
? "effort" in providerOptions
|
||||
? providerOptions.effort
|
||||
: "reasoningEffort" in providerOptions
|
||||
? providerOptions.reasoningEffort
|
||||
: null
|
||||
: null;
|
||||
|
||||
const draftEffort = trimOrNull(rawEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
const isPromptInjected = draftEffort
|
||||
? caps.promptInjectedEffortLevels.includes(draftEffort)
|
||||
: false;
|
||||
const promptEffort =
|
||||
draftEffort && !isPromptInjected && hasEffortLevel(caps, draftEffort)
|
||||
? draftEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
|
||||
// Normalize options for dispatch
|
||||
const normalizedOptions =
|
||||
provider === "codex"
|
||||
? normalizeCodexModelOptions(model, providerOptions)
|
||||
: normalizeClaudeModelOptions(model, providerOptions);
|
||||
|
||||
// Ultrathink styling (driven by capabilities data, not provider identity)
|
||||
const ultrathinkActive =
|
||||
caps.promptInjectedEffortLevels.length > 0 && isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
provider,
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedOptions,
|
||||
...(ultrathinkActive ? { composerFrameClassName: "ultrathink-frame" } : {}),
|
||||
...(ultrathinkActive
|
||||
? { composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" }
|
||||
: {}),
|
||||
...(ultrathinkActive ? { modelPickerIconClassName: "ultrathink-chroma" } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
codex: {
|
||||
getState: ({ modelOptions }) => {
|
||||
const promptEffort =
|
||||
resolveReasoningEffortForProvider("codex", modelOptions?.codex?.reasoningEffort) ??
|
||||
getDefaultReasoningEffort("codex");
|
||||
const normalizedCodexOptions = normalizeCodexModelOptions(modelOptions?.codex);
|
||||
|
||||
return {
|
||||
provider: "codex",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedCodexOptions
|
||||
? { codex: normalizedCodexOptions }
|
||||
: undefined,
|
||||
};
|
||||
},
|
||||
renderTraitsMenuContent: ({ threadId }) => <CodexTraitsMenuContent threadId={threadId} />,
|
||||
renderTraitsPicker: ({ threadId }) => <CodexTraitsPicker threadId={threadId} />,
|
||||
getState: (input) => getProviderStateFromCapabilities(input),
|
||||
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsMenuContent
|
||||
provider="codex"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsPicker
|
||||
provider="codex"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
},
|
||||
claudeAgent: {
|
||||
getState: ({ model, prompt, modelOptions }) => {
|
||||
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
|
||||
const draftEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
modelOptions?.claudeAgent?.effort,
|
||||
);
|
||||
const defaultEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
const promptEffort =
|
||||
draftEffort && draftEffort !== "ultrathink" && reasoningOptions.includes(draftEffort)
|
||||
? draftEffort
|
||||
: reasoningOptions.includes(defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const normalizedClaudeOptions = normalizeClaudeModelOptions(model, modelOptions?.claudeAgent);
|
||||
const ultrathinkActive =
|
||||
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
provider: "claudeAgent",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedClaudeOptions
|
||||
? { claudeAgent: normalizedClaudeOptions }
|
||||
: undefined,
|
||||
...(ultrathinkActive ? { composerFrameClassName: "ultrathink-frame" } : {}),
|
||||
...(ultrathinkActive
|
||||
? { composerSurfaceClassName: "shadow-[0_0_0_1px_rgba(255,255,255,0.04)_inset]" }
|
||||
: {}),
|
||||
...(ultrathinkActive ? { modelPickerIconClassName: "ultrathink-chroma" } : {}),
|
||||
};
|
||||
},
|
||||
renderTraitsMenuContent: ({ threadId, model, onPromptChange }) => (
|
||||
<ClaudeTraitsMenuContent threadId={threadId} model={model} onPromptChange={onPromptChange} />
|
||||
getState: (input) => getProviderStateFromCapabilities(input),
|
||||
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsMenuContent
|
||||
provider="claudeAgent"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
renderTraitsPicker: ({ threadId, model, onPromptChange }) => (
|
||||
<ClaudeTraitsPicker threadId={threadId} model={model} onPromptChange={onPromptChange} />
|
||||
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsPicker
|
||||
provider="claudeAgent"
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
},
|
||||
};
|
||||
@@ -114,11 +157,15 @@ export function renderProviderTraitsMenuContent(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}): ReactNode {
|
||||
return composerProviderRegistry[input.provider].renderTraitsMenuContent({
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
modelOptions: input.modelOptions,
|
||||
prompt: input.prompt,
|
||||
onPromptChange: input.onPromptChange,
|
||||
});
|
||||
}
|
||||
@@ -127,11 +174,15 @@ export function renderProviderTraitsPicker(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}): ReactNode {
|
||||
return composerProviderRegistry[input.provider].renderTraitsPicker({
|
||||
threadId: input.threadId,
|
||||
model: input.model,
|
||||
modelOptions: input.modelOptions,
|
||||
prompt: input.prompt,
|
||||
onPromptChange: input.onPromptChange,
|
||||
});
|
||||
}
|
||||
@@ -164,32 +164,45 @@ function SelectPopup({
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({ className, children, ...props }: SelectPrimitive.Item.Props) {
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
hideIndicator = false,
|
||||
...props
|
||||
}: SelectPrimitive.Item.Props & {
|
||||
hideIndicator?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
className={cn(
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default items-center gap-2 rounded-sm py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
hideIndicator ? "grid-cols-[1fr] ps-3 pe-3" : "grid-cols-[1rem_1fr] ps-2 pe-4",
|
||||
className,
|
||||
)}
|
||||
data-slot="select-item"
|
||||
{...props}
|
||||
>
|
||||
<SelectPrimitive.ItemIndicator className="col-start-1">
|
||||
<svg
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/1500/svg"
|
||||
>
|
||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
||||
</svg>
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
<SelectPrimitive.ItemText className="col-start-2 min-w-0">
|
||||
{hideIndicator ? null : (
|
||||
<SelectPrimitive.ItemIndicator className="col-start-1" data-slot="select-item-indicator">
|
||||
<svg
|
||||
fill="none"
|
||||
height="24"
|
||||
stroke="currentColor"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth="2"
|
||||
viewBox="0 0 24 24"
|
||||
width="24"
|
||||
xmlns="http://www.w3.org/1500/svg"
|
||||
>
|
||||
<path d="M5.252 12.7 10.2 18.63 18.748 5.37" />
|
||||
</svg>
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
)}
|
||||
<SelectPrimitive.ItemText
|
||||
className={cn("min-w-0", hideIndicator ? "col-start-1" : "col-start-2")}
|
||||
data-slot="select-item-text"
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type ModelSelection,
|
||||
type ProviderModelOptions,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -67,11 +72,27 @@ function resetComposerDraftStore() {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModel: null,
|
||||
stickyModelOptions: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
}
|
||||
|
||||
function modelSelection(
|
||||
provider: "codex" | "claudeAgent",
|
||||
model: string,
|
||||
options?: ModelSelection["options"],
|
||||
): ModelSelection {
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
...(options ? { options } : {}),
|
||||
} as ModelSelection;
|
||||
}
|
||||
|
||||
function providerModelOptions(options: ProviderModelOptions): ProviderModelOptions {
|
||||
return options;
|
||||
}
|
||||
|
||||
describe("composerDraftStore addImages", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
@@ -197,6 +218,8 @@ describe("composerDraftStore syncPersistedAttachments", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -253,6 +276,8 @@ describe("composerDraftStore terminal contexts", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -517,9 +542,11 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
it("clears draft registration independently", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setProjectDraftThreadId(projectId, threadId);
|
||||
store.setPrompt(threadId, "remove me");
|
||||
store.clearDraftThread(threadId);
|
||||
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("updates branch context on an existing draft thread", () => {
|
||||
@@ -593,62 +620,58 @@ describe("composerDraftStore project draft thread mapping", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore modelOptions", () => {
|
||||
describe("composerDraftStore modelSelection", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model-options");
|
||||
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores provider-scoped model options in the draft", () => {
|
||||
it("stores a model selection in the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("drops default-only model options from the draft", () => {
|
||||
it("keeps default-only model selections on the draft", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
});
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(modelSelection("codex", "gpt-5.4"));
|
||||
});
|
||||
|
||||
it("replaces only the targeted provider model options", () => {
|
||||
it("replaces only the targeted provider options on the current model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
}),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
@@ -659,114 +682,166 @@ describe("composerDraftStore modelOptions", () => {
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("removes only the targeted provider entry when next options normalize empty", () => {
|
||||
it("keeps explicit default-state overrides on the selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
claudeAgent: {
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", {
|
||||
thinking: true,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
reasoningEffort: "xhigh",
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({});
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: true,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider).toEqual({});
|
||||
});
|
||||
|
||||
it("removes model options entirely when the last provider entry normalizes empty", () => {
|
||||
it("keeps explicit off/default codex overrides on the selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4", { fastMode: true }));
|
||||
|
||||
store.setProviderModelOptions(threadId, "codex", {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(
|
||||
modelSelection("codex", "gpt-5.4", {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("updates only the draft when sticky persistence is omitted", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
store.setModelOptions(threadId, {
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", {
|
||||
thinking: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
codex: {
|
||||
fastMode: true,
|
||||
},
|
||||
claudeAgent: {
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
codex: {
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not clear other provider options when setting options for a single provider", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
// Set options for both providers
|
||||
store.setModelOptions(
|
||||
threadId,
|
||||
providerModelOptions({
|
||||
codex: { fastMode: true },
|
||||
claudeAgent: { effort: "max" },
|
||||
}),
|
||||
);
|
||||
|
||||
// Now set options for only codex — claudeAgent should be untouched
|
||||
store.setModelOptions(threadId, providerModelOptions({ codex: { reasoningEffort: "xhigh" } }));
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ reasoningEffort: "xhigh" });
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" });
|
||||
});
|
||||
|
||||
it("preserves other provider options when switching the active model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelOptions(
|
||||
threadId,
|
||||
providerModelOptions({
|
||||
codex: { fastMode: true },
|
||||
claudeAgent: { effort: "max" },
|
||||
}),
|
||||
);
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("claudeAgent", "claude-opus-4-6"));
|
||||
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
expect(draft?.modelSelectionByProvider.codex?.options).toEqual({ fastMode: true });
|
||||
expect(draft?.activeProvider).toBe("claudeAgent");
|
||||
});
|
||||
|
||||
it("creates the first sticky snapshot from provider option changes", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
"codex",
|
||||
{
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.4", {
|
||||
fastMode: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("updates only the draft when sticky persistence is disabled", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelOptions({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
store.setModelOptions(threadId, {
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
|
||||
store.setProviderModelOptions(
|
||||
threadId,
|
||||
@@ -777,34 +852,35 @@ describe("composerDraftStore modelOptions", () => {
|
||||
{ persistSticky: false },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelOptions).toEqual({
|
||||
claudeAgent: {
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setModel", () => {
|
||||
describe("composerDraftStore setModelSelection", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-model");
|
||||
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("keeps explicit DEFAULT_MODEL overrides instead of coercing to null", () => {
|
||||
it("keeps explicit model overrides instead of coercing to null", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModel(threadId, "gpt-5.3-codex");
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.3-codex"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.model).toBe(
|
||||
"gpt-5.3-codex",
|
||||
);
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(modelSelection("codex", "gpt-5.3-codex"));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -813,63 +889,74 @@ describe("composerDraftStore sticky composer settings", () => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("stores sticky model and codex model options", () => {
|
||||
it("stores a sticky model selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModel("gpt-5.3-codex");
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
store.setStickyModelSelection(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState()).toMatchObject({
|
||||
stickyModel: "gpt-5.3-codex",
|
||||
stickyModelOptions: {
|
||||
codex: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("codex");
|
||||
});
|
||||
|
||||
it("normalizes empty sticky model options", () => {
|
||||
it("normalizes empty sticky model options by dropping selection options", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setStickyModelOptions({
|
||||
codex: {
|
||||
fastMode: false,
|
||||
},
|
||||
});
|
||||
store.setStickyModelSelection(modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelOptions).toEqual({});
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyActiveProvider).toBe("codex");
|
||||
});
|
||||
|
||||
it("applies sticky activeProvider to new drafts", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
const threadId = ThreadId.makeUnsafe("thread-sticky-active-provider");
|
||||
|
||||
store.setStickyModelSelection(modelSelection("claudeAgent", "claude-opus-4-6"));
|
||||
store.applyStickyState(threadId);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
modelSelectionByProvider: {
|
||||
claudeAgent: modelSelection("claudeAgent", "claude-opus-4-6"),
|
||||
},
|
||||
activeProvider: "claudeAgent",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("composerDraftStore setProvider", () => {
|
||||
describe("composerDraftStore provider-scoped option updates", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-provider");
|
||||
|
||||
beforeEach(() => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("persists provider-only selection even when prompt/model are empty", () => {
|
||||
it("retains off-provider option memory without changing the active selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "codex");
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.provider).toBe("codex");
|
||||
});
|
||||
|
||||
it("removes empty provider-only draft when provider is reset", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setProvider(threadId, "codex");
|
||||
store.setProvider(threadId, null);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
}),
|
||||
);
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", { effort: "max" });
|
||||
const draft = useComposerDraftStore.getState().draftsByThreadId[threadId];
|
||||
expect(draft?.modelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", { reasoningEffort: "medium" }),
|
||||
);
|
||||
expect(draft?.modelSelectionByProvider.claudeAgent?.options).toEqual({ effort: "max" });
|
||||
expect(draft?.activeProvider).toBe("codex");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Loaded 100 of 144 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user