Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f8c9d71187 | ||
|
|
3f089a454b | ||
|
|
b225dfaf77 | ||
|
|
ff8d87ddee | ||
|
|
3289a25e57 | ||
|
|
df5bde7e11 | ||
|
|
b3bca04caf | ||
|
|
bf71e0bc5e | ||
|
|
a542a3b168 | ||
|
|
56d13faa1a |
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
+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";
|
||||
@@ -145,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",
|
||||
@@ -157,12 +158,9 @@ const startTurn = (input: {
|
||||
text: input.text,
|
||||
attachments: [],
|
||||
},
|
||||
...(input.provider !== undefined
|
||||
...(input.modelSelection !== undefined
|
||||
? {
|
||||
modelSelection: {
|
||||
provider: input.provider,
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[input.provider],
|
||||
},
|
||||
modelSelection: input.modelSelection,
|
||||
}
|
||||
: {}),
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
@@ -941,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(
|
||||
@@ -995,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(
|
||||
@@ -1102,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) =>
|
||||
@@ -1171,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(
|
||||
@@ -1241,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(
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -21,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>;
|
||||
@@ -461,6 +466,7 @@ function runStackedAction(
|
||||
{
|
||||
...input,
|
||||
actionId: input.actionId ?? "test-action-id",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
},
|
||||
options,
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
||||
import { realpathSync } from "node:fs";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path } from "effect";
|
||||
import type { GitActionProgressEvent, GitActionProgressPhase } from "@t3tools/contracts";
|
||||
import { GitActionProgressEvent, GitActionProgressPhase, ModelSelection } from "@t3tools/contracts";
|
||||
import {
|
||||
resolveAutoFeatureBranchName,
|
||||
sanitizeBranchFragment,
|
||||
@@ -684,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);
|
||||
@@ -711,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)));
|
||||
|
||||
@@ -724,13 +724,13 @@ 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,
|
||||
) =>
|
||||
@@ -760,7 +760,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
branch,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(model ? { model } : {}),
|
||||
modelSelection,
|
||||
});
|
||||
}
|
||||
if (!suggestion) {
|
||||
@@ -837,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;
|
||||
@@ -881,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`);
|
||||
@@ -1102,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({
|
||||
@@ -1115,7 +1115,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
includeBranch: true,
|
||||
...(model ? { model } : {}),
|
||||
modelSelection,
|
||||
});
|
||||
if (!suggestion) {
|
||||
return yield* gitManagerError(
|
||||
@@ -1181,11 +1181,11 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
label: "Preparing feature branch...",
|
||||
});
|
||||
const result = yield* runFeatureBranchStep(
|
||||
input.modelSelection,
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
);
|
||||
branchStep = result.branchStep;
|
||||
commitMessageForStep = result.resolvedCommitMessage;
|
||||
@@ -1198,13 +1198,13 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
|
||||
currentPhase = "commit";
|
||||
const commit = yield* runCommitStep(
|
||||
input.modelSelection,
|
||||
input.cwd,
|
||||
input.action,
|
||||
currentBranch,
|
||||
commitMessageForStep,
|
||||
preResolvedCommitSuggestion,
|
||||
input.filePaths,
|
||||
input.textGenerationModel,
|
||||
options?.progressReporter,
|
||||
progress.actionId,
|
||||
);
|
||||
@@ -1237,7 +1237,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
Effect.flatMap(() =>
|
||||
Effect.gen(function* () {
|
||||
currentPhase = "pr";
|
||||
return yield* runPrStep(input.cwd, currentBranch, input.textGenerationModel);
|
||||
return yield* runPrStep(input.modelSelection, input.cwd, currentBranch);
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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 =
|
||||
| {
|
||||
|
||||
@@ -1933,11 +1933,11 @@ engineLayer("OrchestrationProjectionPipeline via engine dispatch", (it) => {
|
||||
|
||||
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'
|
||||
`;
|
||||
@@ -1945,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"}',
|
||||
},
|
||||
]);
|
||||
}),
|
||||
|
||||
@@ -34,8 +34,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_provider,
|
||||
default_model,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
@@ -45,8 +44,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'project-1',
|
||||
'Project 1',
|
||||
'/tmp/project-1',
|
||||
'codex',
|
||||
'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',
|
||||
@@ -59,8 +57,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_selection_json,
|
||||
branch,
|
||||
worktree_path,
|
||||
latest_turn_id,
|
||||
@@ -72,8 +69,7 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'project-1',
|
||||
'Thread 1',
|
||||
'codex',
|
||||
'gpt-5-codex',
|
||||
'{"provider":"codex","model":"gpt-5-codex"}',
|
||||
NULL,
|
||||
NULL,
|
||||
'turn-1',
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
ChatAttachment,
|
||||
IsoDateTime,
|
||||
ModelSelection,
|
||||
MessageId,
|
||||
NonNegativeInt,
|
||||
OrchestrationCheckpointFile,
|
||||
@@ -18,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";
|
||||
@@ -44,18 +44,12 @@ import {
|
||||
} from "../Services/ProjectionSnapshotQuery.ts";
|
||||
|
||||
const decodeReadModel = Schema.decodeUnknownEffect(OrchestrationReadModel);
|
||||
const ProjectionProjectDbRowSchema = Schema.Struct({
|
||||
projectId: ProjectionProject.fields.projectId,
|
||||
title: ProjectionProject.fields.title,
|
||||
workspaceRoot: ProjectionProject.fields.workspaceRoot,
|
||||
defaultProvider: Schema.NullOr(Schema.Literals(["codex", "claudeAgent"])),
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
createdAt: ProjectionProject.fields.createdAt,
|
||||
updatedAt: ProjectionProject.fields.updatedAt,
|
||||
deletedAt: ProjectionProject.fields.deletedAt,
|
||||
});
|
||||
const ProjectionProjectDbRowSchema = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
Struct.assign({
|
||||
isStreaming: Schema.Number,
|
||||
@@ -63,22 +57,11 @@ const ProjectionThreadMessageDbRowSchema = ProjectionThreadMessage.mapFields(
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadProposedPlanDbRowSchema = ProjectionThreadProposedPlan;
|
||||
const ProjectionThreadDbRowSchema = Schema.Struct({
|
||||
threadId: ProjectionThread.fields.threadId,
|
||||
projectId: ProjectionThread.fields.projectId,
|
||||
title: ProjectionThread.fields.title,
|
||||
provider: Schema.Literals(["codex", "claudeAgent"]),
|
||||
model: Schema.String,
|
||||
modelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
runtimeMode: ProjectionThread.fields.runtimeMode,
|
||||
interactionMode: ProjectionThread.fields.interactionMode,
|
||||
branch: ProjectionThread.fields.branch,
|
||||
worktreePath: ProjectionThread.fields.worktreePath,
|
||||
latestTurnId: ProjectionThread.fields.latestTurnId,
|
||||
createdAt: ProjectionThread.fields.createdAt,
|
||||
updatedAt: ProjectionThread.fields.updatedAt,
|
||||
deletedAt: ProjectionThread.fields.deletedAt,
|
||||
});
|
||||
const ProjectionThreadDbRowSchema = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
}),
|
||||
);
|
||||
const ProjectionThreadActivityDbRowSchema = ProjectionThreadActivity.mapFields(
|
||||
Struct.assign({
|
||||
payload: Schema.fromJsonString(Schema.Unknown),
|
||||
@@ -103,7 +86,6 @@ const ProjectionLatestTurnDbRowSchema = Schema.Struct({
|
||||
sourceProposedPlanId: Schema.NullOr(OrchestrationProposedPlanId),
|
||||
});
|
||||
const ProjectionStateDbRowSchema = ProjectionState;
|
||||
const decodeModelSelectionSchema = Schema.decodeUnknownEffect(ModelSelection);
|
||||
|
||||
const REQUIRED_SNAPSHOT_PROJECTORS = [
|
||||
ORCHESTRATION_PROJECTOR_NAMES.projects,
|
||||
@@ -153,19 +135,6 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
|
||||
: toPersistenceSqlError(sqlOperation)(cause);
|
||||
}
|
||||
|
||||
const decodeModelSelection = (input: {
|
||||
readonly provider: "codex" | "claudeAgent";
|
||||
readonly model: string;
|
||||
readonly options: unknown;
|
||||
}) =>
|
||||
decodeModelSelectionSchema({
|
||||
provider: input.provider,
|
||||
model: input.model,
|
||||
...(input.options !== null && input.options !== undefined ? { options: input.options } : {}),
|
||||
}).pipe(
|
||||
Effect.mapError(toPersistenceDecodeError("ProjectionSnapshotQuery.decodeModelSelection")),
|
||||
);
|
||||
|
||||
const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -178,9 +147,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_provider AS "defaultProvider",
|
||||
default_model AS "defaultModel",
|
||||
default_model_options_json AS "defaultModelOptions",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -199,9 +166,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json AS "modelOptions",
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -572,65 +537,36 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
});
|
||||
}
|
||||
|
||||
const projects: ReadonlyArray<OrchestrationProject> = yield* Effect.forEach(
|
||||
projectRows,
|
||||
(row) => {
|
||||
const defaultModelSelectionEffect: Effect.Effect<
|
||||
OrchestrationProject["defaultModelSelection"],
|
||||
ProjectionRepositoryError
|
||||
> =
|
||||
row.defaultProvider === null || row.defaultModel === null
|
||||
? Effect.succeed(null)
|
||||
: decodeModelSelection({
|
||||
provider: row.defaultProvider,
|
||||
model: row.defaultModel,
|
||||
options: row.defaultModelOptions,
|
||||
});
|
||||
const projects: ReadonlyArray<OrchestrationProject> = projectRows.map((row) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection: row.defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}));
|
||||
|
||||
return defaultModelSelectionEffect.pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
id: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
})),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
const threads: ReadonlyArray<OrchestrationThread> = yield* Effect.forEach(
|
||||
threadRows,
|
||||
(row) =>
|
||||
decodeModelSelection({
|
||||
provider: row.provider,
|
||||
model: row.model,
|
||||
options: row.modelOptions,
|
||||
}).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
})),
|
||||
),
|
||||
);
|
||||
const threads: ReadonlyArray<OrchestrationThread> = threadRows.map((row) => ({
|
||||
id: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: row.modelSelection,
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurn: latestTurnByThread.get(row.threadId) ?? null,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
messages: messagesByThread.get(row.threadId) ?? [],
|
||||
proposedPlans: proposedPlansByThread.get(row.threadId) ?? [],
|
||||
activities: activitiesByThread.get(row.threadId) ?? [],
|
||||
checkpoints: checkpointsByThread.get(row.threadId) ?? [],
|
||||
session: sessionsByThread.get(row.threadId) ?? null,
|
||||
}));
|
||||
|
||||
const snapshot = {
|
||||
snapshotSequence: computeSnapshotSequence(stateRows),
|
||||
|
||||
@@ -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 =>
|
||||
@@ -63,9 +64,6 @@ async function waitFor(
|
||||
return poll();
|
||||
}
|
||||
|
||||
const inferTestProviderForModel = (model: string): "codex" | "claudeAgent" =>
|
||||
model.startsWith("claude-") ? "claudeAgent" : "codex";
|
||||
|
||||
describe("ProviderCommandReactor", () => {
|
||||
let runtime: ManagedRuntime.ManagedRuntime<
|
||||
OrchestrationEngineService | ProviderCommandReactor,
|
||||
@@ -96,38 +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 threadProvider = inferTestProviderForModel(threadModel);
|
||||
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 &&
|
||||
@@ -136,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" &&
|
||||
@@ -145,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,
|
||||
@@ -207,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),
|
||||
@@ -228,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),
|
||||
);
|
||||
@@ -246,10 +234,7 @@ describe("ProviderCommandReactor", () => {
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Provider Project",
|
||||
workspaceRoot: "/tmp/provider-project",
|
||||
defaultModelSelection: {
|
||||
provider: threadProvider,
|
||||
model: threadModel,
|
||||
},
|
||||
defaultModelSelection: modelSelection,
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
@@ -260,10 +245,7 @@ describe("ProviderCommandReactor", () => {
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
projectId: asProjectId("project-1"),
|
||||
title: "Thread",
|
||||
modelSelection: {
|
||||
provider: threadProvider,
|
||||
model: threadModel,
|
||||
},
|
||||
modelSelection: modelSelection,
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
branch: null,
|
||||
@@ -381,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(
|
||||
@@ -432,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(
|
||||
@@ -521,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(
|
||||
@@ -572,45 +560,53 @@ describe("ProviderCommandReactor", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("allows custom model strings on the thread's explicit 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-custom-model"),
|
||||
commandId: CommandId.makeUnsafe("cmd-turn-start-unsupported-1"),
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
message: {
|
||||
messageId: asMessageId("user-message-custom-model"),
|
||||
messageId: asMessageId("user-message-unsupported-1"),
|
||||
role: "user",
|
||||
text: "hello",
|
||||
text: "first",
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => harness.startSession.mock.calls.length === 1);
|
||||
await waitFor(() => harness.sendTurn.mock.calls.length === 1);
|
||||
|
||||
expect(harness.startSession.mock.calls[0]?.[1]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "claude-sonnet-4-6",
|
||||
},
|
||||
});
|
||||
expect(harness.sendTurn.mock.calls[0]?.[0]).toMatchObject({
|
||||
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,
|
||||
}),
|
||||
);
|
||||
|
||||
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: "claude-sonnet-4-6",
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -662,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(
|
||||
@@ -819,7 +817,7 @@ describe("ProviderCommandReactor", () => {
|
||||
|
||||
it("does not inject derived model options when restarting claude on runtime mode changes", async () => {
|
||||
const harness = await createHarness({
|
||||
threadModel: "claude-opus-4-6",
|
||||
threadModelSelection: { provider: "claudeAgent", model: "claude-opus-4-6" },
|
||||
});
|
||||
const now = new Date().toISOString();
|
||||
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import {
|
||||
type ChatAttachment,
|
||||
CommandId,
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL,
|
||||
EventId,
|
||||
type ModelSelection,
|
||||
type OrchestrationEvent,
|
||||
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,6 +24,7 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { ServerSettingsService, deriveProviderStartOptions } from "../../serverSettings.ts";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -75,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 sameModelSelectionOptions = (
|
||||
left: ModelSelection | undefined,
|
||||
right: ModelSelection | 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)) {
|
||||
@@ -143,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,
|
||||
@@ -156,7 +151,6 @@ const make = Effect.gen(function* () {
|
||||
),
|
||||
);
|
||||
|
||||
const threadProviderOptions = new Map<string, ProviderStartOptions>();
|
||||
const threadModelSelections = new Map<string, ModelSelection>();
|
||||
|
||||
const appendProviderFailureActivity = (input: {
|
||||
@@ -215,7 +209,6 @@ const make = Effect.gen(function* () {
|
||||
createdAt: string,
|
||||
options?: {
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
},
|
||||
) {
|
||||
const readModel = yield* orchestrationEngine.getReadModel();
|
||||
@@ -258,16 +251,18 @@ const make = Effect.gen(function* () {
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly provider?: ProviderKind;
|
||||
}) =>
|
||||
providerService.startSession(threadId, {
|
||||
threadId,
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
modelSelection: desiredModelSelection,
|
||||
...(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) =>
|
||||
@@ -306,7 +301,7 @@ const make = Effect.gen(function* () {
|
||||
const shouldRestartForModelSelectionChange =
|
||||
currentProvider === "claudeAgent" &&
|
||||
requestedModelSelection !== undefined &&
|
||||
!sameModelSelectionOptions(previousModelSelection, requestedModelSelection);
|
||||
!Equal.equals(previousModelSelection, requestedModelSelection);
|
||||
|
||||
if (
|
||||
!runtimeModeChanged &&
|
||||
@@ -359,7 +354,6 @@ const make = Effect.gen(function* () {
|
||||
readonly messageText: string;
|
||||
readonly attachments?: ReadonlyArray<ChatAttachment>;
|
||||
readonly modelSelection?: ModelSelection;
|
||||
readonly providerOptions?: ProviderStartOptions;
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly createdAt: string;
|
||||
}) {
|
||||
@@ -367,13 +361,11 @@ const make = Effect.gen(function* () {
|
||||
if (!thread) {
|
||||
return;
|
||||
}
|
||||
yield* ensureSessionForThread(input.threadId, input.createdAt, {
|
||||
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
|
||||
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
|
||||
});
|
||||
if (input.providerOptions !== undefined) {
|
||||
threadProviderOptions.set(input.threadId, input.providerOptions);
|
||||
}
|
||||
yield* ensureSessionForThread(
|
||||
input.threadId,
|
||||
input.createdAt,
|
||||
input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {},
|
||||
);
|
||||
if (input.modelSelection !== undefined) {
|
||||
threadModelSelections.set(input.threadId, input.modelSelection);
|
||||
}
|
||||
@@ -388,14 +380,16 @@ const make = Effect.gen(function* () {
|
||||
activeSession === undefined
|
||||
? "in-session"
|
||||
: (yield* providerService.getCapabilities(activeSession.provider)).sessionModelSwitch;
|
||||
const requestedModelSelection =
|
||||
input.modelSelection ?? threadModelSelections.get(input.threadId) ?? thread.modelSelection;
|
||||
const modelForTurn =
|
||||
sessionModelSwitch === "unsupported"
|
||||
? input.modelSelection
|
||||
? activeSession?.model !== undefined
|
||||
? {
|
||||
...input.modelSelection,
|
||||
model: activeSession?.model ?? input.modelSelection.model,
|
||||
...requestedModelSelection,
|
||||
model: activeSession.model,
|
||||
}
|
||||
: undefined
|
||||
: requestedModelSelection
|
||||
: input.modelSelection;
|
||||
|
||||
yield* providerService.sendTurn({
|
||||
@@ -440,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) =>
|
||||
@@ -518,9 +515,6 @@ const make = Effect.gen(function* () {
|
||||
...(event.payload.modelSelection !== undefined
|
||||
? { modelSelection: event.payload.modelSelection }
|
||||
: {}),
|
||||
...(event.payload.providerOptions !== undefined
|
||||
? { providerOptions: event.payload.providerOptions }
|
||||
: {}),
|
||||
interactionMode: event.payload.interactionMode,
|
||||
createdAt: event.payload.createdAt,
|
||||
}).pipe(
|
||||
@@ -686,14 +680,12 @@ const make = Effect.gen(function* () {
|
||||
if (!thread?.session || thread.session.status === "stopped") {
|
||||
return;
|
||||
}
|
||||
const cachedProviderOptions = threadProviderOptions.get(event.payload.threadId);
|
||||
const cachedModelSelection = threadModelSelections.get(event.payload.threadId);
|
||||
yield* ensureSessionForThread(event.payload.threadId, event.occurredAt, {
|
||||
...(cachedProviderOptions !== undefined
|
||||
? { providerOptions: cachedProviderOptions }
|
||||
: {}),
|
||||
...(cachedModelSelection !== undefined ? { modelSelection: cachedModelSelection } : {}),
|
||||
});
|
||||
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),
|
||||
);
|
||||
@@ -1357,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(
|
||||
@@ -1371,7 +1386,6 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
text: "stream please",
|
||||
attachments: [],
|
||||
},
|
||||
assistantDeliveryMode: "streaming",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
runtimeMode: "approval-required",
|
||||
createdAt: now,
|
||||
|
||||
@@ -13,25 +13,25 @@ import {
|
||||
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;
|
||||
@@ -537,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,
|
||||
@@ -1048,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) {
|
||||
@@ -1256,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);
|
||||
|
||||
@@ -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"],
|
||||
@@ -330,10 +329,6 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
|
||||
...(command.modelSelection !== undefined
|
||||
? { modelSelection: command.modelSelection }
|
||||
: {}),
|
||||
...(command.providerOptions !== undefined
|
||||
? { providerOptions: command.providerOptions }
|
||||
: {}),
|
||||
assistantDeliveryMode: command.assistantDeliveryMode ?? DEFAULT_ASSISTANT_DELIVERY_MODE,
|
||||
runtimeMode: targetThread.runtimeMode,
|
||||
interactionMode: targetThread.interactionMode,
|
||||
...(sourceProposedPlan !== undefined ? { sourceProposedPlan } : {}),
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { ModelSelection, ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
PersistenceDecodeError,
|
||||
toPersistenceDecodeError,
|
||||
toPersistenceSqlError,
|
||||
} from "../Errors.ts";
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionProjectInput,
|
||||
GetProjectionProjectInput,
|
||||
@@ -16,42 +12,14 @@ import {
|
||||
type ProjectionProjectRepositoryShape,
|
||||
} from "../Services/ProjectionProjects.ts";
|
||||
|
||||
const ProjectionProjectDbRow = Schema.Struct({
|
||||
projectId: ProjectionProject.fields.projectId,
|
||||
title: ProjectionProject.fields.title,
|
||||
workspaceRoot: ProjectionProject.fields.workspaceRoot,
|
||||
defaultProvider: Schema.NullOr(Schema.Literals(["codex", "claudeAgent"])),
|
||||
defaultModel: Schema.NullOr(Schema.String),
|
||||
defaultModelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
createdAt: ProjectionProject.fields.createdAt,
|
||||
updatedAt: ProjectionProject.fields.updatedAt,
|
||||
deletedAt: ProjectionProject.fields.deletedAt,
|
||||
});
|
||||
const ProjectionProjectDbRow = ProjectionProject.mapFields(
|
||||
Struct.assign({
|
||||
defaultModelSelection: Schema.NullOr(Schema.fromJsonString(ModelSelection)),
|
||||
scripts: Schema.fromJsonString(Schema.Array(ProjectScript)),
|
||||
}),
|
||||
);
|
||||
type ProjectionProjectDbRow = typeof ProjectionProjectDbRow.Type;
|
||||
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
function decodeDefaultModelSelection(
|
||||
row: ProjectionProjectDbRow,
|
||||
): Effect.Effect<ProjectionProject["defaultModelSelection"], PersistenceDecodeError> {
|
||||
if (row.defaultProvider === null || row.defaultModel === null) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: row.defaultProvider,
|
||||
model: row.defaultModel,
|
||||
...(row.defaultModelOptions !== null ? { options: row.defaultModelOptions } : {}),
|
||||
}),
|
||||
catch: (error) =>
|
||||
toPersistenceDecodeError("ProjectionProjectRepository.decodeDefaultModelSelection")(
|
||||
error as Schema.SchemaError,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -63,9 +31,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
project_id,
|
||||
title,
|
||||
workspace_root,
|
||||
default_provider,
|
||||
default_model,
|
||||
default_model_options_json,
|
||||
default_model_selection_json,
|
||||
scripts_json,
|
||||
created_at,
|
||||
updated_at,
|
||||
@@ -75,13 +41,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.workspaceRoot},
|
||||
${row.defaultModelSelection?.provider ?? null},
|
||||
${row.defaultModelSelection?.model ?? null},
|
||||
${
|
||||
row.defaultModelSelection?.options != null
|
||||
? JSON.stringify(row.defaultModelSelection.options)
|
||||
: null
|
||||
},
|
||||
${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null},
|
||||
${JSON.stringify(row.scripts)},
|
||||
${row.createdAt},
|
||||
${row.updatedAt},
|
||||
@@ -91,9 +51,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
title = excluded.title,
|
||||
workspace_root = excluded.workspace_root,
|
||||
default_provider = excluded.default_provider,
|
||||
default_model = excluded.default_model,
|
||||
default_model_options_json = excluded.default_model_options_json,
|
||||
default_model_selection_json = excluded.default_model_selection_json,
|
||||
scripts_json = excluded.scripts_json,
|
||||
created_at = excluded.created_at,
|
||||
updated_at = excluded.updated_at,
|
||||
@@ -110,9 +68,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_provider AS "defaultProvider",
|
||||
default_model AS "defaultModel",
|
||||
default_model_options_json AS "defaultModelOptions",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -131,9 +87,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
workspace_root AS "workspaceRoot",
|
||||
default_provider AS "defaultProvider",
|
||||
default_model AS "defaultModel",
|
||||
default_model_options_json AS "defaultModelOptions",
|
||||
default_model_selection_json AS "defaultModelSelection",
|
||||
scripts_json AS "scripts",
|
||||
created_at AS "createdAt",
|
||||
updated_at AS "updatedAt",
|
||||
@@ -160,47 +114,11 @@ const makeProjectionProjectRepository = Effect.gen(function* () {
|
||||
const getById: ProjectionProjectRepositoryShape["getById"] = (input) =>
|
||||
getProjectionProjectRow(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.getById:query")),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) =>
|
||||
decodeDefaultModelSelection(row).pipe(
|
||||
Effect.map((defaultModelSelection) =>
|
||||
Option.some({
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listAll: ProjectionProjectRepositoryShape["listAll"] = () =>
|
||||
listProjectionProjectRows().pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionProjectRepository.listAll:query")),
|
||||
Effect.flatMap((rows) =>
|
||||
Effect.forEach(rows, (row) =>
|
||||
decodeDefaultModelSelection(row).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
workspaceRoot: row.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: row.scripts,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
})),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionProjectRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -38,9 +38,9 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly defaultModelOptions: string | null;
|
||||
readonly defaultModelSelection: string | null;
|
||||
}>`
|
||||
SELECT default_model_options_json AS "defaultModelOptions"
|
||||
SELECT default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
WHERE project_id = 'project-null-options'
|
||||
`;
|
||||
@@ -49,7 +49,13 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
return yield* Effect.fail(new Error("Expected projection_projects row to exist."));
|
||||
}
|
||||
|
||||
assert.strictEqual(row.defaultModelOptions, null);
|
||||
assert.strictEqual(
|
||||
row.defaultModelSelection,
|
||||
JSON.stringify({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
}),
|
||||
);
|
||||
|
||||
const persisted = yield* projects.getById({
|
||||
projectId: ProjectId.makeUnsafe("project-null-options"),
|
||||
@@ -61,7 +67,7 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("stores SQL NULL for missing thread model options", () =>
|
||||
it.effect("stores JSON for thread model options", () =>
|
||||
Effect.gen(function* () {
|
||||
const threads = yield* ProjectionThreadRepository;
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
@@ -85,9 +91,9 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
});
|
||||
|
||||
const rows = yield* sql<{
|
||||
readonly modelOptions: string | null;
|
||||
readonly modelSelection: string | null;
|
||||
}>`
|
||||
SELECT model_options_json AS "modelOptions"
|
||||
SELECT model_selection_json AS "modelSelection"
|
||||
FROM projection_threads
|
||||
WHERE thread_id = 'thread-null-options'
|
||||
`;
|
||||
@@ -96,7 +102,13 @@ projectionRepositoriesLayer("Projection repositories", (it) => {
|
||||
return yield* Effect.fail(new Error("Expected projection_threads row to exist."));
|
||||
}
|
||||
|
||||
assert.strictEqual(row.modelOptions, null);
|
||||
assert.strictEqual(
|
||||
row.modelSelection,
|
||||
JSON.stringify({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
}),
|
||||
);
|
||||
|
||||
const persisted = yield* threads.getById({
|
||||
threadId: ThreadId.makeUnsafe("thread-null-options"),
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
|
||||
import { Effect, Layer, Option, Schema } from "effect";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
import { toPersistenceDecodeError, toPersistenceSqlError } from "../Errors.ts";
|
||||
import { toPersistenceSqlError } from "../Errors.ts";
|
||||
import {
|
||||
DeleteProjectionThreadInput,
|
||||
GetProjectionThreadInput,
|
||||
@@ -12,54 +11,15 @@ import {
|
||||
ProjectionThreadRepository,
|
||||
type ProjectionThreadRepositoryShape,
|
||||
} from "../Services/ProjectionThreads.ts";
|
||||
import { ModelSelection } from "@t3tools/contracts";
|
||||
|
||||
const ProjectionThreadDbRow = Schema.Struct({
|
||||
threadId: ProjectionThread.fields.threadId,
|
||||
projectId: ProjectionThread.fields.projectId,
|
||||
title: ProjectionThread.fields.title,
|
||||
provider: Schema.Literals(["codex", "claudeAgent"]),
|
||||
model: Schema.String,
|
||||
modelOptions: Schema.NullOr(Schema.fromJsonString(Schema.Unknown)),
|
||||
runtimeMode: ProjectionThread.fields.runtimeMode,
|
||||
interactionMode: ProjectionThread.fields.interactionMode,
|
||||
branch: ProjectionThread.fields.branch,
|
||||
worktreePath: ProjectionThread.fields.worktreePath,
|
||||
latestTurnId: ProjectionThread.fields.latestTurnId,
|
||||
createdAt: ProjectionThread.fields.createdAt,
|
||||
updatedAt: ProjectionThread.fields.updatedAt,
|
||||
deletedAt: ProjectionThread.fields.deletedAt,
|
||||
});
|
||||
const ProjectionThreadDbRow = ProjectionThread.mapFields(
|
||||
Struct.assign({
|
||||
modelSelection: Schema.fromJsonString(ModelSelection),
|
||||
}),
|
||||
);
|
||||
type ProjectionThreadDbRow = typeof ProjectionThreadDbRow.Type;
|
||||
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
function decodeProjectionThread(row: ProjectionThreadDbRow) {
|
||||
return Effect.try({
|
||||
try: () => ({
|
||||
threadId: row.threadId,
|
||||
projectId: row.projectId,
|
||||
title: row.title,
|
||||
modelSelection: decodeModelSelectionSync({
|
||||
provider: row.provider,
|
||||
model: row.model,
|
||||
...(row.modelOptions !== null ? { options: row.modelOptions } : {}),
|
||||
}),
|
||||
runtimeMode: row.runtimeMode,
|
||||
interactionMode: row.interactionMode,
|
||||
branch: row.branch,
|
||||
worktreePath: row.worktreePath,
|
||||
latestTurnId: row.latestTurnId,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt,
|
||||
deletedAt: row.deletedAt,
|
||||
}),
|
||||
catch: (error) =>
|
||||
toPersistenceDecodeError("ProjectionThreadRepository.decodeProjectionThread")(
|
||||
error as Schema.SchemaError,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
@@ -71,9 +31,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
thread_id,
|
||||
project_id,
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json,
|
||||
model_selection_json,
|
||||
runtime_mode,
|
||||
interaction_mode,
|
||||
branch,
|
||||
@@ -87,9 +45,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
${row.threadId},
|
||||
${row.projectId},
|
||||
${row.title},
|
||||
${row.modelSelection.provider},
|
||||
${row.modelSelection.model},
|
||||
${row.modelSelection.options != null ? JSON.stringify(row.modelSelection.options) : null},
|
||||
${JSON.stringify(row.modelSelection)},
|
||||
${row.runtimeMode},
|
||||
${row.interactionMode},
|
||||
${row.branch},
|
||||
@@ -103,9 +59,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
DO UPDATE SET
|
||||
project_id = excluded.project_id,
|
||||
title = excluded.title,
|
||||
provider = excluded.provider,
|
||||
model = excluded.model,
|
||||
model_options_json = excluded.model_options_json,
|
||||
model_selection_json = excluded.model_selection_json,
|
||||
runtime_mode = excluded.runtime_mode,
|
||||
interaction_mode = excluded.interaction_mode,
|
||||
branch = excluded.branch,
|
||||
@@ -126,9 +80,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json AS "modelOptions",
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -151,9 +103,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
thread_id AS "threadId",
|
||||
project_id AS "projectId",
|
||||
title,
|
||||
provider,
|
||||
model,
|
||||
model_options_json AS "modelOptions",
|
||||
model_selection_json AS "modelSelection",
|
||||
runtime_mode AS "runtimeMode",
|
||||
interaction_mode AS "interactionMode",
|
||||
branch,
|
||||
@@ -185,18 +135,11 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
|
||||
const getById: ProjectionThreadRepositoryShape["getById"] = (input) =>
|
||||
getProjectionThreadRow(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.getById:query")),
|
||||
Effect.flatMap(
|
||||
Option.match({
|
||||
onNone: () => Effect.succeed(Option.none()),
|
||||
onSome: (row) => decodeProjectionThread(row).pipe(Effect.map(Option.some)),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const listByProjectId: ProjectionThreadRepositoryShape["listByProjectId"] = (input) =>
|
||||
listProjectionThreadRows(input).pipe(
|
||||
Effect.mapError(toPersistenceSqlError("ProjectionThreadRepository.listByProjectId:query")),
|
||||
Effect.flatMap((rows) => Effect.forEach(rows, decodeProjectionThread)),
|
||||
);
|
||||
|
||||
const deleteById: ProjectionThreadRepositoryShape["deleteById"] = (input) =>
|
||||
|
||||
@@ -91,12 +91,14 @@ export interface RunMigrationsOptions {
|
||||
export const runMigrations = ({ toMigrationInclusive }: RunMigrationsOptions = {}) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Effect.log(
|
||||
toMigrationInclusive !== undefined
|
||||
? `Running migrations 1 through ${toMigrationInclusive}...`
|
||||
: "Running migrations...",
|
||||
toMigrationInclusive === undefined
|
||||
? "Running all migrations..."
|
||||
: `Running migrations 1 through ${toMigrationInclusive}...`,
|
||||
);
|
||||
const executedMigrations = yield* run({ loader: makeMigrationLoader(toMigrationInclusive) });
|
||||
yield* Effect.log("Migrations ran successfully");
|
||||
yield* Effect.log("Migrations ran successfully").pipe(
|
||||
Effect.annotateLogs({ migrations: executedMigrations.map(([id, name]) => `${id}_${name}`) }),
|
||||
);
|
||||
return executedMigrations;
|
||||
});
|
||||
|
||||
|
||||
@@ -114,6 +114,20 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
'{"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',
|
||||
@@ -128,6 +142,20 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
'{"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',
|
||||
@@ -141,6 +169,20 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
'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"}',
|
||||
'{}'
|
||||
)
|
||||
`;
|
||||
}
|
||||
@@ -152,37 +194,53 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
{
|
||||
const projectRows = yield* sql<{
|
||||
readonly projectId: string;
|
||||
readonly defaultProvider: string | null;
|
||||
readonly defaultModelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
project_id AS "projectId",
|
||||
default_provider AS "defaultProvider"
|
||||
default_model_selection_json AS "defaultModelSelection"
|
||||
FROM projection_projects
|
||||
ORDER BY project_id
|
||||
`;
|
||||
assert.deepStrictEqual(projectRows, [
|
||||
{ projectId: "project-claude", defaultProvider: "claudeAgent" },
|
||||
{ projectId: "project-codex", defaultProvider: "codex" },
|
||||
{ projectId: "project-null", defaultProvider: null },
|
||||
{
|
||||
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 provider: string | null;
|
||||
readonly modelOptions: string | null;
|
||||
readonly modelSelection: string | null;
|
||||
}>`
|
||||
SELECT
|
||||
thread_id AS "threadId",
|
||||
provider,
|
||||
model_options_json AS "modelOptions"
|
||||
model_selection_json AS "modelSelection"
|
||||
FROM projection_threads
|
||||
ORDER BY thread_id
|
||||
`;
|
||||
assert.deepStrictEqual(threadRows, [
|
||||
{ threadId: "thread-claude", provider: "claudeAgent", modelOptions: null },
|
||||
{ threadId: "thread-codex", provider: "codex", modelOptions: null },
|
||||
{ threadId: "thread-legacy-options", provider: "claudeAgent", modelOptions: null },
|
||||
{ threadId: "thread-session", provider: "claudeAgent", modelOptions: null },
|
||||
{
|
||||
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<{
|
||||
@@ -210,6 +268,22 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
});
|
||||
|
||||
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",
|
||||
@@ -229,7 +303,26 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(JSON.parse(eventRows[2]!.payloadJson), {
|
||||
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",
|
||||
@@ -242,6 +335,22 @@ layer("016_CanonicalizeModelSelections", (it) => {
|
||||
},
|
||||
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",
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -6,84 +6,61 @@ export default Effect.gen(function* () {
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_projects
|
||||
ADD COLUMN default_provider TEXT
|
||||
ADD COLUMN default_model_selection_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET default_provider = CASE
|
||||
SET default_model_selection_json = CASE
|
||||
WHEN default_model IS NULL THEN NULL
|
||||
WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
ELSE json_object(
|
||||
'provider',
|
||||
CASE
|
||||
WHEN lower(default_model) LIKE '%claude%' THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'model',
|
||||
default_model
|
||||
)
|
||||
END
|
||||
WHERE default_provider IS NULL
|
||||
WHERE default_model_selection_json IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN provider TEXT
|
||||
ADD COLUMN model_selection_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET provider = COALESCE(
|
||||
(
|
||||
SELECT provider_name
|
||||
FROM projection_thread_sessions
|
||||
WHERE projection_thread_sessions.thread_id = projection_threads.thread_id
|
||||
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'
|
||||
),
|
||||
CASE
|
||||
WHEN lower(model) LIKE '%claude%' THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END,
|
||||
'codex'
|
||||
'model',
|
||||
model
|
||||
)
|
||||
WHERE provider IS NULL
|
||||
WHERE model_selection_json IS NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_projects
|
||||
ADD COLUMN default_model_options_json TEXT
|
||||
DROP COLUMN default_model
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
ALTER TABLE projection_threads
|
||||
ADD COLUMN model_options_json TEXT
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_projects
|
||||
SET
|
||||
default_model_options_json = CASE
|
||||
WHEN default_model_options_json IS NULL THEN NULL
|
||||
WHEN json_valid(default_model_options_json) = 0 THEN default_model_options_json
|
||||
WHEN json_type(default_model_options_json, '$.codex') IS NOT NULL
|
||||
OR json_type(default_model_options_json, '$.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN default_provider = 'claudeAgent'
|
||||
THEN json_extract(default_model_options_json, '$.claudeAgent')
|
||||
ELSE json_extract(default_model_options_json, '$.codex')
|
||||
END
|
||||
ELSE default_model_options_json
|
||||
END
|
||||
WHERE default_model IS NOT NULL
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
UPDATE projection_threads
|
||||
SET
|
||||
model_options_json = CASE
|
||||
WHEN model_options_json IS NULL THEN NULL
|
||||
WHEN json_valid(model_options_json) = 0 THEN model_options_json
|
||||
WHEN json_type(model_options_json, '$.codex') IS NOT NULL
|
||||
OR json_type(model_options_json, '$.claudeAgent') IS NOT NULL
|
||||
THEN CASE
|
||||
WHEN provider = 'claudeAgent'
|
||||
THEN json_extract(model_options_json, '$.claudeAgent')
|
||||
ELSE json_extract(model_options_json, '$.codex')
|
||||
END
|
||||
ELSE model_options_json
|
||||
END
|
||||
DROP COLUMN model
|
||||
`;
|
||||
|
||||
yield* sql`
|
||||
@@ -112,29 +89,47 @@ export default Effect.gen(function* () {
|
||||
'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_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
|
||||
) = 'claudeAgent'
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.defaultModelOptions.codex'))
|
||||
)
|
||||
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'))
|
||||
@@ -183,16 +178,34 @@ export default Effect.gen(function* () {
|
||||
WHEN lower(json_extract(payload_json, '$.model')) LIKE '%claude%'
|
||||
THEN 'claudeAgent'
|
||||
ELSE 'codex'
|
||||
END
|
||||
END
|
||||
) = 'claudeAgent'
|
||||
THEN json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.claudeAgent'))
|
||||
)
|
||||
ELSE json_object(
|
||||
'options',
|
||||
json(json_extract(payload_json, '$.modelOptions.codex'))
|
||||
)
|
||||
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
|
||||
@@ -206,4 +219,17 @@ export default Effect.gen(function* () {
|
||||
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
|
||||
`;
|
||||
});
|
||||
@@ -38,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,
|
||||
@@ -158,6 +156,7 @@ interface ClaudeSessionContext {
|
||||
readonly inFlightTools: Map<number, ToolInFlight>;
|
||||
turnState: ClaudeTurnState | undefined;
|
||||
lastKnownContextWindow: number | undefined;
|
||||
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
|
||||
lastAssistantUuid: string | undefined;
|
||||
lastThreadStartedId: string | undefined;
|
||||
stopped: boolean;
|
||||
@@ -211,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 (
|
||||
@@ -512,21 +520,16 @@ const CLAUDE_SETTING_SOURCES = [
|
||||
] as const satisfies ReadonlyArray<SettingSource>;
|
||||
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions(
|
||||
"claudeAgent",
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined,
|
||||
);
|
||||
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.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined,
|
||||
)
|
||||
requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0
|
||||
? "ultrathink"
|
||||
: requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
: requestedEffort && hasEffortLevel(caps, requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
|
||||
@@ -1374,14 +1377,33 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const resultUsage =
|
||||
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
|
||||
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
|
||||
const usageSnapshot = normalizeClaudeTokenUsage(
|
||||
resultUsage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
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) {
|
||||
@@ -2057,6 +2079,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2088,6 +2111,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
context.lastKnownTokenUsage = normalizedUsage;
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -2706,24 +2730,13 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
const providerOptions = input.providerOptions?.claudeAgent;
|
||||
const modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const requestedEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
modelSelection?.options?.effort ?? null,
|
||||
);
|
||||
const supportedEffortOptions = getReasoningEffortOptions(
|
||||
"claudeAgent",
|
||||
modelSelection?.model,
|
||||
);
|
||||
const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null);
|
||||
const caps = getModelCapabilities("claudeAgent", modelSelection?.model);
|
||||
const effort =
|
||||
requestedEffort && supportedEffortOptions.includes(requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
const fastMode =
|
||||
modelSelection?.options?.fastMode === true &&
|
||||
supportsClaudeFastMode(modelSelection?.model);
|
||||
requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
const thinking =
|
||||
typeof modelSelection?.options?.thinking === "boolean" &&
|
||||
supportsClaudeThinkingToggle(modelSelection?.model)
|
||||
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
|
||||
? modelSelection.options.thinking
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
|
||||
@@ -2806,6 +2819,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
inFlightTools,
|
||||
turnState: undefined,
|
||||
lastKnownContextWindow: undefined,
|
||||
lastKnownTokenUsage: undefined,
|
||||
lastAssistantUuid: resumeState?.resumeSessionAt,
|
||||
lastThreadStartedId: undefined,
|
||||
stopped: false,
|
||||
|
||||
@@ -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);
|
||||
@@ -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),
|
||||
@@ -1838,6 +1840,10 @@ describe("WebSocket Server", () => {
|
||||
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");
|
||||
@@ -1846,6 +1852,10 @@ describe("WebSocket Server", () => {
|
||||
actionId: "client-action-1",
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
},
|
||||
expect.objectContaining({
|
||||
actionId: "client-action-1",
|
||||
@@ -1901,6 +1911,10 @@ describe("WebSocket Server", () => {
|
||||
actionId: "client-action-2",
|
||||
cwd: "/test",
|
||||
action: "commit",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
});
|
||||
const progressPush = await waitForPush(initiatingWs, WS_CHANNELS.gitActionProgress);
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -878,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,
|
||||
@@ -887,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);
|
||||
@@ -895,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({
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
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,
|
||||
getCustomModelsForProvider,
|
||||
getDefaultCustomModelsForProvider,
|
||||
getProviderStartOptions,
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
normalizeCustomModelSlugs,
|
||||
patchCustomModels,
|
||||
resolveAppModelSelectionState,
|
||||
resolveAppModelSelection,
|
||||
} from "./appSettings";
|
||||
} from "./modelSelection";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
@@ -131,35 +131,6 @@ describe("provider-specific custom models", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getProviderStartOptions", () => {
|
||||
it("returns only populated provider overrides", () => {
|
||||
expect(
|
||||
getProviderStartOptions({
|
||||
claudeBinaryPath: "/usr/local/bin/claude",
|
||||
codexBinaryPath: "",
|
||||
codexHomePath: "/Users/you/.codex",
|
||||
}),
|
||||
).toEqual({
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
},
|
||||
codex: {
|
||||
homePath: "/Users/you/.codex",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns undefined when no provider overrides are configured", () => {
|
||||
expect(
|
||||
getProviderStartOptions({
|
||||
claudeBinaryPath: "",
|
||||
codexBinaryPath: "",
|
||||
codexHomePath: "",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider-indexed custom model settings", () => {
|
||||
const settings = {
|
||||
customCodexModels: ["custom/codex-model"],
|
||||
@@ -239,29 +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({
|
||||
claudeBinaryPath: "",
|
||||
codexBinaryPath: "/usr/local/bin/codex",
|
||||
codexHomePath: "",
|
||||
defaultThreadEnvMode: "local",
|
||||
confirmThreadDelete: false,
|
||||
enableAssistantStreaming: false,
|
||||
sidebarProjectSortOrder: DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
sidebarThreadSortOrder: DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
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
-275
@@ -1,290 +1,50 @@
|
||||
import { useCallback } from "react";
|
||||
import { Option, Schema } from "effect";
|
||||
/**
|
||||
* 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 {
|
||||
TrimmedNonEmptyString,
|
||||
type ProviderKind,
|
||||
type ProviderStartOptions,
|
||||
} from "@t3tools/contracts";
|
||||
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";
|
||||
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";
|
||||
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({
|
||||
claudeBinaryPath: Schema.String.check(Schema.isMaxLength(4096)).pipe(withDefaults(() => "")),
|
||||
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)),
|
||||
diffWordWrap: Schema.Boolean.pipe(withDefaults(() => false)),
|
||||
enableAssistantStreaming: 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)),
|
||||
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),
|
||||
};
|
||||
}
|
||||
|
||||
export function getProviderStartOptions(
|
||||
settings: Pick<AppSettings, "claudeBinaryPath" | "codexBinaryPath" | "codexHomePath">,
|
||||
): ProviderStartOptions | undefined {
|
||||
const providerOptions: ProviderStartOptions = {
|
||||
...(settings.codexBinaryPath || settings.codexHomePath
|
||||
? {
|
||||
codex: {
|
||||
...(settings.codexBinaryPath ? { binaryPath: settings.codexBinaryPath } : {}),
|
||||
...(settings.codexHomePath ? { homePath: settings.codexHomePath } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(settings.claudeBinaryPath
|
||||
? {
|
||||
claudeAgent: {
|
||||
binaryPath: settings.claudeBinaryPath,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
|
||||
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
|
||||
}
|
||||
// ── 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({});
|
||||
@@ -90,6 +90,7 @@ interface UserRowMeasurement {
|
||||
}
|
||||
|
||||
interface MountedChatView {
|
||||
[Symbol.asyncDispose]: () => Promise<void>;
|
||||
cleanup: () => Promise<void>;
|
||||
measureUserRow: (targetMessageId: MessageId) => Promise<UserRowMeasurement>;
|
||||
setViewport: (viewport: ViewportSpec) => Promise<void>;
|
||||
@@ -116,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" },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -765,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);
|
||||
@@ -826,7 +839,8 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelection: null,
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
useStore.setState({
|
||||
projects: [],
|
||||
@@ -1491,14 +1505,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("snapshots sticky codex settings into a new draft thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1523,13 +1540,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
@@ -1538,14 +1558,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("hydrates the provider alongside a sticky claude model", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
stickyModelSelectionByProvider: {
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "claudeAgent",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1570,16 +1593,18 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const newThreadId = newThreadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[newThreadId]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
options: {
|
||||
effort: "max",
|
||||
fastMode: true,
|
||||
modelSelectionByProvider: {
|
||||
claudeAgent: {
|
||||
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();
|
||||
}
|
||||
@@ -1615,14 +1640,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
|
||||
it("prefers draft state over sticky composer settings and defaults", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
stickyModelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "medium",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
stickyActiveProvider: "codex",
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
@@ -1647,13 +1675,16 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
const threadId = threadPath.slice(1) as ThreadId;
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
|
||||
useComposerDraftStore.getState().setModelSelection(threadId, {
|
||||
@@ -1673,14 +1704,17 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
"New-thread should reuse the existing project draft thread.",
|
||||
);
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toMatchObject({
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
modelSelectionByProvider: {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
activeProvider: "codex",
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
|
||||
@@ -24,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";
|
||||
@@ -121,19 +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,
|
||||
getProviderStartOptions,
|
||||
resolveAppModelSelection,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
} from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
type DraftThreadEnvMode,
|
||||
type PersistedComposerImageAttachment,
|
||||
useComposerDraftStore,
|
||||
useEffectiveComposerModelState,
|
||||
useComposerThreadDraft,
|
||||
} from "../composerDraftStore";
|
||||
import {
|
||||
@@ -197,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;
|
||||
@@ -595,7 +596,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
]);
|
||||
|
||||
const sessionProvider = activeThread?.session?.provider ?? null;
|
||||
const selectedProviderByThreadId = composerDraft.modelSelection?.provider ?? null;
|
||||
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
|
||||
const threadProvider =
|
||||
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
|
||||
const hasThreadStarted = Boolean(
|
||||
@@ -609,34 +610,23 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: null;
|
||||
const selectedProvider: ProviderKind =
|
||||
lockedProvider ?? selectedProviderByThreadId ?? threadProvider ?? "codex";
|
||||
const baseThreadModel = resolveModelSlugForProvider(
|
||||
selectedProvider,
|
||||
activeThread?.modelSelection.model ??
|
||||
activeProject?.defaultModelSelection?.model ??
|
||||
getDefaultModel(selectedProvider),
|
||||
);
|
||||
const customModelsByProvider = useMemo(() => getCustomModelsByProvider(settings), [settings]);
|
||||
const selectedModel = useMemo(() => {
|
||||
const draftModel = composerDraft.modelSelection?.model;
|
||||
if (!draftModel) {
|
||||
return baseThreadModel;
|
||||
}
|
||||
return resolveAppModelSelection(selectedProvider, customModelsByProvider, draftModel);
|
||||
}, [
|
||||
baseThreadModel,
|
||||
composerDraft.modelSelection?.model,
|
||||
customModelsByProvider,
|
||||
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadId,
|
||||
selectedProvider,
|
||||
]);
|
||||
threadModelSelection: activeThread?.modelSelection,
|
||||
projectModelSelection: activeProject?.defaultModelSelection,
|
||||
customModelsByProvider,
|
||||
});
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
prompt,
|
||||
modelOptions: composerDraft.modelSelection?.options,
|
||||
modelOptions: composerModelOptions,
|
||||
}),
|
||||
[composerDraft.modelSelection?.options, prompt, selectedModel, selectedProvider],
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider],
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
@@ -648,11 +638,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}),
|
||||
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
|
||||
);
|
||||
const providerOptionsForDispatch = useMemo(() => getProviderStartOptions(settings), [settings]);
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const modelOptionsByProvider = useMemo(
|
||||
() => getCustomModelOptionsByProvider(settings),
|
||||
[settings],
|
||||
() => getCustomModelOptionsByProvider(settings, selectedProvider, selectedModel),
|
||||
[settings, selectedProvider, selectedModel],
|
||||
);
|
||||
const selectedModelForPickerWithCustomFallback = useMemo(() => {
|
||||
const currentOptions = modelOptionsByProvider[selectedProvider];
|
||||
@@ -2469,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,
|
||||
});
|
||||
@@ -2654,8 +2644,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
attachments: turnAttachments,
|
||||
},
|
||||
modelSelection: selectedModelSelection,
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
interactionMode,
|
||||
createdAt: messageCreatedAt,
|
||||
@@ -2891,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,
|
||||
});
|
||||
@@ -2935,8 +2924,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: selectedModelSelection,
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
interactionMode: nextInteractionMode,
|
||||
...(nextInteractionMode === "default" && activeProposedPlan
|
||||
@@ -2982,11 +2969,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
setComposerDraftInteractionMode,
|
||||
setThreadError,
|
||||
settings.enableAssistantStreaming,
|
||||
selectedModel,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -3011,6 +2998,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
|
||||
const outgoingImplementationPrompt = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
effort: selectedPromptEffort,
|
||||
text: implementationPrompt,
|
||||
});
|
||||
@@ -3050,8 +3038,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: selectedModelSelection,
|
||||
...(providerOptionsForDispatch ? { providerOptions: providerOptionsForDispatch } : {}),
|
||||
assistantDeliveryMode: settings.enableAssistantStreaming ? "streaming" : "buffered",
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
createdAt,
|
||||
@@ -3102,10 +3088,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
providerOptionsForDispatch,
|
||||
selectedProvider,
|
||||
settings.enableAssistantStreaming,
|
||||
syncServerReadModel,
|
||||
selectedModel,
|
||||
]);
|
||||
|
||||
const onProviderModelSelect = useCallback(
|
||||
@@ -3116,14 +3101,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
const resolvedModel = resolveAppModelSelection(provider, customModelsByProvider, model);
|
||||
const existingModelSelection = composerDraft.modelSelection;
|
||||
const preserveOptions =
|
||||
existingModelSelection?.provider === provider &&
|
||||
existingModelSelection.options !== undefined;
|
||||
const nextModelSelection: ModelSelection = {
|
||||
provider,
|
||||
model: resolvedModel,
|
||||
...(preserveOptions ? { options: existingModelSelection.options } : {}),
|
||||
};
|
||||
setComposerDraftModelSelection(activeThread.id, nextModelSelection);
|
||||
setStickyComposerModelSelection(nextModelSelection);
|
||||
@@ -3131,7 +3111,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
composerDraft.modelSelection,
|
||||
lockedProvider,
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModelSelection,
|
||||
@@ -3159,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(
|
||||
|
||||
@@ -261,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 }));
|
||||
@@ -347,13 +347,16 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
progress.lastOutputLine = null;
|
||||
break;
|
||||
case "action_finished":
|
||||
progress.phaseStartedAtMs = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
break;
|
||||
// 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":
|
||||
progress.phaseStartedAtMs = null;
|
||||
progress.hookStartedAtMs = null;
|
||||
break;
|
||||
// Same reasoning as action_finished — let the HTTP error handler
|
||||
// manage the final toast state to avoid a flash of bare title.
|
||||
return;
|
||||
}
|
||||
|
||||
updateActiveProgressToast();
|
||||
|
||||
@@ -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" },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
getFallbackThreadIdAfterDelete,
|
||||
getVisibleThreadsForProject,
|
||||
getProjectSortTimestamp,
|
||||
hasUnseenCompletion,
|
||||
@@ -343,6 +344,7 @@ describe("getVisibleThreadsForProject", () => {
|
||||
});
|
||||
|
||||
function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
const { defaultModelSelection, ...rest } = overrides;
|
||||
return {
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Project",
|
||||
@@ -350,13 +352,13 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
defaultModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
...overrides?.defaultModelSelection,
|
||||
...defaultModelSelection,
|
||||
},
|
||||
expanded: true,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
scripts: [],
|
||||
...overrides,
|
||||
...rest,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -515,6 +517,76 @@ describe("sortThreadsForSidebar", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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 = [
|
||||
|
||||
@@ -279,6 +279,33 @@ export function sortThreadsForSidebar<
|
||||
});
|
||||
}
|
||||
|
||||
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[],
|
||||
|
||||
@@ -91,6 +91,7 @@ import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
|
||||
import { isNonEmpty as isNonEmptyString } from "effect/String";
|
||||
import {
|
||||
getFallbackThreadIdAfterDelete,
|
||||
getVisibleThreadsForProject,
|
||||
resolveProjectStatusIndicator,
|
||||
resolveSidebarNewThreadEnvMode,
|
||||
@@ -715,8 +716,12 @@ export default function Sidebar() {
|
||||
|
||||
const allDeletedIds = deletedIds ?? new Set<ThreadId>();
|
||||
const shouldNavigateToFallback = routeThreadId === threadId;
|
||||
const fallbackThreadId =
|
||||
threads.find((entry) => entry.id !== threadId && !allDeletedIds.has(entry.id))?.id ?? null;
|
||||
const fallbackThreadId = getFallbackThreadIdAfterDelete({
|
||||
threads,
|
||||
deletedThreadId: threadId,
|
||||
deletedThreadIds: allDeletedIds,
|
||||
sortOrder: appSettings.sidebarThreadSortOrder,
|
||||
});
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
@@ -763,6 +768,7 @@ export default function Sidebar() {
|
||||
}
|
||||
},
|
||||
[
|
||||
appSettings.sidebarThreadSortOrder,
|
||||
clearComposerDraftForThread,
|
||||
clearProjectDraftThreadById,
|
||||
clearTerminalState,
|
||||
|
||||
@@ -1,198 +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: [],
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
options: {
|
||||
...(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().stickyModelSelection).toMatchObject({
|
||||
provider: "claudeAgent",
|
||||
options: {
|
||||
effort: "max",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,274 +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.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
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.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
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,194 +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: [],
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
...(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().stickyModelSelection).toMatchObject({
|
||||
provider: "codex",
|
||||
options: {
|
||||
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: [],
|
||||
modelSelection: null,
|
||||
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]?.modelSelection).toEqual(
|
||||
{
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,150 +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.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
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 draft = useComposerThreadDraft(props.threadId);
|
||||
const modelOptions =
|
||||
draft.modelSelection?.provider === PROVIDER ? draft.modelSelection.options : null;
|
||||
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,37 +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: [],
|
||||
modelSelection: {
|
||||
provider,
|
||||
model: props?.model ?? "claude-opus-4-6",
|
||||
...(props?.modelOptions
|
||||
? {
|
||||
options:
|
||||
provider === "codex" ? props.modelOptions.codex : props.modelOptions.claudeAgent,
|
||||
}
|
||||
: {}),
|
||||
modelSelectionByProvider: {
|
||||
[provider]: {
|
||||
provider,
|
||||
model,
|
||||
...(props?.modelSelection?.options ? { options: props.modelSelection.options } : {}),
|
||||
},
|
||||
},
|
||||
activeProvider: provider,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
@@ -48,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}
|
||||
@@ -55,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()}
|
||||
@@ -72,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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -87,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");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
);
|
||||
});
|
||||
@@ -23,8 +23,10 @@ describe("getComposerProviderState", () => {
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
codex: {
|
||||
reasoningEffort: "low",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -38,6 +40,47 @@ describe("getComposerProviderState", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves codex fast mode when it is the only active option", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
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", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
@@ -59,7 +102,9 @@ describe("getComposerProviderState", () => {
|
||||
model: "claude-sonnet-4-6",
|
||||
prompt: "Ultrathink:\nInvestigate this failure",
|
||||
modelOptions: {
|
||||
effort: "medium",
|
||||
claudeAgent: {
|
||||
effort: "medium",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -81,8 +126,10 @@ describe("getComposerProviderState", () => {
|
||||
model: "claude-haiku-4-5",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
claudeAgent: {
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -94,4 +141,45 @@ describe("getComposerProviderState", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves Claude fast mode when it is the only active option", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,35 +1,32 @@
|
||||
import {
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type ModelSlug,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
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;
|
||||
model: ModelSlug;
|
||||
prompt: string;
|
||||
modelOptions: ModelSelection["options"] | null | undefined;
|
||||
modelOptions: ProviderModelOptions | null | undefined;
|
||||
};
|
||||
|
||||
export type ComposerProviderState = {
|
||||
provider: ProviderKind;
|
||||
promptEffort: string | null;
|
||||
modelOptionsForDispatch: ModelSelection["options"] | undefined;
|
||||
modelOptionsForDispatch: ProviderModelOptions[ProviderKind] | undefined;
|
||||
composerFrameClassName?: string;
|
||||
composerSurfaceClassName?: string;
|
||||
modelPickerIconClassName?: string;
|
||||
@@ -40,82 +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 asCodexModelOptions(
|
||||
modelOptions: ModelSelection["options"] | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
return modelOptions && "reasoningEffort" in modelOptions ? modelOptions : undefined;
|
||||
}
|
||||
function getProviderStateFromCapabilities(
|
||||
input: ComposerProviderStateInput,
|
||||
): ComposerProviderState {
|
||||
const { provider, model, prompt, modelOptions } = input;
|
||||
const caps = getModelCapabilities(provider, model);
|
||||
const providerOptions = modelOptions?.[provider];
|
||||
|
||||
function asClaudeModelOptions(
|
||||
modelOptions: ModelSelection["options"] | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
return modelOptions && ("effort" in modelOptions || "thinking" in modelOptions)
|
||||
? modelOptions
|
||||
: undefined;
|
||||
// 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 codexModelOptions = asCodexModelOptions(modelOptions);
|
||||
const promptEffort =
|
||||
resolveReasoningEffortForProvider("codex", codexModelOptions?.reasoningEffort) ??
|
||||
getDefaultReasoningEffort("codex");
|
||||
const normalizedCodexOptions = normalizeCodexModelOptions(codexModelOptions);
|
||||
|
||||
return {
|
||||
provider: "codex",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedCodexOptions,
|
||||
};
|
||||
},
|
||||
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 claudeModelOptions = asClaudeModelOptions(modelOptions);
|
||||
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
|
||||
const draftEffort = resolveReasoningEffortForProvider(
|
||||
"claudeAgent",
|
||||
claudeModelOptions?.effort,
|
||||
);
|
||||
const defaultEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
const promptEffort =
|
||||
draftEffort && draftEffort !== "ultrathink" && reasoningOptions.includes(draftEffort)
|
||||
? draftEffort
|
||||
: reasoningOptions.includes(defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const normalizedClaudeOptions = normalizeClaudeModelOptions(model, claudeModelOptions);
|
||||
const ultrathinkActive =
|
||||
supportsClaudeUltrathinkKeyword(model) && isClaudeUltrathinkPrompt(prompt);
|
||||
|
||||
return {
|
||||
provider: "claudeAgent",
|
||||
promptEffort,
|
||||
modelOptionsForDispatch: normalizedClaudeOptions,
|
||||
...(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}
|
||||
/>
|
||||
),
|
||||
},
|
||||
};
|
||||
@@ -128,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,
|
||||
});
|
||||
}
|
||||
@@ -141,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,
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
import * as Schema from "effect/Schema";
|
||||
import { ProjectId, ThreadId, type ModelSelection } from "@t3tools/contracts";
|
||||
import {
|
||||
ProjectId,
|
||||
ThreadId,
|
||||
type ModelSelection,
|
||||
type ProviderModelOptions,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
@@ -67,7 +72,8 @@ function resetComposerDraftStore() {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelection: null,
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -83,6 +89,10 @@ function modelSelection(
|
||||
} as ModelSelection;
|
||||
}
|
||||
|
||||
function providerModelOptions(options: ProviderModelOptions): ProviderModelOptions {
|
||||
return options;
|
||||
}
|
||||
|
||||
describe("composerDraftStore addImages", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-dedupe");
|
||||
let originalRevokeObjectUrl: typeof URL.revokeObjectURL;
|
||||
@@ -208,6 +218,8 @@ describe("composerDraftStore syncPersistedAttachments", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -264,6 +276,8 @@ describe("composerDraftStore terminal contexts", () => {
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -623,7 +637,9 @@ describe("composerDraftStore modelSelection", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
@@ -635,9 +651,9 @@ describe("composerDraftStore modelSelection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
);
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(modelSelection("codex", "gpt-5.4"));
|
||||
});
|
||||
|
||||
it("replaces only the targeted provider options on the current model selection", () => {
|
||||
@@ -666,19 +682,22 @@ describe("composerDraftStore modelSelection", () => {
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("removes selection options when the patched provider options normalize empty", () => {
|
||||
it("keeps explicit default-state overrides on the selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
|
||||
store.setModelSelection(
|
||||
@@ -692,13 +711,18 @@ describe("composerDraftStore modelSelection", () => {
|
||||
thinking: true,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6"),
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: true,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toBeNull();
|
||||
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.setModelSelection(threadId, modelSelection("codex", "gpt-5.4", { fastMode: true }));
|
||||
@@ -708,8 +732,13 @@ describe("composerDraftStore modelSelection", () => {
|
||||
fastMode: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.4"),
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(
|
||||
modelSelection("codex", "gpt-5.4", {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -728,16 +757,60 @@ describe("composerDraftStore modelSelection", () => {
|
||||
thinking: false,
|
||||
});
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
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();
|
||||
|
||||
@@ -752,7 +825,7 @@ describe("composerDraftStore modelSelection", () => {
|
||||
{ persistSticky: true },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.codex).toEqual(
|
||||
modelSelection("codex", "gpt-5.4", {
|
||||
fastMode: true,
|
||||
}),
|
||||
@@ -779,12 +852,15 @@ describe("composerDraftStore modelSelection", () => {
|
||||
{ persistSticky: false },
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider
|
||||
.claudeAgent,
|
||||
).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", {
|
||||
thinking: false,
|
||||
}),
|
||||
);
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).toEqual(
|
||||
expect(useComposerDraftStore.getState().stickyModelSelectionByProvider.claudeAgent).toEqual(
|
||||
modelSelection("claudeAgent", "claude-opus-4-6", { effort: "max" }),
|
||||
);
|
||||
});
|
||||
@@ -802,9 +878,9 @@ describe("composerDraftStore setModelSelection", () => {
|
||||
|
||||
store.setModelSelection(threadId, modelSelection("codex", "gpt-5.3-codex"));
|
||||
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex"),
|
||||
);
|
||||
expect(
|
||||
useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelectionByProvider.codex,
|
||||
).toEqual(modelSelection("codex", "gpt-5.3-codex"));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -823,16 +899,13 @@ describe("composerDraftStore sticky composer settings", () => {
|
||||
}),
|
||||
);
|
||||
|
||||
expect(useComposerDraftStore.getState()).toMatchObject({
|
||||
stickyModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.3-codex",
|
||||
options: {
|
||||
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 by dropping selection options", () => {
|
||||
@@ -840,9 +913,25 @@ describe("composerDraftStore sticky composer settings", () => {
|
||||
|
||||
store.setStickyModelSelection(modelSelection("codex", "gpt-5.4"));
|
||||
|
||||
expect(useComposerDraftStore.getState().stickyModelSelection).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",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -853,7 +942,7 @@ describe("composerDraftStore provider-scoped option updates", () => {
|
||||
resetComposerDraftStore();
|
||||
});
|
||||
|
||||
it("does not patch provider options when the draft selection is on another provider", () => {
|
||||
it("retains off-provider option memory without changing the active selection", () => {
|
||||
const store = useComposerDraftStore.getState();
|
||||
store.setModelSelection(
|
||||
threadId,
|
||||
@@ -862,11 +951,12 @@ describe("composerDraftStore provider-scoped option updates", () => {
|
||||
}),
|
||||
);
|
||||
store.setProviderModelOptions(threadId, "claudeAgent", { effort: "max" });
|
||||
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.modelSelection).toEqual(
|
||||
modelSelection("codex", "gpt-5.3-codex", {
|
||||
reasoningEffort: "medium",
|
||||
}),
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+574
-113
@@ -2,8 +2,8 @@ import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexReasoningEffort,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
type ModelSlug,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
ProviderKind,
|
||||
@@ -14,8 +14,14 @@ import {
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as Equal from "effect/Equal";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import {
|
||||
getDefaultModel,
|
||||
normalizeModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { useMemo } from "react";
|
||||
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import { resolveAppModelSelection } from "./modelSelection";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type ChatImageAttachment } from "./types";
|
||||
import {
|
||||
type TerminalContextDraft,
|
||||
@@ -27,7 +33,7 @@ import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
|
||||
|
||||
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 2;
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 3;
|
||||
const DraftThreadEnvModeSchema = Schema.Literals(["local", "worktree"]);
|
||||
export type DraftThreadEnvMode = typeof DraftThreadEnvModeSchema.Type;
|
||||
|
||||
@@ -74,7 +80,10 @@ const PersistedComposerThreadDraftState = Schema.Struct({
|
||||
prompt: Schema.String,
|
||||
attachments: Schema.Array(PersistedComposerImageAttachment),
|
||||
terminalContexts: Schema.optionalKey(Schema.Array(PersistedTerminalContextDraft)),
|
||||
modelSelection: Schema.optionalKey(Schema.NullOr(Schema.Unknown)),
|
||||
modelSelectionByProvider: Schema.optionalKey(
|
||||
Schema.Record(ProviderKind, Schema.optionalKey(ModelSelection)),
|
||||
),
|
||||
activeProvider: Schema.optionalKey(Schema.NullOr(ProviderKind)),
|
||||
runtimeMode: Schema.optionalKey(RuntimeMode),
|
||||
interactionMode: Schema.optionalKey(ProviderInteractionMode),
|
||||
});
|
||||
@@ -87,13 +96,39 @@ const LegacyCodexFields = Schema.Struct({
|
||||
});
|
||||
type LegacyCodexFields = typeof LegacyCodexFields.Type;
|
||||
|
||||
type LegacyPersistedCodexThreadDraftState = PersistedComposerThreadDraftState & LegacyCodexFields;
|
||||
type LegacyPersistedComposerThreadDraftState = LegacyPersistedCodexThreadDraftState & {
|
||||
provider?: ProviderKind;
|
||||
model?: string;
|
||||
const LegacyThreadModelFields = Schema.Struct({
|
||||
provider: Schema.optionalKey(ProviderKind),
|
||||
model: Schema.optionalKey(Schema.String),
|
||||
modelOptions: Schema.optionalKey(Schema.NullOr(ProviderModelOptions)),
|
||||
});
|
||||
type LegacyThreadModelFields = typeof LegacyThreadModelFields.Type;
|
||||
|
||||
type LegacyV2ThreadDraftFields = {
|
||||
modelSelection?: ModelSelection | null;
|
||||
modelOptions?: ProviderModelOptions | null;
|
||||
};
|
||||
|
||||
type LegacyPersistedComposerThreadDraftState = PersistedComposerThreadDraftState &
|
||||
LegacyCodexFields &
|
||||
LegacyThreadModelFields &
|
||||
LegacyV2ThreadDraftFields;
|
||||
|
||||
const LegacyStickyModelFields = Schema.Struct({
|
||||
stickyProvider: Schema.optionalKey(ProviderKind),
|
||||
stickyModel: Schema.optionalKey(Schema.String),
|
||||
stickyModelOptions: Schema.optionalKey(Schema.NullOr(ProviderModelOptions)),
|
||||
});
|
||||
type LegacyStickyModelFields = typeof LegacyStickyModelFields.Type;
|
||||
|
||||
type LegacyV2StoreFields = {
|
||||
stickyModelSelection?: ModelSelection | null;
|
||||
stickyModelOptions?: ProviderModelOptions | null;
|
||||
};
|
||||
|
||||
type LegacyPersistedComposerDraftStoreState = PersistedComposerDraftStoreState &
|
||||
LegacyStickyModelFields &
|
||||
LegacyV2StoreFields;
|
||||
|
||||
const PersistedDraftThreadState = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
createdAt: Schema.String,
|
||||
@@ -109,7 +144,10 @@ const PersistedComposerDraftStoreState = Schema.Struct({
|
||||
draftsByThreadId: Schema.Record(ThreadId, PersistedComposerThreadDraftState),
|
||||
draftThreadsByThreadId: Schema.Record(ThreadId, PersistedDraftThreadState),
|
||||
projectDraftThreadIdByProjectId: Schema.Record(ProjectId, ThreadId),
|
||||
stickyModelSelection: Schema.NullOr(Schema.Unknown),
|
||||
stickyModelSelectionByProvider: Schema.optionalKey(
|
||||
Schema.Record(ProviderKind, Schema.optionalKey(ModelSelection)),
|
||||
),
|
||||
stickyActiveProvider: Schema.optionalKey(Schema.NullOr(ProviderKind)),
|
||||
});
|
||||
type PersistedComposerDraftStoreState = typeof PersistedComposerDraftStoreState.Type;
|
||||
|
||||
@@ -118,13 +156,14 @@ const PersistedComposerDraftStoreStorage = Schema.Struct({
|
||||
state: PersistedComposerDraftStoreState,
|
||||
});
|
||||
|
||||
interface ComposerThreadDraftState {
|
||||
export interface ComposerThreadDraftState {
|
||||
prompt: string;
|
||||
images: ComposerImageAttachment[];
|
||||
nonPersistedImageIds: string[];
|
||||
persistedAttachments: PersistedComposerImageAttachment[];
|
||||
terminalContexts: TerminalContextDraft[];
|
||||
modelSelection: ModelSelection | null;
|
||||
modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;
|
||||
activeProvider: ProviderKind | null;
|
||||
runtimeMode: RuntimeMode | null;
|
||||
interactionMode: ProviderInteractionMode | null;
|
||||
}
|
||||
@@ -147,7 +186,8 @@ interface ComposerDraftStoreState {
|
||||
draftsByThreadId: Record<ThreadId, ComposerThreadDraftState>;
|
||||
draftThreadsByThreadId: Record<ThreadId, DraftThreadState>;
|
||||
projectDraftThreadIdByProjectId: Record<ProjectId, ThreadId>;
|
||||
stickyModelSelection: ModelSelection | null;
|
||||
stickyModelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>>;
|
||||
stickyActiveProvider: ProviderKind | null;
|
||||
getDraftThreadByProjectId: (projectId: ProjectId) => ProjectDraftThread | null;
|
||||
getDraftThread: (threadId: ThreadId) => DraftThreadState | null;
|
||||
setProjectDraftThreadId: (
|
||||
@@ -184,6 +224,11 @@ interface ComposerDraftStoreState {
|
||||
threadId: ThreadId,
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
) => void;
|
||||
setModelOptions: (
|
||||
threadId: ThreadId,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
) => void;
|
||||
applyStickyState: (threadId: ThreadId) => void;
|
||||
setProviderModelOptions: (
|
||||
threadId: ThreadId,
|
||||
provider: ProviderKind,
|
||||
@@ -218,11 +263,42 @@ interface ComposerDraftStoreState {
|
||||
clearComposerContent: (threadId: ThreadId) => void;
|
||||
}
|
||||
|
||||
export interface EffectiveComposerModelState {
|
||||
selectedModel: ModelSlug;
|
||||
modelOptions: ProviderModelOptions | null;
|
||||
}
|
||||
|
||||
function providerModelOptionsFromSelection(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (!modelSelection?.options) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
[modelSelection.provider]: modelSelection.options,
|
||||
};
|
||||
}
|
||||
|
||||
function modelSelectionByProviderToOptions(
|
||||
map: Partial<Record<ProviderKind, ModelSelection>> | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (!map) return null;
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [provider, selection] of Object.entries(map)) {
|
||||
if (selection?.options) {
|
||||
result[provider] = selection.options;
|
||||
}
|
||||
}
|
||||
return Object.keys(result).length > 0 ? (result as ProviderModelOptions) : null;
|
||||
}
|
||||
|
||||
const EMPTY_PERSISTED_DRAFT_STORE_STATE = Object.freeze<PersistedComposerDraftStoreState>({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelection: null,
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
});
|
||||
|
||||
const EMPTY_IMAGES: ComposerImageAttachment[] = [];
|
||||
@@ -232,13 +308,17 @@ const EMPTY_TERMINAL_CONTEXTS: TerminalContextDraft[] = [];
|
||||
Object.freeze(EMPTY_IMAGES);
|
||||
Object.freeze(EMPTY_IDS);
|
||||
Object.freeze(EMPTY_PERSISTED_ATTACHMENTS);
|
||||
const EMPTY_MODEL_SELECTION_BY_PROVIDER: Partial<Record<ProviderKind, ModelSelection>> =
|
||||
Object.freeze({});
|
||||
|
||||
const EMPTY_THREAD_DRAFT = Object.freeze<ComposerThreadDraftState>({
|
||||
prompt: "",
|
||||
images: EMPTY_IMAGES,
|
||||
nonPersistedImageIds: EMPTY_IDS,
|
||||
persistedAttachments: EMPTY_PERSISTED_ATTACHMENTS,
|
||||
terminalContexts: EMPTY_TERMINAL_CONTEXTS,
|
||||
modelSelection: null,
|
||||
modelSelectionByProvider: EMPTY_MODEL_SELECTION_BY_PROVIDER,
|
||||
activeProvider: null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
});
|
||||
@@ -250,7 +330,8 @@ function createEmptyThreadDraft(): ComposerThreadDraftState {
|
||||
nonPersistedImageIds: [],
|
||||
persistedAttachments: [],
|
||||
terminalContexts: [],
|
||||
modelSelection: null,
|
||||
modelSelectionByProvider: {},
|
||||
activeProvider: null,
|
||||
runtimeMode: null,
|
||||
interactionMode: null,
|
||||
};
|
||||
@@ -319,7 +400,8 @@ function shouldRemoveDraft(draft: ComposerThreadDraftState): boolean {
|
||||
draft.images.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.modelSelection === null &&
|
||||
Object.keys(draft.modelSelectionByProvider).length === 0 &&
|
||||
draft.activeProvider === null &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
);
|
||||
@@ -358,20 +440,28 @@ function normalizeProviderModelOptions(
|
||||
? legacy.effort
|
||||
: undefined;
|
||||
const codexFastMode =
|
||||
codexCandidate?.fastMode === true ||
|
||||
(provider === "codex" && legacy?.codexFastMode === true) ||
|
||||
(typeof legacy?.serviceTier === "string" && legacy.serviceTier === "fast");
|
||||
codexCandidate?.fastMode === true
|
||||
? true
|
||||
: codexCandidate?.fastMode === false
|
||||
? false
|
||||
: (provider === "codex" && legacy?.codexFastMode === true) ||
|
||||
(typeof legacy?.serviceTier === "string" && legacy.serviceTier === "fast")
|
||||
? true
|
||||
: undefined;
|
||||
const codex =
|
||||
codexReasoningEffort && codexReasoningEffort !== DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex
|
||||
codexReasoningEffort !== undefined || codexFastMode !== undefined
|
||||
? {
|
||||
reasoningEffort: codexReasoningEffort,
|
||||
...(codexFastMode ? { fastMode: true } : {}),
|
||||
...(codexReasoningEffort !== undefined ? { reasoningEffort: codexReasoningEffort } : {}),
|
||||
...(codexFastMode !== undefined ? { fastMode: codexFastMode } : {}),
|
||||
}
|
||||
: codexFastMode
|
||||
? { fastMode: true }
|
||||
: undefined;
|
||||
: undefined;
|
||||
|
||||
const claudeThinking = claudeCandidate?.thinking === false ? false : undefined;
|
||||
const claudeThinking =
|
||||
claudeCandidate?.thinking === true
|
||||
? true
|
||||
: claudeCandidate?.thinking === false
|
||||
? false
|
||||
: undefined;
|
||||
const claudeEffort: ClaudeCodeEffort | undefined =
|
||||
claudeCandidate?.effort === "low" ||
|
||||
claudeCandidate?.effort === "medium" ||
|
||||
@@ -380,17 +470,18 @@ function normalizeProviderModelOptions(
|
||||
claudeCandidate?.effort === "ultrathink"
|
||||
? claudeCandidate.effort
|
||||
: undefined;
|
||||
const claudeFastMode = claudeCandidate?.fastMode === true;
|
||||
const claudeFastMode =
|
||||
claudeCandidate?.fastMode === true
|
||||
? true
|
||||
: claudeCandidate?.fastMode === false
|
||||
? false
|
||||
: undefined;
|
||||
const claude =
|
||||
claudeThinking === false ||
|
||||
(claudeEffort && claudeEffort !== DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeAgent) ||
|
||||
claudeFastMode
|
||||
claudeThinking !== undefined || claudeEffort !== undefined || claudeFastMode !== undefined
|
||||
? {
|
||||
...(claudeThinking === false ? { thinking: false } : {}),
|
||||
...(claudeEffort && claudeEffort !== DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeAgent
|
||||
? { effort: claudeEffort }
|
||||
: {}),
|
||||
...(claudeFastMode ? { fastMode: true } : {}),
|
||||
...(claudeThinking !== undefined ? { thinking: claudeThinking } : {}),
|
||||
...(claudeEffort !== undefined ? { effort: claudeEffort } : {}),
|
||||
...(claudeFastMode !== undefined ? { fastMode: claudeFastMode } : {}),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
@@ -438,7 +529,38 @@ function normalizeModelSelection(
|
||||
};
|
||||
}
|
||||
|
||||
function replaceProviderModelOptions(
|
||||
// ── Legacy sync helpers (used only during migration from v2 storage) ──
|
||||
|
||||
function legacySyncModelSelectionOptions(
|
||||
modelSelection: ModelSelection | null,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
): ModelSelection | null {
|
||||
if (modelSelection === null) {
|
||||
return null;
|
||||
}
|
||||
const options = modelOptions?.[modelSelection.provider];
|
||||
return {
|
||||
provider: modelSelection.provider,
|
||||
model: modelSelection.model,
|
||||
...(options ? { options } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
modelSelection: ModelSelection | null,
|
||||
currentModelOptions: ProviderModelOptions | null | undefined,
|
||||
): ProviderModelOptions | null {
|
||||
if (modelSelection?.options === undefined) {
|
||||
return normalizeProviderModelOptions(currentModelOptions);
|
||||
}
|
||||
return legacyReplaceProviderModelOptions(
|
||||
normalizeProviderModelOptions(currentModelOptions),
|
||||
modelSelection.provider,
|
||||
modelSelection.options,
|
||||
);
|
||||
}
|
||||
|
||||
function legacyReplaceProviderModelOptions(
|
||||
currentModelOptions: ProviderModelOptions | null | undefined,
|
||||
provider: ProviderKind,
|
||||
nextProviderOptions: ProviderModelOptions[ProviderKind] | null | undefined,
|
||||
@@ -456,6 +578,72 @@ function replaceProviderModelOptions(
|
||||
});
|
||||
}
|
||||
|
||||
// ── New helpers for the consolidated representation ────────────────────
|
||||
|
||||
function legacyToModelSelectionByProvider(
|
||||
modelSelection: ModelSelection | null,
|
||||
modelOptions: ProviderModelOptions | null | undefined,
|
||||
): Partial<Record<ProviderKind, ModelSelection>> {
|
||||
const result: Partial<Record<ProviderKind, ModelSelection>> = {};
|
||||
// Add entries from the options bag (for non-active providers)
|
||||
if (modelOptions) {
|
||||
for (const provider of ["codex", "claudeAgent"] as const) {
|
||||
const options = modelOptions[provider];
|
||||
if (options && Object.keys(options).length > 0) {
|
||||
result[provider] = {
|
||||
provider,
|
||||
model:
|
||||
modelSelection?.provider === provider
|
||||
? modelSelection.model
|
||||
: getDefaultModel(provider),
|
||||
options,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
// Add/overwrite the active selection (it's authoritative for its provider)
|
||||
if (modelSelection) {
|
||||
result[modelSelection.provider] = modelSelection;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function deriveEffectiveComposerModelState(input: {
|
||||
draft:
|
||||
| Pick<ComposerThreadDraftState, "modelSelectionByProvider" | "activeProvider">
|
||||
| null
|
||||
| undefined;
|
||||
selectedProvider: ProviderKind;
|
||||
threadModelSelection: ModelSelection | null | undefined;
|
||||
projectModelSelection: ModelSelection | null | undefined;
|
||||
customModelsByProvider: Record<ProviderKind, readonly string[]>;
|
||||
}): EffectiveComposerModelState {
|
||||
const baseModel = resolveModelSlugForProvider(
|
||||
input.selectedProvider,
|
||||
input.threadModelSelection?.model ??
|
||||
input.projectModelSelection?.model ??
|
||||
getDefaultModel(input.selectedProvider),
|
||||
);
|
||||
const activeSelection = input.draft?.modelSelectionByProvider?.[input.selectedProvider];
|
||||
const selectedModel = activeSelection?.model
|
||||
? resolveAppModelSelection(
|
||||
input.selectedProvider,
|
||||
input.customModelsByProvider,
|
||||
activeSelection.model,
|
||||
)
|
||||
: baseModel;
|
||||
const modelOptions =
|
||||
modelSelectionByProviderToOptions(input.draft?.modelSelectionByProvider) ??
|
||||
providerModelOptionsFromSelection(input.threadModelSelection) ??
|
||||
providerModelOptionsFromSelection(input.projectModelSelection) ??
|
||||
null;
|
||||
|
||||
return {
|
||||
selectedModel,
|
||||
modelOptions,
|
||||
};
|
||||
}
|
||||
|
||||
function revokeObjectPreviewUrl(previewUrl: string): void {
|
||||
if (typeof URL === "undefined") {
|
||||
return;
|
||||
@@ -656,9 +844,7 @@ function normalizePersistedDraftsByThreadId(
|
||||
if (!draftValue || typeof draftValue !== "object") {
|
||||
continue;
|
||||
}
|
||||
const draftCandidate = draftValue as
|
||||
| PersistedComposerThreadDraftState
|
||||
| LegacyPersistedCodexThreadDraftState;
|
||||
const draftCandidate = draftValue as PersistedComposerThreadDraftState;
|
||||
const promptCandidate = typeof draftCandidate.prompt === "string" ? draftCandidate.prompt : "";
|
||||
const attachments = Array.isArray(draftCandidate.attachments)
|
||||
? draftCandidate.attachments.flatMap((entry) => {
|
||||
@@ -685,18 +871,59 @@ function normalizePersistedDraftsByThreadId(
|
||||
promptCandidate,
|
||||
terminalContexts.length,
|
||||
);
|
||||
const legacyDraftCandidate = draftCandidate as LegacyPersistedComposerThreadDraftState;
|
||||
const modelSelection = normalizeModelSelection(draftCandidate.modelSelection, {
|
||||
provider: legacyDraftCandidate.provider,
|
||||
model: legacyDraftCandidate.model,
|
||||
modelOptions: legacyDraftCandidate.modelOptions,
|
||||
legacyCodex: legacyDraftCandidate,
|
||||
});
|
||||
// If the draft already has the v3 shape, use it directly
|
||||
const legacyDraftCandidate = draftValue as LegacyPersistedComposerThreadDraftState;
|
||||
let modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> = {};
|
||||
let activeProvider: ProviderKind | null = null;
|
||||
|
||||
if (
|
||||
draftCandidate.modelSelectionByProvider &&
|
||||
typeof draftCandidate.modelSelectionByProvider === "object"
|
||||
) {
|
||||
// v3 format
|
||||
modelSelectionByProvider = draftCandidate.modelSelectionByProvider as Partial<
|
||||
Record<ProviderKind, ModelSelection>
|
||||
>;
|
||||
activeProvider = normalizeProviderKind(draftCandidate.activeProvider);
|
||||
} else {
|
||||
// v2 or legacy format: migrate
|
||||
const normalizedModelOptions =
|
||||
normalizeProviderModelOptions(
|
||||
legacyDraftCandidate.modelOptions,
|
||||
undefined,
|
||||
legacyDraftCandidate,
|
||||
) ?? null;
|
||||
const normalizedModelSelection = normalizeModelSelection(
|
||||
legacyDraftCandidate.modelSelection,
|
||||
{
|
||||
provider: legacyDraftCandidate.provider,
|
||||
model: legacyDraftCandidate.model,
|
||||
modelOptions: normalizedModelOptions ?? legacyDraftCandidate.modelOptions,
|
||||
legacyCodex: legacyDraftCandidate,
|
||||
},
|
||||
);
|
||||
const mergedModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
normalizedModelSelection,
|
||||
normalizedModelOptions,
|
||||
);
|
||||
const modelSelection = legacySyncModelSelectionOptions(
|
||||
normalizedModelSelection,
|
||||
mergedModelOptions,
|
||||
);
|
||||
modelSelectionByProvider = legacyToModelSelectionByProvider(
|
||||
modelSelection,
|
||||
mergedModelOptions,
|
||||
);
|
||||
activeProvider = modelSelection?.provider ?? null;
|
||||
}
|
||||
|
||||
const hasModelData =
|
||||
Object.keys(modelSelectionByProvider).length > 0 || activeProvider !== null;
|
||||
if (
|
||||
promptCandidate.length === 0 &&
|
||||
attachments.length === 0 &&
|
||||
terminalContexts.length === 0 &&
|
||||
modelSelection === null &&
|
||||
!hasModelData &&
|
||||
!runtimeMode &&
|
||||
!interactionMode
|
||||
) {
|
||||
@@ -706,7 +933,7 @@ function normalizePersistedDraftsByThreadId(
|
||||
prompt,
|
||||
attachments,
|
||||
...(terminalContexts.length > 0 ? { terminalContexts } : {}),
|
||||
...(modelSelection ? { modelSelection } : {}),
|
||||
...(hasModelData ? { modelSelectionByProvider, activeProvider } : {}),
|
||||
...(runtimeMode ? { runtimeMode } : {}),
|
||||
...(interactionMode ? { interactionMode } : {}),
|
||||
};
|
||||
@@ -721,15 +948,32 @@ function migratePersistedComposerDraftStoreState(
|
||||
if (!persistedState || typeof persistedState !== "object") {
|
||||
return EMPTY_PERSISTED_DRAFT_STORE_STATE;
|
||||
}
|
||||
const candidate = persistedState as Record<string, unknown>;
|
||||
const candidate = persistedState as LegacyPersistedComposerDraftStoreState;
|
||||
const rawDraftMap = candidate.draftsByThreadId;
|
||||
const rawDraftThreadsByThreadId = candidate.draftThreadsByThreadId;
|
||||
const rawProjectDraftThreadIdByProjectId = candidate.projectDraftThreadIdByProjectId;
|
||||
const stickyModelSelection = normalizeModelSelection(candidate.stickyModelSelection, {
|
||||
|
||||
// Migrate sticky state from v2 (dual) to v3 (consolidated)
|
||||
const stickyModelOptions = normalizeProviderModelOptions(candidate.stickyModelOptions) ?? {};
|
||||
const normalizedStickyModelSelection = normalizeModelSelection(candidate.stickyModelSelection, {
|
||||
provider: candidate.stickyProvider ?? "codex",
|
||||
model: candidate.stickyModel,
|
||||
modelOptions: candidate.stickyModelOptions,
|
||||
modelOptions: stickyModelOptions,
|
||||
});
|
||||
const nextStickyModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
normalizedStickyModelSelection,
|
||||
stickyModelOptions,
|
||||
);
|
||||
const stickyModelSelection = legacySyncModelSelectionOptions(
|
||||
normalizedStickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
const stickyModelSelectionByProvider = legacyToModelSelectionByProvider(
|
||||
stickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
const stickyActiveProvider = normalizeProviderKind(candidate.stickyProvider) ?? null;
|
||||
|
||||
const { draftThreadsByThreadId, projectDraftThreadIdByProjectId } =
|
||||
normalizePersistedDraftThreads(rawDraftThreadsByThreadId, rawProjectDraftThreadIdByProjectId);
|
||||
const draftsByThreadId = normalizePersistedDraftsByThreadId(rawDraftMap);
|
||||
@@ -737,7 +981,8 @@ function migratePersistedComposerDraftStoreState(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection,
|
||||
stickyModelSelectionByProvider,
|
||||
stickyActiveProvider,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -751,11 +996,13 @@ function partializeComposerDraftStoreState(
|
||||
if (typeof threadId !== "string" || threadId.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const hasModelData =
|
||||
Object.keys(draft.modelSelectionByProvider).length > 0 || draft.activeProvider !== null;
|
||||
if (
|
||||
draft.prompt.length === 0 &&
|
||||
draft.persistedAttachments.length === 0 &&
|
||||
draft.terminalContexts.length === 0 &&
|
||||
draft.modelSelection === null &&
|
||||
!hasModelData &&
|
||||
draft.runtimeMode === null &&
|
||||
draft.interactionMode === null
|
||||
) {
|
||||
@@ -777,7 +1024,12 @@ function partializeComposerDraftStoreState(
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
...(draft.modelSelection ? { modelSelection: draft.modelSelection } : {}),
|
||||
...(hasModelData
|
||||
? {
|
||||
modelSelectionByProvider: draft.modelSelectionByProvider,
|
||||
activeProvider: draft.activeProvider,
|
||||
}
|
||||
: {}),
|
||||
...(draft.runtimeMode ? { runtimeMode: draft.runtimeMode } : {}),
|
||||
...(draft.interactionMode ? { interactionMode: draft.interactionMode } : {}),
|
||||
};
|
||||
@@ -787,7 +1039,8 @@ function partializeComposerDraftStoreState(
|
||||
draftsByThreadId: persistedDraftsByThreadId,
|
||||
draftThreadsByThreadId: state.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: state.projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection: state.stickyModelSelection,
|
||||
stickyModelSelectionByProvider: state.stickyModelSelectionByProvider,
|
||||
stickyActiveProvider: state.stickyActiveProvider,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -797,25 +1050,58 @@ function normalizeCurrentPersistedComposerDraftStoreState(
|
||||
if (!persistedState || typeof persistedState !== "object") {
|
||||
return EMPTY_PERSISTED_DRAFT_STORE_STATE;
|
||||
}
|
||||
const normalizedPersistedState = persistedState as Record<string, unknown>;
|
||||
const normalizedPersistedState = persistedState as LegacyPersistedComposerDraftStoreState;
|
||||
const { draftThreadsByThreadId, projectDraftThreadIdByProjectId } =
|
||||
normalizePersistedDraftThreads(
|
||||
normalizedPersistedState.draftThreadsByThreadId,
|
||||
normalizedPersistedState.projectDraftThreadIdByProjectId,
|
||||
);
|
||||
const stickyModelSelection = normalizeModelSelection(
|
||||
normalizedPersistedState.stickyModelSelection,
|
||||
{
|
||||
provider: normalizedPersistedState.stickyProvider,
|
||||
model: normalizedPersistedState.stickyModel,
|
||||
modelOptions: normalizedPersistedState.stickyModelOptions,
|
||||
},
|
||||
);
|
||||
|
||||
// Handle both v3 (modelSelectionByProvider) and v2/legacy formats
|
||||
let stickyModelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> = {};
|
||||
let stickyActiveProvider: ProviderKind | null = null;
|
||||
if (
|
||||
normalizedPersistedState.stickyModelSelectionByProvider &&
|
||||
typeof normalizedPersistedState.stickyModelSelectionByProvider === "object"
|
||||
) {
|
||||
stickyModelSelectionByProvider =
|
||||
normalizedPersistedState.stickyModelSelectionByProvider as Partial<
|
||||
Record<ProviderKind, ModelSelection>
|
||||
>;
|
||||
stickyActiveProvider = normalizeProviderKind(normalizedPersistedState.stickyActiveProvider);
|
||||
} else {
|
||||
// Legacy migration path
|
||||
const stickyModelOptions =
|
||||
normalizeProviderModelOptions(normalizedPersistedState.stickyModelOptions) ?? {};
|
||||
const normalizedStickyModelSelection = normalizeModelSelection(
|
||||
normalizedPersistedState.stickyModelSelection,
|
||||
{
|
||||
provider: normalizedPersistedState.stickyProvider,
|
||||
model: normalizedPersistedState.stickyModel,
|
||||
modelOptions: stickyModelOptions,
|
||||
},
|
||||
);
|
||||
const nextStickyModelOptions = legacyMergeModelSelectionIntoProviderModelOptions(
|
||||
normalizedStickyModelSelection,
|
||||
stickyModelOptions,
|
||||
);
|
||||
const stickyModelSelection = legacySyncModelSelectionOptions(
|
||||
normalizedStickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
stickyModelSelectionByProvider = legacyToModelSelectionByProvider(
|
||||
stickyModelSelection,
|
||||
nextStickyModelOptions,
|
||||
);
|
||||
stickyActiveProvider = normalizeProviderKind(normalizedPersistedState.stickyProvider);
|
||||
}
|
||||
|
||||
return {
|
||||
draftsByThreadId: normalizePersistedDraftsByThreadId(normalizedPersistedState.draftsByThreadId),
|
||||
draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection,
|
||||
stickyModelSelectionByProvider,
|
||||
stickyActiveProvider,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -942,6 +1228,11 @@ function hydrateImagesFromPersisted(
|
||||
function toHydratedThreadDraft(
|
||||
persistedDraft: PersistedComposerThreadDraftState,
|
||||
): ComposerThreadDraftState {
|
||||
// The persisted draft is already in v3 shape (migration handles older formats)
|
||||
const modelSelectionByProvider: Partial<Record<ProviderKind, ModelSelection>> =
|
||||
persistedDraft.modelSelectionByProvider ?? {};
|
||||
const activeProvider = normalizeProviderKind(persistedDraft.activeProvider) ?? null;
|
||||
|
||||
return {
|
||||
prompt: persistedDraft.prompt,
|
||||
images: hydrateImagesFromPersisted(persistedDraft.attachments),
|
||||
@@ -952,12 +1243,8 @@ function toHydratedThreadDraft(
|
||||
...context,
|
||||
text: "",
|
||||
})) ?? [],
|
||||
modelSelection: normalizeModelSelection(persistedDraft.modelSelection, {
|
||||
provider: (persistedDraft as LegacyPersistedComposerThreadDraftState).provider,
|
||||
model: (persistedDraft as LegacyPersistedComposerThreadDraftState).model,
|
||||
modelOptions: (persistedDraft as LegacyPersistedComposerThreadDraftState).modelOptions,
|
||||
legacyCodex: persistedDraft as LegacyPersistedComposerThreadDraftState,
|
||||
}),
|
||||
modelSelectionByProvider,
|
||||
activeProvider,
|
||||
runtimeMode: persistedDraft.runtimeMode ?? null,
|
||||
interactionMode: persistedDraft.interactionMode ?? null,
|
||||
};
|
||||
@@ -969,7 +1256,8 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
projectDraftThreadIdByProjectId: {},
|
||||
stickyModelSelection: null,
|
||||
stickyModelSelectionByProvider: {},
|
||||
stickyActiveProvider: null,
|
||||
getDraftThreadByProjectId: (projectId) => {
|
||||
if (projectId.length === 0) {
|
||||
return null;
|
||||
@@ -1216,12 +1504,67 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
});
|
||||
},
|
||||
setStickyModelSelection: (modelSelection) => {
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
set((state) =>
|
||||
Equal.equals(state.stickyModelSelection, normalizedModelSelection)
|
||||
? state
|
||||
: { stickyModelSelection: normalizedModelSelection },
|
||||
);
|
||||
const normalized = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
if (!normalized) {
|
||||
return state;
|
||||
}
|
||||
const nextMap: Partial<Record<ProviderKind, ModelSelection>> = {
|
||||
...state.stickyModelSelectionByProvider,
|
||||
[normalized.provider]: normalized,
|
||||
};
|
||||
if (Equal.equals(state.stickyModelSelectionByProvider, nextMap)) {
|
||||
return state.stickyActiveProvider === normalized.provider
|
||||
? state
|
||||
: { stickyActiveProvider: normalized.provider };
|
||||
}
|
||||
return {
|
||||
stickyModelSelectionByProvider: nextMap,
|
||||
stickyActiveProvider: normalized.provider,
|
||||
};
|
||||
});
|
||||
},
|
||||
applyStickyState: (threadId) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
set((state) => {
|
||||
const stickyMap = state.stickyModelSelectionByProvider;
|
||||
const stickyActiveProvider = state.stickyActiveProvider;
|
||||
if (Object.keys(stickyMap).length === 0 && stickyActiveProvider === null) {
|
||||
return state;
|
||||
}
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
for (const [provider, selection] of Object.entries(stickyMap)) {
|
||||
if (selection) {
|
||||
const current = nextMap[provider as ProviderKind];
|
||||
nextMap[provider as ProviderKind] = {
|
||||
...selection,
|
||||
model: current?.model ?? selection.model,
|
||||
};
|
||||
}
|
||||
}
|
||||
if (
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
base.activeProvider === stickyActiveProvider
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
activeProvider: stickyActiveProvider,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setPrompt: (threadId, prompt) => {
|
||||
if (threadId.length === 0) {
|
||||
@@ -1270,19 +1613,84 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedModelSelection = normalizeModelSelection(modelSelection);
|
||||
const normalized = normalizeModelSelection(modelSelection);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedModelSelection === null) {
|
||||
if (!existing && normalized === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (Equal.equals(base.modelSelection, normalizedModelSelection)) {
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
if (normalized) {
|
||||
const current = nextMap[normalized.provider];
|
||||
if (normalized.options !== undefined) {
|
||||
// Explicit options provided → use them
|
||||
nextMap[normalized.provider] = normalized;
|
||||
} else {
|
||||
// No options in selection → preserve existing options, update provider+model
|
||||
nextMap[normalized.provider] = {
|
||||
provider: normalized.provider,
|
||||
model: normalized.model,
|
||||
...(current?.options ? { options: current.options } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
const nextActiveProvider = normalized?.provider ?? base.activeProvider;
|
||||
if (
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
base.activeProvider === nextActiveProvider
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelection: normalizedModelSelection,
|
||||
modelSelectionByProvider: nextMap,
|
||||
activeProvider: nextActiveProvider,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
delete nextDraftsByThreadId[threadId];
|
||||
} else {
|
||||
nextDraftsByThreadId[threadId] = nextDraft;
|
||||
}
|
||||
return { draftsByThreadId: nextDraftsByThreadId };
|
||||
});
|
||||
},
|
||||
setModelOptions: (threadId, modelOptions) => {
|
||||
if (threadId.length === 0) {
|
||||
return;
|
||||
}
|
||||
const normalizedOpts = normalizeProviderModelOptions(modelOptions);
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
if (!existing && normalizedOpts === null) {
|
||||
return state;
|
||||
}
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
for (const provider of ["codex", "claudeAgent"] as const) {
|
||||
// Only touch providers explicitly present in the input
|
||||
if (!normalizedOpts || !(provider in normalizedOpts)) continue;
|
||||
const opts = normalizedOpts[provider];
|
||||
const current = nextMap[provider];
|
||||
if (opts) {
|
||||
nextMap[provider] = {
|
||||
provider,
|
||||
model: current?.model ?? getDefaultModel(provider),
|
||||
options: opts,
|
||||
};
|
||||
} else if (current?.options) {
|
||||
// Remove options but keep the selection
|
||||
const { options: _, ...rest } = current;
|
||||
nextMap[provider] = rest as ModelSelection;
|
||||
}
|
||||
}
|
||||
if (Equal.equals(base.modelSelectionByProvider, nextMap)) {
|
||||
return state;
|
||||
}
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelectionByProvider: nextMap,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1301,46 +1709,67 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (normalizedProvider === null) {
|
||||
return;
|
||||
}
|
||||
// Normalize just this provider's options
|
||||
const normalizedOpts = normalizeProviderModelOptions(
|
||||
{ [normalizedProvider]: nextProviderOptions },
|
||||
normalizedProvider,
|
||||
);
|
||||
const providerOpts = normalizedOpts?.[normalizedProvider];
|
||||
|
||||
set((state) => {
|
||||
const existing = state.draftsByThreadId[threadId];
|
||||
const base = existing ?? createEmptyThreadDraft();
|
||||
if (base.modelSelection?.provider !== normalizedProvider) {
|
||||
return state;
|
||||
|
||||
// Update the map entry for this provider
|
||||
const nextMap = { ...base.modelSelectionByProvider };
|
||||
const currentForProvider = nextMap[normalizedProvider];
|
||||
if (providerOpts) {
|
||||
nextMap[normalizedProvider] = {
|
||||
provider: normalizedProvider,
|
||||
model: currentForProvider?.model ?? getDefaultModel(normalizedProvider),
|
||||
options: providerOpts,
|
||||
};
|
||||
} else if (currentForProvider?.options) {
|
||||
const { options: _, ...rest } = currentForProvider;
|
||||
nextMap[normalizedProvider] = rest as ModelSelection;
|
||||
}
|
||||
|
||||
// Handle sticky persistence
|
||||
let nextStickyMap = state.stickyModelSelectionByProvider;
|
||||
let nextStickyActiveProvider = state.stickyActiveProvider;
|
||||
if (options?.persistSticky === true) {
|
||||
nextStickyMap = { ...state.stickyModelSelectionByProvider };
|
||||
const stickyBase =
|
||||
nextStickyMap[normalizedProvider] ??
|
||||
base.modelSelectionByProvider[normalizedProvider] ??
|
||||
({
|
||||
provider: normalizedProvider,
|
||||
model: getDefaultModel(normalizedProvider),
|
||||
} as ModelSelection);
|
||||
if (providerOpts) {
|
||||
nextStickyMap[normalizedProvider] = {
|
||||
...stickyBase,
|
||||
provider: normalizedProvider,
|
||||
options: providerOpts,
|
||||
};
|
||||
} else if (stickyBase.options) {
|
||||
const { options: _, ...rest } = stickyBase;
|
||||
nextStickyMap[normalizedProvider] = rest as ModelSelection;
|
||||
}
|
||||
nextStickyActiveProvider = base.activeProvider ?? normalizedProvider;
|
||||
}
|
||||
const nextProviderModelOptions = replaceProviderModelOptions(
|
||||
base.modelSelection?.options
|
||||
? { [normalizedProvider]: base.modelSelection.options }
|
||||
: null,
|
||||
normalizedProvider,
|
||||
nextProviderOptions,
|
||||
);
|
||||
const nextOptions =
|
||||
normalizedProvider === "codex"
|
||||
? nextProviderModelOptions?.codex
|
||||
: nextProviderModelOptions?.claudeAgent;
|
||||
const nextModelSelection =
|
||||
base.modelSelection === null
|
||||
? null
|
||||
: {
|
||||
provider: base.modelSelection.provider,
|
||||
model: base.modelSelection.model,
|
||||
...(nextOptions ? { options: nextOptions } : {}),
|
||||
};
|
||||
const nextStickyModelSelection =
|
||||
options?.persistSticky === true && nextModelSelection !== null
|
||||
? nextModelSelection
|
||||
: state.stickyModelSelection;
|
||||
|
||||
if (
|
||||
Equal.equals(base.modelSelection, nextModelSelection) &&
|
||||
Equal.equals(state.stickyModelSelection, nextStickyModelSelection)
|
||||
Equal.equals(base.modelSelectionByProvider, nextMap) &&
|
||||
Equal.equals(state.stickyModelSelectionByProvider, nextStickyMap) &&
|
||||
state.stickyActiveProvider === nextStickyActiveProvider
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
|
||||
const nextDraft: ComposerThreadDraftState = {
|
||||
...base,
|
||||
modelSelection: nextModelSelection,
|
||||
modelSelectionByProvider: nextMap,
|
||||
};
|
||||
const nextDraftsByThreadId = { ...state.draftsByThreadId };
|
||||
if (shouldRemoveDraft(nextDraft)) {
|
||||
@@ -1352,7 +1781,10 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
return {
|
||||
draftsByThreadId: nextDraftsByThreadId,
|
||||
...(options?.persistSticky === true
|
||||
? { stickyModelSelection: nextStickyModelSelection }
|
||||
? {
|
||||
stickyModelSelectionByProvider: nextStickyMap,
|
||||
stickyActiveProvider: nextStickyActiveProvider,
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
});
|
||||
@@ -1711,7 +2143,8 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
draftsByThreadId,
|
||||
draftThreadsByThreadId: normalizedPersisted.draftThreadsByThreadId,
|
||||
projectDraftThreadIdByProjectId: normalizedPersisted.projectDraftThreadIdByProjectId,
|
||||
stickyModelSelection: normalizedPersisted.stickyModelSelection as ModelSelection | null,
|
||||
stickyModelSelectionByProvider: normalizedPersisted.stickyModelSelectionByProvider ?? {},
|
||||
stickyActiveProvider: normalizedPersisted.stickyActiveProvider ?? null,
|
||||
};
|
||||
},
|
||||
},
|
||||
@@ -1722,6 +2155,34 @@ export function useComposerThreadDraft(threadId: ThreadId): ComposerThreadDraftS
|
||||
return useComposerDraftStore((state) => state.draftsByThreadId[threadId] ?? EMPTY_THREAD_DRAFT);
|
||||
}
|
||||
|
||||
export function useEffectiveComposerModelState(input: {
|
||||
threadId: ThreadId;
|
||||
selectedProvider: ProviderKind;
|
||||
threadModelSelection: ModelSelection | null | undefined;
|
||||
projectModelSelection: ModelSelection | null | undefined;
|
||||
customModelsByProvider: Record<ProviderKind, readonly string[]>;
|
||||
}): EffectiveComposerModelState {
|
||||
const draft = useComposerThreadDraft(input.threadId);
|
||||
|
||||
return useMemo(
|
||||
() =>
|
||||
deriveEffectiveComposerModelState({
|
||||
draft,
|
||||
selectedProvider: input.selectedProvider,
|
||||
threadModelSelection: input.threadModelSelection,
|
||||
projectModelSelection: input.projectModelSelection,
|
||||
customModelsByProvider: input.customModelsByProvider,
|
||||
}),
|
||||
[
|
||||
draft,
|
||||
input.customModelsByProvider,
|
||||
input.projectModelSelection,
|
||||
input.selectedProvider,
|
||||
input.threadModelSelection,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear draft threads that have been promoted to server threads.
|
||||
*
|
||||
|
||||
@@ -12,7 +12,6 @@ import { useStore } from "../store";
|
||||
export function useHandleNewThread() {
|
||||
const projects = useStore((store) => store.projects);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const stickyModelSelection = useComposerDraftStore((store) => store.stickyModelSelection);
|
||||
const navigate = useNavigate();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
@@ -39,7 +38,7 @@ export function useHandleNewThread() {
|
||||
clearProjectDraftThreadId,
|
||||
getDraftThread,
|
||||
getDraftThreadByProjectId,
|
||||
setModelSelection,
|
||||
applyStickyState,
|
||||
setDraftThreadContext,
|
||||
setProjectDraftThreadId,
|
||||
} = useComposerDraftStore.getState();
|
||||
@@ -98,9 +97,7 @@ export function useHandleNewThread() {
|
||||
envMode: options?.envMode ?? "local",
|
||||
runtimeMode: DEFAULT_RUNTIME_MODE,
|
||||
});
|
||||
if (stickyModelSelection) {
|
||||
setModelSelection(threadId, stickyModelSelection);
|
||||
}
|
||||
applyStickyState(threadId);
|
||||
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
@@ -108,7 +105,7 @@ export function useHandleNewThread() {
|
||||
});
|
||||
})();
|
||||
},
|
||||
[navigate, routeThreadId, stickyModelSelection],
|
||||
[navigate, routeThreadId],
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* Unified settings hook.
|
||||
*
|
||||
* Abstracts the split between server-authoritative settings (persisted in
|
||||
* `settings.json` on the server, fetched via `server.getConfig`) and
|
||||
* client-only settings (persisted in localStorage).
|
||||
*
|
||||
* Consumers use `useSettings(selector)` to read, and `useUpdateSettings()` to
|
||||
* write. The hook transparently routes reads/writes to the correct backing
|
||||
* store.
|
||||
*/
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ServerSettings, ServerSettingsPatch, ServerConfig } from "@t3tools/contracts";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
|
||||
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
|
||||
import { ensureNativeApi } from "~/nativeApi";
|
||||
import { useLocalStorage } from "./useLocalStorage";
|
||||
import {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
} from "~/clientSettings";
|
||||
import { Struct } from "effect";
|
||||
|
||||
// ── Unified type ─────────────────────────────────────────────────────
|
||||
|
||||
export type UnifiedSettings = ServerSettings & ClientSettings;
|
||||
|
||||
// ── Key sets for routing patches ─────────────────────────────────────
|
||||
|
||||
const SERVER_SETTINGS_KEYS = new Set<string>(Struct.keys(ServerSettings.fields));
|
||||
|
||||
function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||
serverPatch: ServerSettingsPatch;
|
||||
clientPatch: Partial<ClientSettings>;
|
||||
} {
|
||||
const serverPatch: Record<string, unknown> = {};
|
||||
const clientPatch: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(patch)) {
|
||||
if (SERVER_SETTINGS_KEYS.has(key)) {
|
||||
serverPatch[key] = value;
|
||||
} else {
|
||||
clientPatch[key] = value;
|
||||
}
|
||||
}
|
||||
return {
|
||||
serverPatch: serverPatch as ServerSettingsPatch,
|
||||
clientPatch: clientPatch as Partial<ClientSettings>,
|
||||
};
|
||||
}
|
||||
|
||||
// ── Hooks ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Read merged settings. Selector narrows the subscription so components
|
||||
* only re-render when the slice they care about changes.
|
||||
*/
|
||||
|
||||
export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
|
||||
selector?: (s: UnifiedSettings) => T,
|
||||
): T {
|
||||
const { data: serverConfig } = useQuery(serverConfigQueryOptions());
|
||||
const [clientSettings] = useLocalStorage(
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
ClientSettingsSchema,
|
||||
);
|
||||
|
||||
const merged = useMemo<UnifiedSettings>(
|
||||
() => ({
|
||||
...(serverConfig?.settings ?? DEFAULT_SERVER_SETTINGS),
|
||||
...clientSettings,
|
||||
}),
|
||||
[serverConfig?.settings, clientSettings],
|
||||
);
|
||||
|
||||
return useMemo(() => (selector ? selector(merged) : (merged as T)), [merged, selector]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an updater that routes each key to the correct backing store.
|
||||
*
|
||||
* Server keys are optimistically patched in the React Query cache, then
|
||||
* persisted via RPC. Client keys go straight to localStorage.
|
||||
*/
|
||||
export function useUpdateSettings() {
|
||||
const queryClient = useQueryClient();
|
||||
const [, setClientSettings] = useLocalStorage(
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
ClientSettingsSchema,
|
||||
);
|
||||
|
||||
const updateSettings = useCallback(
|
||||
(patch: Partial<UnifiedSettings>) => {
|
||||
const { serverPatch, clientPatch } = splitPatch(patch);
|
||||
|
||||
if (Object.keys(serverPatch).length > 0) {
|
||||
// Optimistic update of the React Query cache
|
||||
queryClient.setQueryData<ServerConfig>(serverQueryKeys.config(), (old) => {
|
||||
if (!old) return old;
|
||||
return {
|
||||
...old,
|
||||
settings: { ...old.settings, ...serverPatch },
|
||||
};
|
||||
});
|
||||
// Fire-and-forget RPC — push will reconcile on success
|
||||
void ensureNativeApi().server.updateSettings(serverPatch);
|
||||
}
|
||||
|
||||
if (Object.keys(clientPatch).length > 0) {
|
||||
setClientSettings((prev) => ({ ...prev, ...clientPatch }));
|
||||
}
|
||||
},
|
||||
[queryClient, setClientSettings],
|
||||
);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
updateSettings({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
});
|
||||
}, [updateSettings]);
|
||||
|
||||
return {
|
||||
updateSettings,
|
||||
resetSettings,
|
||||
defaults: { ...DEFAULT_SERVER_SETTINGS, ...DEFAULT_CLIENT_SETTINGS } as UnifiedSettings,
|
||||
};
|
||||
}
|
||||
|
||||
// ── One-time migration from localStorage ─────────────────────────────
|
||||
|
||||
const MIGRATION_FLAG_KEY = "t3code:settings-migrated:v1";
|
||||
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
|
||||
|
||||
/**
|
||||
* Call once on app startup. Migrates server-relevant settings from the
|
||||
* old localStorage key to the server. Idempotent.
|
||||
*/
|
||||
export function migrateLocalSettingsToServer(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
if (localStorage.getItem(MIGRATION_FLAG_KEY)) return;
|
||||
|
||||
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
|
||||
if (!raw) {
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const old = JSON.parse(raw) as Record<string, unknown>;
|
||||
const serverPatch: Record<string, unknown> = {};
|
||||
for (const key of SERVER_SETTINGS_KEYS) {
|
||||
if (key in old && old[key] !== undefined) {
|
||||
serverPatch[key] = old[key];
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate old flat binary-path keys into their new nested shape
|
||||
const codexBinaryPath = old["codexBinaryPath"];
|
||||
const codexHomePath = old["codexHomePath"];
|
||||
const claudeBinaryPath = old["claudeBinaryPath"];
|
||||
|
||||
if (
|
||||
(typeof codexBinaryPath === "string" && codexBinaryPath) ||
|
||||
(typeof codexHomePath === "string" && codexHomePath)
|
||||
) {
|
||||
const existing = (serverPatch["codex"] as Record<string, unknown> | undefined) ?? {};
|
||||
serverPatch["codex"] = {
|
||||
...existing,
|
||||
...(typeof codexBinaryPath === "string" && codexBinaryPath
|
||||
? { binaryPath: codexBinaryPath }
|
||||
: {}),
|
||||
...(typeof codexHomePath === "string" && codexHomePath ? { homePath: codexHomePath } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof claudeBinaryPath === "string" && claudeBinaryPath) {
|
||||
const existing = (serverPatch["claude"] as Record<string, unknown> | undefined) ?? {};
|
||||
serverPatch["claude"] = {
|
||||
...existing,
|
||||
binaryPath: claudeBinaryPath,
|
||||
};
|
||||
}
|
||||
|
||||
if (Object.keys(serverPatch).length > 0) {
|
||||
void ensureNativeApi()
|
||||
.server.updateSettings(serverPatch as ServerSettingsPatch)
|
||||
.then(() => {
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
});
|
||||
} else {
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, mark as migrated to avoid retrying
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,14 @@ describe("git mutation options", () => {
|
||||
const queryClient = new QueryClient();
|
||||
|
||||
it("attaches cwd-scoped mutation key for runStackedAction", () => {
|
||||
const options = gitRunStackedActionMutationOptions({ cwd: "/repo/a", queryClient });
|
||||
const options = gitRunStackedActionMutationOptions({
|
||||
cwd: "/repo/a",
|
||||
queryClient,
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
});
|
||||
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
|
||||
});
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { GitStackedAction } from "@t3tools/contracts";
|
||||
import { type GitStackedAction, type ModelSelection } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
import { ensureNativeApi } from "../nativeApi";
|
||||
|
||||
@@ -112,7 +112,7 @@ export function gitCheckoutMutationOptions(input: {
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
model?: string | null;
|
||||
modelSelection: ModelSelection;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
@@ -134,11 +134,11 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
return api.git.runStackedAction({
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
modelSelection: input.modelSelection,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
...(filePaths ? { filePaths } : {}),
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
});
|
||||
},
|
||||
onSettled: async () => {
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultModel,
|
||||
getModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveSelectableModel,
|
||||
} from "@t3tools/shared/model";
|
||||
import { getComposerProviderState } from "./components/chat/composerProviderRegistry";
|
||||
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
|
||||
export type CustomModelSettings = {
|
||||
customCodexModels: readonly string[];
|
||||
customClaudeModels: readonly string[];
|
||||
};
|
||||
|
||||
export type ProviderCustomModelConfig = {
|
||||
provider: ProviderKind;
|
||||
settingsKey: keyof CustomModelSettings;
|
||||
defaultSettingsKey: keyof CustomModelSettings;
|
||||
title: string;
|
||||
description: string;
|
||||
placeholder: string;
|
||||
example: string;
|
||||
};
|
||||
|
||||
export interface AppModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
isCustom: boolean;
|
||||
}
|
||||
|
||||
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",
|
||||
},
|
||||
};
|
||||
|
||||
const BUILT_IN_MODEL_SLUGS_BY_PROVIDER: Record<ProviderKind, ReadonlySet<string>> = {
|
||||
codex: new Set(getModelOptions("codex").map((option) => option.slug)),
|
||||
claudeAgent: new Set(getModelOptions("claudeAgent").map((option) => option.slug)),
|
||||
};
|
||||
|
||||
export 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;
|
||||
}
|
||||
|
||||
export function getCustomModelsForProvider(
|
||||
settings: CustomModelSettings,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return settings[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey];
|
||||
}
|
||||
|
||||
export function getDefaultCustomModelsForProvider(
|
||||
defaults: CustomModelSettings,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return defaults[PROVIDER_CUSTOM_MODEL_CONFIG[provider].defaultSettingsKey];
|
||||
}
|
||||
|
||||
export function patchCustomModels(
|
||||
provider: ProviderKind,
|
||||
models: string[],
|
||||
): Partial<CustomModelSettings> {
|
||||
return {
|
||||
[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey]: models,
|
||||
};
|
||||
}
|
||||
|
||||
export function getCustomModelsByProvider(
|
||||
settings: CustomModelSettings,
|
||||
): 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: CustomModelSettings,
|
||||
selectedProvider?: ProviderKind | null,
|
||||
selectedModel?: string | null,
|
||||
): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
const customModelsByProvider = getCustomModelsByProvider(settings);
|
||||
return {
|
||||
codex: getAppModelOptions(
|
||||
"codex",
|
||||
customModelsByProvider.codex,
|
||||
selectedProvider === "codex" ? selectedModel : undefined,
|
||||
),
|
||||
claudeAgent: getAppModelOptions(
|
||||
"claudeAgent",
|
||||
customModelsByProvider.claudeAgent,
|
||||
selectedProvider === "claudeAgent" ? selectedModel : undefined,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAppModelSelectionState(
|
||||
settings: CustomModelSettings & {
|
||||
textGenerationModelSelection: ModelSelection | undefined;
|
||||
},
|
||||
): ModelSelection {
|
||||
const selection = settings.textGenerationModelSelection ?? {
|
||||
provider: "codex" as const,
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
||||
};
|
||||
const provider = selection.provider;
|
||||
const customModelsByProvider = getCustomModelsByProvider(settings);
|
||||
const model = resolveAppModelSelection(provider, customModelsByProvider, selection.model);
|
||||
const { modelOptionsForDispatch } = getComposerProviderState({
|
||||
provider,
|
||||
model,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
[provider]: selection.options,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
...(modelOptionsForDispatch ? { options: modelOptionsForDispatch } : {}),
|
||||
};
|
||||
}
|
||||
@@ -21,6 +21,7 @@ import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
|
||||
@@ -230,6 +231,8 @@ function EventRouter() {
|
||||
);
|
||||
});
|
||||
const unsubWelcome = onServerWelcome((payload) => {
|
||||
// Migrate old localStorage settings to server on first connect
|
||||
migrateLocalSettingsToServer();
|
||||
void (async () => {
|
||||
await syncSnapshot();
|
||||
if (disposed) {
|
||||
|
||||
@@ -2,16 +2,17 @@ import { createFileRoute } from "@tanstack/react-router";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { ChevronDownIcon, PlusIcon, RotateCcwIcon, Undo2Icon, XIcon } from "lucide-react";
|
||||
import { type ReactNode, useCallback, useState } from "react";
|
||||
import { type ProviderKind, DEFAULT_GIT_TEXT_GENERATION_MODEL } from "@t3tools/contracts";
|
||||
import { type ProviderKind } from "@t3tools/contracts";
|
||||
import { getModelOptions, normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import {
|
||||
getAppModelOptions,
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsForProvider,
|
||||
MAX_CUSTOM_MODEL_LENGTH,
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
patchCustomModels,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
resolveAppModelSelectionState,
|
||||
} from "../modelSelection";
|
||||
import { APP_VERSION } from "../branding";
|
||||
import { Button } from "../components/ui/button";
|
||||
import { Collapsible, CollapsibleContent } from "../components/ui/collapsible";
|
||||
@@ -25,6 +26,8 @@ import {
|
||||
} from "../components/ui/select";
|
||||
import { SidebarTrigger } from "../components/ui/sidebar";
|
||||
import { Switch } from "../components/ui/switch";
|
||||
import { ProviderModelPicker } from "../components/chat/ProviderModelPicker";
|
||||
import { TraitsPicker } from "../components/chat/TraitsPicker";
|
||||
import { SidebarInset } from "../components/ui/sidebar";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../components/ui/tooltip";
|
||||
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
|
||||
@@ -192,8 +195,8 @@ function SettingsRouteView() {
|
||||
const [isOpeningKeybindings, setIsOpeningKeybindings] = useState(false);
|
||||
const [openKeybindingsError, setOpenKeybindingsError] = useState<string | null>(null);
|
||||
const [openInstallProviders, setOpenInstallProviders] = useState<Record<ProviderKind, boolean>>({
|
||||
codex: Boolean(settings.codexBinaryPath || settings.codexHomePath),
|
||||
claudeAgent: Boolean(settings.claudeBinaryPath),
|
||||
codex: Boolean(settings.codex?.binaryPath || settings.codex?.homePath),
|
||||
claudeAgent: Boolean(settings.claude?.binaryPath),
|
||||
});
|
||||
const [selectedCustomModelProvider, setSelectedCustomModelProvider] =
|
||||
useState<ProviderKind>("codex");
|
||||
@@ -208,26 +211,21 @@ function SettingsRouteView() {
|
||||
>({});
|
||||
const [showAllCustomModels, setShowAllCustomModels] = useState(false);
|
||||
|
||||
const codexBinaryPath = settings.codexBinaryPath;
|
||||
const codexHomePath = settings.codexHomePath;
|
||||
const claudeBinaryPath = settings.claudeBinaryPath;
|
||||
const codexBinaryPath = settings.codex?.binaryPath ?? "";
|
||||
const codexHomePath = settings.codex?.homePath ?? "";
|
||||
const claudeBinaryPath = settings.claude?.binaryPath ?? "";
|
||||
const keybindingsConfigPath = serverConfigQuery.data?.keybindingsConfigPath ?? null;
|
||||
const availableEditors = serverConfigQuery.data?.availableEditors;
|
||||
|
||||
const gitTextGenerationModelOptions = getAppModelOptions(
|
||||
"codex",
|
||||
settings.customCodexModels,
|
||||
settings.textGenerationModel,
|
||||
const textGenerationModelSelection = resolveAppModelSelectionState(settings);
|
||||
const textGenProvider = textGenerationModelSelection.provider;
|
||||
const textGenModel = textGenerationModelSelection.model;
|
||||
const textGenModelOptions = textGenerationModelSelection.options;
|
||||
const gitModelOptionsByProvider = getCustomModelOptionsByProvider(
|
||||
settings,
|
||||
textGenProvider,
|
||||
textGenModel,
|
||||
);
|
||||
const currentGitTextGenerationModel =
|
||||
settings.textGenerationModel ?? DEFAULT_GIT_TEXT_GENERATION_MODEL;
|
||||
const defaultGitTextGenerationModel =
|
||||
defaults.textGenerationModel ?? DEFAULT_GIT_TEXT_GENERATION_MODEL;
|
||||
const isGitTextGenerationModelDirty =
|
||||
currentGitTextGenerationModel !== defaultGitTextGenerationModel;
|
||||
const selectedGitTextGenerationModelLabel =
|
||||
gitTextGenerationModelOptions.find((option) => option.slug === currentGitTextGenerationModel)
|
||||
?.name ?? currentGitTextGenerationModel;
|
||||
const selectedCustomModelProviderSettings = MODEL_PROVIDER_SETTINGS.find(
|
||||
(providerSettings) => providerSettings.provider === selectedCustomModelProvider,
|
||||
)!;
|
||||
@@ -246,9 +244,9 @@ function SettingsRouteView() {
|
||||
? savedCustomModelRows
|
||||
: savedCustomModelRows.slice(0, 5);
|
||||
const isInstallSettingsDirty =
|
||||
settings.claudeBinaryPath !== defaults.claudeBinaryPath ||
|
||||
settings.codexBinaryPath !== defaults.codexBinaryPath ||
|
||||
settings.codexHomePath !== defaults.codexHomePath;
|
||||
settings.claude?.binaryPath !== defaults.claude?.binaryPath ||
|
||||
settings.codex?.binaryPath !== defaults.codex?.binaryPath ||
|
||||
settings.codex?.homePath !== defaults.codex?.homePath;
|
||||
const changedSettingLabels = [
|
||||
...(theme !== "system" ? ["Theme"] : []),
|
||||
...(settings.timestampFormat !== defaults.timestampFormat ? ["Time format"] : []),
|
||||
@@ -260,7 +258,10 @@ function SettingsRouteView() {
|
||||
...(settings.confirmThreadDelete !== defaults.confirmThreadDelete
|
||||
? ["Delete confirmation"]
|
||||
: []),
|
||||
...(isGitTextGenerationModelDirty ? ["Git writing model"] : []),
|
||||
...(JSON.stringify(settings.textGenerationModelSelection ?? null) !==
|
||||
JSON.stringify(defaults.textGenerationModelSelection ?? null)
|
||||
? ["Git writing model"]
|
||||
: []),
|
||||
...(settings.customCodexModels.length > 0 || settings.customClaudeModels.length > 0
|
||||
? ["Custom models"]
|
||||
: []),
|
||||
@@ -631,43 +632,61 @@ function SettingsRouteView() {
|
||||
<SettingsSection title="Models">
|
||||
<SettingsRow
|
||||
title="Git writing model"
|
||||
description="Used for generated commit messages, PR titles, and branch names."
|
||||
description="Provider and model used for auto-generated git content."
|
||||
resetAction={
|
||||
isGitTextGenerationModelDirty ? (
|
||||
JSON.stringify(settings.textGenerationModelSelection ?? null) !==
|
||||
JSON.stringify(defaults.textGenerationModelSelection ?? null) ? (
|
||||
<SettingResetButton
|
||||
label="git writing model"
|
||||
onClick={() =>
|
||||
onClick={() => {
|
||||
updateSettings({
|
||||
textGenerationModel: defaults.textGenerationModel,
|
||||
})
|
||||
}
|
||||
textGenerationModelSelection: defaults.textGenerationModelSelection,
|
||||
});
|
||||
}}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={currentGitTextGenerationModel}
|
||||
onValueChange={(value) => {
|
||||
if (!value) return;
|
||||
updateSettings({
|
||||
textGenerationModel: value,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SelectTrigger
|
||||
className="w-full sm:w-52"
|
||||
aria-label="Git text generation model"
|
||||
>
|
||||
<SelectValue>{selectedGitTextGenerationModelLabel}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{gitTextGenerationModelOptions.map((option) => (
|
||||
<SelectItem hideIndicator key={option.slug} value={option.slug}>
|
||||
{option.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
<div className="flex flex-wrap items-center justify-end gap-1.5">
|
||||
<ProviderModelPicker
|
||||
provider={textGenProvider}
|
||||
model={textGenModel}
|
||||
lockedProvider={null}
|
||||
modelOptionsByProvider={gitModelOptionsByProvider}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onProviderModelChange={(provider, model) => {
|
||||
updateSettings({
|
||||
textGenerationModelSelection: resolveAppModelSelectionState({
|
||||
...settings,
|
||||
textGenerationModelSelection: { provider, model },
|
||||
}),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
<TraitsPicker
|
||||
provider={textGenProvider}
|
||||
model={textGenModel}
|
||||
prompt=""
|
||||
onPromptChange={() => {}}
|
||||
modelOptions={textGenModelOptions}
|
||||
allowPromptInjectedEffort={false}
|
||||
triggerVariant="outline"
|
||||
triggerClassName="min-w-0 max-w-none shrink-0 text-foreground/90 hover:text-foreground"
|
||||
onModelOptionsChange={(nextOptions) => {
|
||||
updateSettings({
|
||||
textGenerationModelSelection: resolveAppModelSelectionState({
|
||||
...settings,
|
||||
textGenerationModelSelection: {
|
||||
provider: textGenProvider,
|
||||
model: textGenModel,
|
||||
...(nextOptions ? { options: nextOptions } : {}),
|
||||
},
|
||||
}),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -812,9 +831,11 @@ function SettingsRouteView() {
|
||||
label="provider installs"
|
||||
onClick={() => {
|
||||
updateSettings({
|
||||
claudeBinaryPath: defaults.claudeBinaryPath,
|
||||
codexBinaryPath: defaults.codexBinaryPath,
|
||||
codexHomePath: defaults.codexHomePath,
|
||||
claude: { binaryPath: defaults.claude?.binaryPath ?? "" },
|
||||
codex: {
|
||||
binaryPath: defaults.codex?.binaryPath ?? "",
|
||||
homePath: defaults.codex?.homePath ?? "",
|
||||
},
|
||||
});
|
||||
setOpenInstallProviders({
|
||||
codex: false,
|
||||
@@ -831,12 +852,12 @@ function SettingsRouteView() {
|
||||
const isOpen = openInstallProviders[providerSettings.provider];
|
||||
const isDirty =
|
||||
providerSettings.provider === "codex"
|
||||
? settings.codexBinaryPath !== defaults.codexBinaryPath ||
|
||||
settings.codexHomePath !== defaults.codexHomePath
|
||||
: settings.claudeBinaryPath !== defaults.claudeBinaryPath;
|
||||
? settings.codex?.binaryPath !== defaults.codex?.binaryPath ||
|
||||
settings.codex?.homePath !== defaults.codex?.homePath
|
||||
: settings.claude?.binaryPath !== defaults.claude?.binaryPath;
|
||||
const binaryPathValue =
|
||||
providerSettings.binaryPathKey === "claudeBinaryPath"
|
||||
? claudeBinaryPath
|
||||
? (settings.claude?.binaryPath ?? "")
|
||||
: codexBinaryPath;
|
||||
|
||||
return (
|
||||
@@ -891,9 +912,19 @@ function SettingsRouteView() {
|
||||
value={binaryPathValue}
|
||||
onChange={(event) =>
|
||||
updateSettings(
|
||||
providerSettings.binaryPathKey === "claudeBinaryPath"
|
||||
? { claudeBinaryPath: event.target.value }
|
||||
: { codexBinaryPath: event.target.value },
|
||||
providerSettings.provider === "claudeAgent"
|
||||
? {
|
||||
claude: {
|
||||
...settings.claude,
|
||||
binaryPath: event.target.value,
|
||||
},
|
||||
}
|
||||
: {
|
||||
codex: {
|
||||
...settings.codex,
|
||||
binaryPath: event.target.value,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
placeholder={providerSettings.binaryPlaceholder}
|
||||
@@ -918,7 +949,10 @@ function SettingsRouteView() {
|
||||
value={codexHomePath}
|
||||
onChange={(event) =>
|
||||
updateSettings({
|
||||
codexHomePath: event.target.value,
|
||||
codex: {
|
||||
...settings.codex,
|
||||
homePath: event.target.value,
|
||||
},
|
||||
})
|
||||
}
|
||||
placeholder={providerSettings.homePlaceholder}
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
import { Fragment, type ReactNode, createElement, useEffect } from "react";
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
ThreadId,
|
||||
type OrchestrationReadModel,
|
||||
@@ -326,26 +324,6 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveModelSelection(
|
||||
modelSelection: ModelSelection | null | undefined,
|
||||
fallbackProvider: ProviderKind,
|
||||
fallbackModel?: string | null,
|
||||
): ModelSelection {
|
||||
if (modelSelection) {
|
||||
return {
|
||||
...modelSelection,
|
||||
model: resolveModelSlugForProvider(modelSelection.provider, modelSelection.model),
|
||||
};
|
||||
}
|
||||
return {
|
||||
provider: fallbackProvider,
|
||||
model: resolveModelSlugForProvider(
|
||||
fallbackProvider,
|
||||
fallbackModel ?? DEFAULT_MODEL_BY_PROVIDER[fallbackProvider],
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadVisited(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
|
||||
@@ -353,11 +353,27 @@ describe("wsNativeApi", () => {
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
const api = createWsNativeApi();
|
||||
await api.git.runStackedAction({ actionId: "action-1", cwd: "/repo", action: "commit" });
|
||||
await api.git.runStackedAction({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
});
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(
|
||||
WS_METHODS.gitRunStackedAction,
|
||||
{ actionId: "action-1", cwd: "/repo", action: "commit" },
|
||||
{
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
},
|
||||
{ timeoutMs: null },
|
||||
);
|
||||
});
|
||||
|
||||
@@ -179,6 +179,8 @@ export function createWsNativeApi(): NativeApi {
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
getSettings: () => transport.request(WS_METHODS.serverGetSettings),
|
||||
updateSettings: (patch) => transport.request(WS_METHODS.serverUpdateSettings, { patch }),
|
||||
},
|
||||
orchestration: {
|
||||
getSnapshot: () => transport.request(ORCHESTRATION_WS_METHODS.getSnapshot),
|
||||
|
||||
@@ -65,9 +65,28 @@ describe("GitRunStackedActionInput", () => {
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.actionId).toBe("action-1");
|
||||
expect(parsed.action).toBe("commit");
|
||||
});
|
||||
|
||||
it("accepts git text generation as a modelSelection", () => {
|
||||
const parsed = decodeRunStackedActionInput({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit_push_pr",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.modelSelection?.provider).toBe("claudeAgent");
|
||||
expect(parsed.modelSelection?.model).toBe("claude-haiku-4-5");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Option, Schema } from "effect";
|
||||
import { Schema } from "effect";
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL } from "./model";
|
||||
import { ModelSelection } from "./orchestration";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
|
||||
@@ -80,9 +80,7 @@ export const GitRunStackedActionInput = Schema.Struct({
|
||||
filePaths: Schema.optional(
|
||||
Schema.Array(TrimmedNonEmptyStringSchema).check(Schema.isMinLength(1)),
|
||||
),
|
||||
textGenerationModel: Schema.optional(TrimmedNonEmptyStringSchema).pipe(
|
||||
Schema.withConstructorDefault(() => Option.some(DEFAULT_GIT_TEXT_GENERATION_MODEL)),
|
||||
),
|
||||
modelSelection: ModelSelection,
|
||||
});
|
||||
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import type {
|
||||
ProjectWriteFileInput,
|
||||
ProjectWriteFileResult,
|
||||
} from "./project";
|
||||
import type { ServerConfig } from "./server";
|
||||
import type { ServerConfig, ServerSettings, ServerSettingsPatch } from "./server";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -161,6 +161,8 @@ export interface NativeApi {
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
getSettings: () => Promise<ServerSettings>;
|
||||
updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
|
||||
};
|
||||
orchestration: {
|
||||
getSnapshot: () => Promise<OrchestrationReadModel>;
|
||||
|
||||
+173
-22
@@ -26,26 +26,166 @@ export const ProviderModelOptions = Schema.Struct({
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
|
||||
type ModelOption = {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
export type EffortOption = {
|
||||
readonly value: string;
|
||||
readonly label: string;
|
||||
readonly isDefault?: true;
|
||||
};
|
||||
|
||||
export type ModelCapabilities = {
|
||||
readonly reasoningEffortLevels: readonly EffortOption[];
|
||||
readonly supportsFastMode: boolean;
|
||||
readonly supportsThinkingToggle: boolean;
|
||||
readonly promptInjectedEffortLevels: readonly string[];
|
||||
};
|
||||
|
||||
type ModelDefinition = {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
readonly capabilities: ModelCapabilities;
|
||||
};
|
||||
|
||||
/**
|
||||
* TODO: This should not be a static array, each provider
|
||||
* should return its own model list over the WS API.
|
||||
*/
|
||||
export const MODEL_OPTIONS_BY_PROVIDER = {
|
||||
codex: [
|
||||
{ slug: "gpt-5.4", name: "GPT-5.4" },
|
||||
{ slug: "gpt-5.4-mini", name: "GPT-5.4 Mini" },
|
||||
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
|
||||
{ slug: "gpt-5.3-codex-spark", name: "GPT-5.3 Codex Spark" },
|
||||
{ slug: "gpt-5.2-codex", name: "GPT-5.2 Codex" },
|
||||
{ slug: "gpt-5.2", name: "GPT-5.2" },
|
||||
{
|
||||
slug: "gpt-5.4",
|
||||
name: "GPT-5.4",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.4-mini",
|
||||
name: "GPT-5.4 Mini",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex",
|
||||
name: "GPT-5.3 Codex",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "GPT-5.3 Codex Spark",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2-codex",
|
||||
name: "GPT-5.2 Codex",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.2",
|
||||
name: "GPT-5.2",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "xhigh", label: "Extra High" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "low", label: "Low" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
claudeAgent: [
|
||||
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
|
||||
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
|
||||
{ slug: "claude-haiku-4-5", name: "Claude Haiku 4.5" },
|
||||
{
|
||||
slug: "claude-opus-4-6",
|
||||
name: "Claude Opus 4.6",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "max", label: "Max" },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-sonnet-4-6",
|
||||
name: "Claude Sonnet 4.6",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [
|
||||
{ value: "low", label: "Low" },
|
||||
{ value: "medium", label: "Medium" },
|
||||
{ value: "high", label: "High", isDefault: true },
|
||||
{ value: "ultrathink", label: "Ultrathink" },
|
||||
],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
} as const satisfies Record<ProviderKind, readonly ModelOption[]>;
|
||||
} as const satisfies Record<ProviderKind, readonly ModelDefinition[]>;
|
||||
export type ModelOptionsByProvider = typeof MODEL_OPTIONS_BY_PROVIDER;
|
||||
|
||||
type BuiltInModelSlug = (typeof MODEL_OPTIONS_BY_PROVIDER)[ProviderKind][number]["slug"];
|
||||
@@ -59,7 +199,12 @@ export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, ModelSlug> = {
|
||||
// Backward compatibility for existing Codex-only call sites.
|
||||
export const MODEL_OPTIONS = MODEL_OPTIONS_BY_PROVIDER.codex;
|
||||
export const DEFAULT_MODEL = DEFAULT_MODEL_BY_PROVIDER.codex;
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini" as const;
|
||||
|
||||
/** Per-provider text generation model defaults. */
|
||||
export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
|
||||
codex: "gpt-5.4-mini",
|
||||
claudeAgent: "claude-haiku-4-5",
|
||||
};
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, ModelSlug>> = {
|
||||
codex: {
|
||||
@@ -85,12 +230,18 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
|
||||
},
|
||||
};
|
||||
|
||||
export const REASONING_EFFORT_OPTIONS_BY_PROVIDER = {
|
||||
codex: CODEX_REASONING_EFFORT_OPTIONS,
|
||||
claudeAgent: CLAUDE_CODE_EFFORT_OPTIONS,
|
||||
} as const satisfies Record<ProviderKind, readonly ProviderReasoningEffort[]>;
|
||||
// ── Model capabilities index ──────────────────────────────────────────
|
||||
|
||||
export const DEFAULT_REASONING_EFFORT_BY_PROVIDER = {
|
||||
codex: "high",
|
||||
claudeAgent: "high",
|
||||
} as const satisfies Record<ProviderKind, ProviderReasoningEffort>;
|
||||
export const MODEL_CAPABILITIES_INDEX = Object.fromEntries(
|
||||
Object.entries(MODEL_OPTIONS_BY_PROVIDER).map(([provider, models]) => [
|
||||
provider,
|
||||
Object.fromEntries(models.map((m) => [m.slug, m.capabilities])),
|
||||
]),
|
||||
) as unknown as Record<ProviderKind, Record<string, ModelCapabilities>>;
|
||||
|
||||
// ── Provider display names ────────────────────────────────────────────
|
||||
|
||||
export const PROVIDER_DISPLAY_NAMES: Record<ProviderKind, string> = {
|
||||
codex: "Codex",
|
||||
claudeAgent: "Claude",
|
||||
};
|
||||
@@ -116,24 +116,6 @@ it.effect("decodes historical project.created payloads with a default provider",
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy project.created payloads into defaultModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectCreatedPayload({
|
||||
projectId: "project-legacy-1",
|
||||
title: "Project Title",
|
||||
workspaceRoot: "/tmp/workspace",
|
||||
defaultModel: "gpt-5.4",
|
||||
scripts: [],
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.defaultModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes project.meta-updated payloads with explicit default provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectMetaUpdatedPayload({
|
||||
@@ -148,21 +130,6 @@ it.effect("decodes project.meta-updated payloads with explicit default provider"
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy project.meta-updated payloads into defaultModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeProjectMetaUpdatedPayload({
|
||||
projectId: "project-legacy-2",
|
||||
defaultProvider: "claudeAgent",
|
||||
defaultModel: "claude-opus-4-6",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.defaultModelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("rejects command fields that become empty after trim", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* Effect.exit(
|
||||
@@ -246,29 +213,6 @@ it.effect("decodes thread.created runtime mode for historical events", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.created payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadCreatedPayload({
|
||||
threadId: "thread-legacy-1",
|
||||
projectId: "project-1",
|
||||
title: "Thread title",
|
||||
model: "claude-opus-4-6",
|
||||
provider: "claudeAgent",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
});
|
||||
assert.strictEqual(parsed.runtimeMode, DEFAULT_RUNTIME_MODE);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes thread.meta-updated payloads with explicit provider", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadMetaUpdatedPayload({
|
||||
@@ -283,20 +227,6 @@ it.effect("decodes thread.meta-updated payloads with explicit provider", () =>
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.meta-updated payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadMetaUpdatedPayload({
|
||||
threadId: "thread-legacy-2",
|
||||
model: "gpt-5.4",
|
||||
updatedAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("accepts provider-scoped model options in thread.turn.start", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartCommand({
|
||||
@@ -384,21 +314,6 @@ it.effect("decodes thread.turn-start-requested source proposed plan metadata whe
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes legacy thread.turn-start-requested payloads into modelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeThreadTurnStartRequestedPayload({
|
||||
threadId: "thread-legacy-3",
|
||||
messageId: "msg-legacy-3",
|
||||
model: "gpt-5.4",
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
});
|
||||
assert.deepStrictEqual(parsed.modelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
});
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("decodes latest turn source proposed plan metadata when present", () =>
|
||||
Effect.gen(function* () {
|
||||
const parsed = yield* decodeOrchestrationLatestTurn({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Effect, Option, Schema, SchemaIssue, SchemaTransformation, Struct } from "effect";
|
||||
import { Option, Schema, SchemaIssue, Struct } from "effect";
|
||||
import { ClaudeModelOptions, CodexModelOptions } from "./model";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
@@ -60,96 +60,6 @@ export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
|
||||
|
||||
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
|
||||
export type ModelSelection = typeof ModelSelection.Type;
|
||||
const decodeModelSelectionSync = Schema.decodeUnknownSync(ModelSelection);
|
||||
|
||||
const LegacyDefaultModelSelectionFields = {
|
||||
defaultProvider: Schema.optional(ProviderKind),
|
||||
defaultModel: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
defaultModelOptions: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
} as const;
|
||||
|
||||
const LegacyThreadModelSelectionFields = {
|
||||
provider: Schema.optional(ProviderKind),
|
||||
model: Schema.optional(TrimmedNonEmptyString),
|
||||
modelOptions: Schema.optional(Schema.NullOr(Schema.Unknown)),
|
||||
} as const;
|
||||
|
||||
function invalidLegacyModelSelectionIssue(
|
||||
value: unknown,
|
||||
title: string,
|
||||
cause: unknown,
|
||||
): SchemaIssue.InvalidValue {
|
||||
return new SchemaIssue.InvalidValue(Option.some(value), {
|
||||
title,
|
||||
...(Schema.isSchemaError(cause)
|
||||
? { description: SchemaIssue.makeFormatterDefault()(cause.issue) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
type LegacyDefaultModelSelectionInput = {
|
||||
readonly defaultModelSelection?: ModelSelection | null | undefined;
|
||||
readonly defaultProvider?: ProviderKind | undefined;
|
||||
readonly defaultModel?: string | null | undefined;
|
||||
readonly defaultModelOptions?: unknown | null | undefined;
|
||||
};
|
||||
|
||||
type LegacyThreadModelSelectionInput = {
|
||||
readonly modelSelection?: ModelSelection | undefined;
|
||||
readonly provider?: ProviderKind | undefined;
|
||||
readonly model?: string | undefined;
|
||||
readonly modelOptions?: unknown | null | undefined;
|
||||
};
|
||||
|
||||
function normalizeLegacyDefaultModelSelection(
|
||||
input: LegacyDefaultModelSelectionInput,
|
||||
): Effect.Effect<ModelSelection | null, SchemaIssue.InvalidValue> {
|
||||
if (input.defaultModelSelection !== undefined) {
|
||||
return Effect.succeed(input.defaultModelSelection);
|
||||
}
|
||||
if (input.defaultModel === undefined || input.defaultModel === null) {
|
||||
return Effect.succeed(null);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: input.defaultProvider ?? DEFAULT_PROVIDER_KIND,
|
||||
model: input.defaultModel,
|
||||
...(input.defaultModelOptions != null ? { options: input.defaultModelOptions } : {}),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
invalidLegacyModelSelectionIssue(
|
||||
input,
|
||||
"Invalid legacy default model selection payload",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeLegacyThreadModelSelection(
|
||||
input: LegacyThreadModelSelectionInput,
|
||||
): Effect.Effect<ModelSelection | undefined, SchemaIssue.InvalidValue> {
|
||||
if (input.modelSelection !== undefined) {
|
||||
return Effect.succeed(input.modelSelection);
|
||||
}
|
||||
if (input.model === undefined) {
|
||||
return Effect.succeed<ModelSelection | undefined>(undefined);
|
||||
}
|
||||
return Effect.try({
|
||||
try: () =>
|
||||
decodeModelSelectionSync({
|
||||
provider: input.provider ?? DEFAULT_PROVIDER_KIND,
|
||||
model: input.model,
|
||||
...(input.modelOptions != null ? { options: input.modelOptions } : {}),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
invalidLegacyModelSelectionIssue(
|
||||
input,
|
||||
"Invalid legacy thread model selection payload",
|
||||
cause,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
export const CodexProviderStartOptions = Schema.Struct({
|
||||
binaryPath: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -492,8 +402,6 @@ export const ThreadTurnStartCommand = Schema.Struct({
|
||||
attachments: Schema.Array(ChatAttachment),
|
||||
}),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
@@ -513,8 +421,6 @@ const ClientThreadTurnStartCommand = Schema.Struct({
|
||||
attachments: Schema.Array(UploadChatAttachment),
|
||||
}),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode,
|
||||
interactionMode: ProviderInteractionMode,
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
@@ -709,7 +615,7 @@ export const OrchestrationAggregateKind = Schema.Literals(["project", "thread"])
|
||||
export type OrchestrationAggregateKind = typeof OrchestrationAggregateKind.Type;
|
||||
export const OrchestrationActorKind = Schema.Literals(["client", "server", "provider"]);
|
||||
|
||||
const ProjectCreatedPayloadCanonical = Schema.Struct({
|
||||
export const ProjectCreatedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
@@ -718,48 +624,8 @@ const ProjectCreatedPayloadCanonical = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
const ProjectCreatedPayloadSource = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
workspaceRoot: TrimmedNonEmptyString,
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
...LegacyDefaultModelSelectionFields,
|
||||
scripts: Schema.Array(ProjectScript),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectCreatedPayloadSource = typeof ProjectCreatedPayloadSource.Type;
|
||||
export const ProjectCreatedPayload = ProjectCreatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ProjectCreatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input) =>
|
||||
normalizeLegacyDefaultModelSelection(input).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
defaultModelSelection,
|
||||
scripts: input.scripts,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical) =>
|
||||
Effect.succeed({
|
||||
projectId: canonical.projectId,
|
||||
title: canonical.title,
|
||||
workspaceRoot: canonical.workspaceRoot,
|
||||
defaultModelSelection: canonical.defaultModelSelection,
|
||||
scripts: canonical.scripts,
|
||||
createdAt: canonical.createdAt,
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ProjectCreatedPayloadSource),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const ProjectMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
export const ProjectMetaUpdatedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
@@ -767,60 +633,13 @@ const ProjectMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectMetaUpdatedPayloadCanonical = typeof ProjectMetaUpdatedPayloadCanonical.Type;
|
||||
const ProjectMetaUpdatedPayloadSource = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
workspaceRoot: Schema.optional(TrimmedNonEmptyString),
|
||||
defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)),
|
||||
...LegacyDefaultModelSelectionFields,
|
||||
scripts: Schema.optional(Schema.Array(ProjectScript)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ProjectMetaUpdatedPayloadSource = typeof ProjectMetaUpdatedPayloadSource.Type;
|
||||
export const ProjectMetaUpdatedPayload = ProjectMetaUpdatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ProjectMetaUpdatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ProjectMetaUpdatedPayloadSource) =>
|
||||
normalizeLegacyDefaultModelSelection(input).pipe(
|
||||
Effect.map((defaultModelSelection) => ({
|
||||
projectId: input.projectId,
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(input.workspaceRoot !== undefined ? { workspaceRoot: input.workspaceRoot } : {}),
|
||||
...(input.defaultModelSelection !== undefined ||
|
||||
input.defaultModel !== undefined ||
|
||||
input.defaultProvider !== undefined ||
|
||||
input.defaultModelOptions !== undefined
|
||||
? { defaultModelSelection }
|
||||
: {}),
|
||||
...(input.scripts !== undefined ? { scripts: input.scripts } : {}),
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ProjectMetaUpdatedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
projectId: canonical.projectId,
|
||||
...(canonical.title !== undefined ? { title: canonical.title } : {}),
|
||||
...(canonical.workspaceRoot !== undefined
|
||||
? { workspaceRoot: canonical.workspaceRoot }
|
||||
: {}),
|
||||
...(canonical.defaultModelSelection !== undefined
|
||||
? { defaultModelSelection: canonical.defaultModelSelection }
|
||||
: {}),
|
||||
...(canonical.scripts !== undefined ? { scripts: canonical.scripts } : {}),
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ProjectMetaUpdatedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ProjectDeletedPayload = Schema.Struct({
|
||||
projectId: ProjectId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadCreatedPayloadCanonical = Schema.Struct({
|
||||
export const ThreadCreatedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
@@ -834,72 +653,13 @@ const ThreadCreatedPayloadCanonical = Schema.Struct({
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
const ThreadCreatedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
projectId: ProjectId,
|
||||
title: TrimmedNonEmptyString,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
branch: Schema.NullOr(TrimmedNonEmptyString),
|
||||
worktreePath: Schema.NullOr(TrimmedNonEmptyString),
|
||||
createdAt: IsoDateTime,
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadCreatedPayloadSource = typeof ThreadCreatedPayloadSource.Type;
|
||||
export const ThreadCreatedPayload = ThreadCreatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadCreatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.flatMap((modelSelection) =>
|
||||
modelSelection === undefined
|
||||
? Effect.fail(
|
||||
new SchemaIssue.InvalidValue(Option.some(input), {
|
||||
title: "Legacy thread.created payload is missing a model selection",
|
||||
}),
|
||||
)
|
||||
: Effect.succeed({
|
||||
threadId: input.threadId,
|
||||
projectId: input.projectId,
|
||||
title: input.title,
|
||||
modelSelection,
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
}),
|
||||
),
|
||||
),
|
||||
encode: (canonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
projectId: canonical.projectId,
|
||||
title: canonical.title,
|
||||
modelSelection: canonical.modelSelection,
|
||||
runtimeMode: canonical.runtimeMode,
|
||||
interactionMode: canonical.interactionMode,
|
||||
branch: canonical.branch,
|
||||
worktreePath: canonical.worktreePath,
|
||||
createdAt: canonical.createdAt,
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ThreadCreatedPayloadSource),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadDeletedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
deletedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
export const ThreadMetaUpdatedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
@@ -907,46 +667,6 @@ const ThreadMetaUpdatedPayloadCanonical = Schema.Struct({
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadMetaUpdatedPayloadCanonical = typeof ThreadMetaUpdatedPayloadCanonical.Type;
|
||||
const ThreadMetaUpdatedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
title: Schema.optional(TrimmedNonEmptyString),
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
branch: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
worktreePath: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
type ThreadMetaUpdatedPayloadSource = typeof ThreadMetaUpdatedPayloadSource.Type;
|
||||
export const ThreadMetaUpdatedPayload = ThreadMetaUpdatedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadMetaUpdatedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ThreadMetaUpdatedPayloadSource) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
threadId: input.threadId,
|
||||
...(input.title !== undefined ? { title: input.title } : {}),
|
||||
...(modelSelection !== undefined ? { modelSelection } : {}),
|
||||
...(input.branch !== undefined ? { branch: input.branch } : {}),
|
||||
...(input.worktreePath !== undefined ? { worktreePath: input.worktreePath } : {}),
|
||||
updatedAt: input.updatedAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ThreadMetaUpdatedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
...(canonical.title !== undefined ? { title: canonical.title } : {}),
|
||||
...(canonical.modelSelection !== undefined
|
||||
? { modelSelection: canonical.modelSelection }
|
||||
: {}),
|
||||
...(canonical.branch !== undefined ? { branch: canonical.branch } : {}),
|
||||
...(canonical.worktreePath !== undefined ? { worktreePath: canonical.worktreePath } : {}),
|
||||
updatedAt: canonical.updatedAt,
|
||||
} as ThreadMetaUpdatedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadRuntimeModeSetPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
@@ -974,7 +694,7 @@ export const ThreadMessageSentPayload = Schema.Struct({
|
||||
updatedAt: IsoDateTime,
|
||||
});
|
||||
|
||||
const ThreadTurnStartRequestedPayloadCanonical = Schema.Struct({
|
||||
export const ThreadTurnStartRequestedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
@@ -987,70 +707,6 @@ const ThreadTurnStartRequestedPayloadCanonical = Schema.Struct({
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
type ThreadTurnStartRequestedPayloadCanonical =
|
||||
typeof ThreadTurnStartRequestedPayloadCanonical.Type;
|
||||
const ThreadTurnStartRequestedPayloadSource = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
messageId: MessageId,
|
||||
modelSelection: Schema.optional(ModelSelection),
|
||||
...LegacyThreadModelSelectionFields,
|
||||
providerOptions: Schema.optional(ProviderStartOptions),
|
||||
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
|
||||
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
|
||||
interactionMode: ProviderInteractionMode.pipe(
|
||||
Schema.withDecodingDefault(() => DEFAULT_PROVIDER_INTERACTION_MODE),
|
||||
),
|
||||
sourceProposedPlan: Schema.optional(SourceProposedPlanReference),
|
||||
createdAt: IsoDateTime,
|
||||
});
|
||||
type ThreadTurnStartRequestedPayloadSource = typeof ThreadTurnStartRequestedPayloadSource.Type;
|
||||
export const ThreadTurnStartRequestedPayload = ThreadTurnStartRequestedPayloadSource.pipe(
|
||||
Schema.decodeTo(
|
||||
Schema.toType(ThreadTurnStartRequestedPayloadCanonical),
|
||||
SchemaTransformation.transformOrFail({
|
||||
decode: (input: ThreadTurnStartRequestedPayloadSource) =>
|
||||
normalizeLegacyThreadModelSelection(input).pipe(
|
||||
Effect.map((modelSelection) => ({
|
||||
threadId: input.threadId,
|
||||
messageId: input.messageId,
|
||||
...(modelSelection !== undefined ? { modelSelection } : {}),
|
||||
...(input.providerOptions !== undefined
|
||||
? { providerOptions: input.providerOptions }
|
||||
: {}),
|
||||
...(input.assistantDeliveryMode !== undefined
|
||||
? { assistantDeliveryMode: input.assistantDeliveryMode }
|
||||
: {}),
|
||||
runtimeMode: input.runtimeMode,
|
||||
interactionMode: input.interactionMode,
|
||||
...(input.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: input.sourceProposedPlan }
|
||||
: {}),
|
||||
createdAt: input.createdAt,
|
||||
})),
|
||||
),
|
||||
encode: (canonical: ThreadTurnStartRequestedPayloadCanonical) =>
|
||||
Effect.succeed({
|
||||
threadId: canonical.threadId,
|
||||
messageId: canonical.messageId,
|
||||
...(canonical.modelSelection !== undefined
|
||||
? { modelSelection: canonical.modelSelection }
|
||||
: {}),
|
||||
...(canonical.providerOptions !== undefined
|
||||
? { providerOptions: canonical.providerOptions }
|
||||
: {}),
|
||||
...(canonical.assistantDeliveryMode !== undefined
|
||||
? { assistantDeliveryMode: canonical.assistantDeliveryMode }
|
||||
: {}),
|
||||
runtimeMode: canonical.runtimeMode,
|
||||
interactionMode: canonical.interactionMode,
|
||||
...(canonical.sourceProposedPlan !== undefined
|
||||
? { sourceProposedPlan: canonical.sourceProposedPlan }
|
||||
: {}),
|
||||
createdAt: canonical.createdAt,
|
||||
} as ThreadTurnStartRequestedPayloadSource),
|
||||
} as any),
|
||||
),
|
||||
);
|
||||
|
||||
export const ThreadTurnInterruptRequestedPayload = Schema.Struct({
|
||||
threadId: ThreadId,
|
||||
|
||||
@@ -1,8 +1,49 @@
|
||||
import { Schema } from "effect";
|
||||
import { Schema, Struct } from "effect";
|
||||
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
|
||||
import { EditorId } from "./editor";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
import { DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER } from "./model";
|
||||
import { ModelSelection, ProviderKind } from "./orchestration";
|
||||
|
||||
// ── Server Settings (server-authoritative) ───────────────────────────
|
||||
|
||||
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
|
||||
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
|
||||
|
||||
export const CodexSettings = Schema.Struct({
|
||||
binaryPath: Schema.String.pipe(Schema.withDecodingDefault(() => "")),
|
||||
homePath: Schema.String.pipe(Schema.withDecodingDefault(() => "")),
|
||||
});
|
||||
export type CodexSettings = typeof CodexSettings.Type;
|
||||
|
||||
export const ClaudeSettings = Schema.Struct({
|
||||
binaryPath: Schema.String.pipe(Schema.withDecodingDefault(() => "")),
|
||||
});
|
||||
export type ClaudeSettings = typeof ClaudeSettings.Type;
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
claude: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
|
||||
defaultThreadEnvMode: ThreadEnvMode.pipe(
|
||||
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
|
||||
),
|
||||
customCodexModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
|
||||
customClaudeModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
|
||||
textGenerationModelSelection: ModelSelection.pipe(
|
||||
Schema.withDecodingDefault(() => ({
|
||||
provider: "codex" as const,
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
||||
})),
|
||||
),
|
||||
});
|
||||
export type ServerSettings = typeof ServerSettings.Type;
|
||||
|
||||
export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeUnknownSync(ServerSettings)({});
|
||||
|
||||
export const ServerSettingsPatch = ServerSettings.mapFields(Struct.map(Schema.optionalKey));
|
||||
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
|
||||
|
||||
const KeybindingsMalformedConfigIssue = Schema.Struct({
|
||||
kind: Schema.Literal("keybindings.malformed-config"),
|
||||
@@ -52,6 +93,7 @@ export const ServerConfig = Schema.Struct({
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
availableEditors: Schema.Array(EditorId),
|
||||
settings: ServerSettings,
|
||||
});
|
||||
export type ServerConfig = typeof ServerConfig.Type;
|
||||
|
||||
@@ -67,5 +109,6 @@ export type ServerUpsertKeybindingResult = typeof ServerUpsertKeybindingResult.T
|
||||
export const ServerConfigUpdatedPayload = Schema.Struct({
|
||||
issues: ServerConfigIssues,
|
||||
providers: ServerProviderStatuses,
|
||||
settings: Schema.optional(ServerSettings),
|
||||
});
|
||||
export type ServerConfigUpdatedPayload = typeof ServerConfigUpdatedPayload.Type;
|
||||
@@ -37,7 +37,7 @@ import {
|
||||
import { KeybindingRule } from "./keybindings";
|
||||
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
|
||||
import { OpenInEditorInput } from "./editor";
|
||||
import { ServerConfigUpdatedPayload } from "./server";
|
||||
import { ServerConfigUpdatedPayload, ServerSettingsPatch } from "./server";
|
||||
|
||||
// ── WebSocket RPC Method Names ───────────────────────────────────────
|
||||
|
||||
@@ -76,6 +76,8 @@ export const WS_METHODS = {
|
||||
// Server meta
|
||||
serverGetConfig: "server.getConfig",
|
||||
serverUpsertKeybinding: "server.upsertKeybinding",
|
||||
serverGetSettings: "server.getSettings",
|
||||
serverUpdateSettings: "server.updateSettings",
|
||||
} as const;
|
||||
|
||||
// ── Push Event Channels ──────────────────────────────────────────────
|
||||
@@ -141,6 +143,8 @@ const WebSocketRequestBody = Schema.Union([
|
||||
// Server meta
|
||||
tagRequestBody(WS_METHODS.serverGetConfig, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverUpsertKeybinding, KeybindingRule),
|
||||
tagRequestBody(WS_METHODS.serverGetSettings, Schema.Struct({})),
|
||||
tagRequestBody(WS_METHODS.serverUpdateSettings, Schema.Struct({ patch: ServerSettingsPatch })),
|
||||
]);
|
||||
|
||||
export const WebSocketRequest = Schema.Struct({
|
||||
|
||||
@@ -2,32 +2,25 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_OPTIONS,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getEffectiveClaudeCodeEffort,
|
||||
getDefaultModel,
|
||||
getDefaultReasoningEffort,
|
||||
getModelCapabilities,
|
||||
getModelOptions,
|
||||
getReasoningEffortOptions,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptions,
|
||||
normalizeCodexModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveReasoningEffortForProvider,
|
||||
resolveSelectableModel,
|
||||
resolveModelSlug,
|
||||
resolveModelSlugForProvider,
|
||||
supportsClaudeAdaptiveReasoning,
|
||||
supportsClaudeFastMode,
|
||||
supportsClaudeMaxEffort,
|
||||
supportsClaudeThinkingToggle,
|
||||
supportsClaudeUltrathinkKeyword,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
} from "./model";
|
||||
|
||||
describe("normalizeModelSlug", () => {
|
||||
@@ -158,13 +151,16 @@ describe("resolveSelectableModel", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getReasoningEffortOptions", () => {
|
||||
describe("getModelCapabilities reasoningEffortLevels", () => {
|
||||
const values = (provider: "codex" | "claudeAgent", model: string | null) =>
|
||||
getModelCapabilities(provider, model).reasoningEffortLevels.map((l) => l.value);
|
||||
|
||||
it("returns codex reasoning options for codex", () => {
|
||||
expect(getReasoningEffortOptions("codex")).toEqual(REASONING_EFFORT_OPTIONS_BY_PROVIDER.codex);
|
||||
expect(values("codex", "gpt-5.4")).toEqual([...CODEX_REASONING_EFFORT_OPTIONS]);
|
||||
});
|
||||
|
||||
it("returns claude effort options for Opus 4.6", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-opus-4-6")).toEqual([
|
||||
expect(values("claudeAgent", "claude-opus-4-6")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
@@ -174,7 +170,7 @@ describe("getReasoningEffortOptions", () => {
|
||||
});
|
||||
|
||||
it("returns claude effort options for Sonnet 4.6", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-sonnet-4-6")).toEqual([
|
||||
expect(values("claudeAgent", "claude-sonnet-4-6")).toEqual([
|
||||
"low",
|
||||
"medium",
|
||||
"high",
|
||||
@@ -183,28 +179,37 @@ describe("getReasoningEffortOptions", () => {
|
||||
});
|
||||
|
||||
it("returns no claude effort options for Haiku 4.5", () => {
|
||||
expect(getReasoningEffortOptions("claudeAgent", "claude-haiku-4-5")).toEqual([]);
|
||||
expect(values("claudeAgent", "claude-haiku-4-5")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDefaultReasoningEffort", () => {
|
||||
it("returns provider-scoped defaults", () => {
|
||||
expect(getDefaultReasoningEffort("codex")).toBe(DEFAULT_REASONING_EFFORT_BY_PROVIDER.codex);
|
||||
expect(getDefaultReasoningEffort("claudeAgent")).toBe(
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER.claudeAgent,
|
||||
it("co-locates labels with effort values", () => {
|
||||
const levels = getModelCapabilities("claudeAgent", "claude-opus-4-6").reasoningEffortLevels;
|
||||
const high = levels.find((l) => l.value === "high");
|
||||
expect(high).toEqual({ value: "high", label: "High", isDefault: true });
|
||||
const xhigh = getModelCapabilities("codex", "gpt-5.4").reasoningEffortLevels.find(
|
||||
(l) => l.value === "xhigh",
|
||||
);
|
||||
expect(xhigh).toEqual({ value: "xhigh", label: "Extra High" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveReasoningEffortForProvider", () => {
|
||||
it("accepts provider-scoped effort values", () => {
|
||||
expect(resolveReasoningEffortForProvider("codex", "xhigh")).toBe("xhigh");
|
||||
expect(resolveReasoningEffortForProvider("claudeAgent", "ultrathink")).toBe("ultrathink");
|
||||
describe("getDefaultEffort", () => {
|
||||
it("returns the default effort from capabilities", () => {
|
||||
expect(getDefaultEffort(getModelCapabilities("codex", "gpt-5.4"))).toBe("high");
|
||||
expect(getDefaultEffort(getModelCapabilities("claudeAgent", "claude-opus-4-6"))).toBe("high");
|
||||
expect(getDefaultEffort(getModelCapabilities("claudeAgent", "claude-haiku-4-5"))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects effort values from the wrong provider", () => {
|
||||
expect(resolveReasoningEffortForProvider("codex", "max")).toBeNull();
|
||||
expect(resolveReasoningEffortForProvider("claudeAgent", "xhigh")).toBeNull();
|
||||
describe("hasEffortLevel", () => {
|
||||
it("validates effort against model capabilities", () => {
|
||||
const opusCaps = getModelCapabilities("claudeAgent", "claude-opus-4-6");
|
||||
expect(hasEffortLevel(opusCaps, "max")).toBe(true);
|
||||
expect(hasEffortLevel(opusCaps, "xhigh")).toBe(false);
|
||||
|
||||
const codexCaps = getModelCapabilities("codex", "gpt-5.4");
|
||||
expect(hasEffortLevel(codexCaps, "xhigh")).toBe(true);
|
||||
expect(hasEffortLevel(codexCaps, "max")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -223,27 +228,17 @@ describe("applyClaudePromptEffortPrefix", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getEffectiveClaudeCodeEffort", () => {
|
||||
it("does not persist ultrathink into Claude runtime configuration", () => {
|
||||
expect(getEffectiveClaudeCodeEffort("ultrathink")).toBeNull();
|
||||
expect(getEffectiveClaudeCodeEffort("high")).toBe("high");
|
||||
});
|
||||
|
||||
it("returns null when no claude effort is selected", () => {
|
||||
expect(getEffectiveClaudeCodeEffort(null)).toBeNull();
|
||||
expect(getEffectiveClaudeCodeEffort(undefined)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeCodexModelOptions", () => {
|
||||
it("drops default-only codex options", () => {
|
||||
expect(
|
||||
normalizeCodexModelOptions({ reasoningEffort: "high", fastMode: false }),
|
||||
normalizeCodexModelOptions("gpt-5.4", { reasoningEffort: "high", fastMode: false }),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("preserves non-default codex options", () => {
|
||||
expect(normalizeCodexModelOptions({ reasoningEffort: "xhigh", fastMode: true })).toEqual({
|
||||
expect(
|
||||
normalizeCodexModelOptions("gpt-5.4", { reasoningEffort: "xhigh", fastMode: true }),
|
||||
).toEqual({
|
||||
reasoningEffort: "xhigh",
|
||||
fastMode: true,
|
||||
});
|
||||
@@ -272,49 +267,50 @@ describe("normalizeClaudeModelOptions", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeAdaptiveReasoning", () => {
|
||||
describe("getModelCapabilities Claude capability flags", () => {
|
||||
it("only enables adaptive reasoning for Opus 4.6 and Sonnet 4.6", () => {
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-sonnet-4-6")).toBe(true);
|
||||
expect(supportsClaudeAdaptiveReasoning("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeAdaptiveReasoning(undefined)).toBe(false);
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).reasoningEffortLevels.length > 0;
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(true);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
expect(has(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeMaxEffort", () => {
|
||||
it("only enables max effort for Opus 4.6", () => {
|
||||
expect(supportsClaudeMaxEffort("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeMaxEffort("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeMaxEffort("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeMaxEffort(undefined)).toBe(false);
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).reasoningEffortLevels.some((l) => l.value === "max");
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(false);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
expect(has(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeFastMode", () => {
|
||||
it("only enables Claude fast mode for Opus 4.6", () => {
|
||||
expect(supportsClaudeFastMode("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeFastMode("opus")).toBe(true);
|
||||
expect(supportsClaudeFastMode("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeFastMode("claude-haiku-4-5")).toBe(false);
|
||||
expect(supportsClaudeFastMode(undefined)).toBe(false);
|
||||
const has = (m: string | undefined) => getModelCapabilities("claudeAgent", m).supportsFastMode;
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("opus")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(false);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
expect(has(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeUltrathinkKeyword", () => {
|
||||
it("only enables ultrathink keyword handling for Opus 4.6 and Sonnet 4.6", () => {
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-opus-4-6")).toBe(true);
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-sonnet-4-6")).toBe(true);
|
||||
expect(supportsClaudeUltrathinkKeyword("claude-haiku-4-5")).toBe(false);
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).reasoningEffortLevels.length > 0;
|
||||
expect(has("claude-opus-4-6")).toBe(true);
|
||||
expect(has("claude-sonnet-4-6")).toBe(true);
|
||||
expect(has("claude-haiku-4-5")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("supportsClaudeThinkingToggle", () => {
|
||||
it("only enables the Claude thinking toggle for Haiku 4.5", () => {
|
||||
expect(supportsClaudeThinkingToggle("claude-opus-4-6")).toBe(false);
|
||||
expect(supportsClaudeThinkingToggle("claude-sonnet-4-6")).toBe(false);
|
||||
expect(supportsClaudeThinkingToggle("claude-haiku-4-5")).toBe(true);
|
||||
expect(supportsClaudeThinkingToggle("haiku")).toBe(true);
|
||||
expect(supportsClaudeThinkingToggle(undefined)).toBe(false);
|
||||
const has = (m: string | undefined) =>
|
||||
getModelCapabilities("claudeAgent", m).supportsThinkingToggle;
|
||||
expect(has("claude-opus-4-6")).toBe(false);
|
||||
expect(has("claude-sonnet-4-6")).toBe(false);
|
||||
expect(has("claude-haiku-4-5")).toBe(true);
|
||||
expect(has("haiku")).toBe(true);
|
||||
expect(has(undefined)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+43
-108
@@ -1,18 +1,15 @@
|
||||
import {
|
||||
CLAUDE_CODE_EFFORT_OPTIONS,
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_REASONING_EFFORT_BY_PROVIDER,
|
||||
MODEL_CAPABILITIES_INDEX,
|
||||
MODEL_OPTIONS_BY_PROVIDER,
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
REASONING_EFFORT_OPTIONS_BY_PROVIDER,
|
||||
type ClaudeModelOptions,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexModelOptions,
|
||||
type CodexReasoningEffort,
|
||||
type ModelCapabilities,
|
||||
type ModelSlug,
|
||||
type ProviderReasoningEffort,
|
||||
type ProviderKind,
|
||||
CodexReasoningEffort,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> = {
|
||||
@@ -20,10 +17,6 @@ const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> =
|
||||
codex: new Set(MODEL_OPTIONS_BY_PROVIDER.codex.map((option) => option.slug)),
|
||||
};
|
||||
|
||||
const CLAUDE_OPUS_4_6_MODEL = "claude-opus-4-6";
|
||||
const CLAUDE_SONNET_4_6_MODEL = "claude-sonnet-4-6";
|
||||
const CLAUDE_HAIKU_4_5_MODEL = "claude-haiku-4-5";
|
||||
|
||||
export interface SelectableModelOption {
|
||||
slug: string;
|
||||
name: string;
|
||||
@@ -37,25 +30,34 @@ export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug {
|
||||
return DEFAULT_MODEL_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function supportsClaudeFastMode(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_OPUS_4_6_MODEL;
|
||||
// ── Effort helpers ────────────────────────────────────────────────────
|
||||
|
||||
/** Check whether a capabilities object includes a given effort value. */
|
||||
export function hasEffortLevel(caps: ModelCapabilities, value: string): boolean {
|
||||
return caps.reasoningEffortLevels.some((l) => l.value === value);
|
||||
}
|
||||
|
||||
export function supportsClaudeAdaptiveReasoning(model: string | null | undefined): boolean {
|
||||
const normalized = normalizeModelSlug(model, "claudeAgent");
|
||||
return normalized === CLAUDE_OPUS_4_6_MODEL || normalized === CLAUDE_SONNET_4_6_MODEL;
|
||||
/** Return the default effort value for a capabilities object, or null if none. */
|
||||
export function getDefaultEffort(caps: ModelCapabilities): string | null {
|
||||
return caps.reasoningEffortLevels.find((l) => l.isDefault)?.value ?? null;
|
||||
}
|
||||
|
||||
export function supportsClaudeMaxEffort(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_OPUS_4_6_MODEL;
|
||||
}
|
||||
// ── Data-driven capability resolver ───────────────────────────────────
|
||||
|
||||
export function supportsClaudeUltrathinkKeyword(model: string | null | undefined): boolean {
|
||||
return supportsClaudeAdaptiveReasoning(model);
|
||||
}
|
||||
|
||||
export function supportsClaudeThinkingToggle(model: string | null | undefined): boolean {
|
||||
return normalizeModelSlug(model, "claudeAgent") === CLAUDE_HAIKU_4_5_MODEL;
|
||||
export function getModelCapabilities(
|
||||
provider: ProviderKind,
|
||||
model: string | null | undefined,
|
||||
): ModelCapabilities {
|
||||
const slug = normalizeModelSlug(model, provider);
|
||||
if (slug && MODEL_CAPABILITIES_INDEX[provider]?.[slug]) {
|
||||
return MODEL_CAPABILITIES_INDEX[provider][slug];
|
||||
}
|
||||
return {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
promptInjectedEffortLevels: [],
|
||||
};
|
||||
}
|
||||
|
||||
export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
|
||||
@@ -136,85 +138,20 @@ export function resolveModelSlugForProvider(
|
||||
return resolveModelSlug(model, provider);
|
||||
}
|
||||
|
||||
export function getReasoningEffortOptions(provider: "codex"): ReadonlyArray<CodexReasoningEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider: "claudeAgent",
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ClaudeCodeEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider?: ProviderKind,
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ProviderReasoningEffort>;
|
||||
export function getReasoningEffortOptions(
|
||||
provider: ProviderKind = "codex",
|
||||
model?: string | null | undefined,
|
||||
): ReadonlyArray<ProviderReasoningEffort> {
|
||||
if (provider === "claudeAgent") {
|
||||
if (supportsClaudeMaxEffort(model)) {
|
||||
return ["low", "medium", "high", "max", "ultrathink"];
|
||||
}
|
||||
if (supportsClaudeAdaptiveReasoning(model)) {
|
||||
return ["low", "medium", "high", "ultrathink"];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
return REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function getDefaultReasoningEffort(provider: "codex"): CodexReasoningEffort;
|
||||
export function getDefaultReasoningEffort(provider: "claudeAgent"): ClaudeCodeEffort;
|
||||
export function getDefaultReasoningEffort(provider?: ProviderKind): ProviderReasoningEffort;
|
||||
export function getDefaultReasoningEffort(
|
||||
provider: ProviderKind = "codex",
|
||||
): ProviderReasoningEffort {
|
||||
return DEFAULT_REASONING_EFFORT_BY_PROVIDER[provider];
|
||||
}
|
||||
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: "codex",
|
||||
effort: string | null | undefined,
|
||||
): CodexReasoningEffort | null;
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: "claudeAgent",
|
||||
effort: string | null | undefined,
|
||||
): ClaudeCodeEffort | null;
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: ProviderKind,
|
||||
effort: string | null | undefined,
|
||||
): ProviderReasoningEffort | null;
|
||||
export function resolveReasoningEffortForProvider(
|
||||
provider: ProviderKind,
|
||||
effort: string | null | undefined,
|
||||
): ProviderReasoningEffort | null {
|
||||
if (typeof effort !== "string") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const trimmed = effort.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const options = REASONING_EFFORT_OPTIONS_BY_PROVIDER[provider] as ReadonlyArray<string>;
|
||||
return options.includes(trimmed) ? (trimmed as ProviderReasoningEffort) : null;
|
||||
}
|
||||
|
||||
export function getEffectiveClaudeCodeEffort(
|
||||
effort: ClaudeCodeEffort | null | undefined,
|
||||
): Exclude<ClaudeCodeEffort, "ultrathink"> | null {
|
||||
if (!effort) {
|
||||
return null;
|
||||
}
|
||||
return effort === "ultrathink" ? null : effort;
|
||||
/** Trim a string, returning null for empty/missing values. */
|
||||
export function trimOrNull<T extends string>(value: T | null | undefined): T | null {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim() as T;
|
||||
return trimmed || null;
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("codex");
|
||||
const reasoningEffort =
|
||||
resolveReasoningEffortForProvider("codex", modelOptions?.reasoningEffort) ??
|
||||
defaultReasoningEffort;
|
||||
const caps = getModelCapabilities("codex", model);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps) as CodexReasoningEffort;
|
||||
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort !== defaultReasoningEffort ? { reasoningEffort } : {}),
|
||||
@@ -227,20 +164,20 @@ export function normalizeClaudeModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const reasoningOptions = getReasoningEffortOptions("claudeAgent", model);
|
||||
const defaultReasoningEffort = getDefaultReasoningEffort("claudeAgent");
|
||||
const resolvedEffort = resolveReasoningEffortForProvider("claudeAgent", modelOptions?.effort);
|
||||
const caps = getModelCapabilities("claudeAgent", model);
|
||||
const defaultReasoningEffort = getDefaultEffort(caps);
|
||||
const resolvedEffort = trimOrNull(modelOptions?.effort);
|
||||
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
|
||||
const effort =
|
||||
resolvedEffort &&
|
||||
resolvedEffort !== "ultrathink" &&
|
||||
reasoningOptions.includes(resolvedEffort) &&
|
||||
!isPromptInjected &&
|
||||
hasEffortLevel(caps, resolvedEffort) &&
|
||||
resolvedEffort !== defaultReasoningEffort
|
||||
? resolvedEffort
|
||||
: undefined;
|
||||
const thinking =
|
||||
supportsClaudeThinkingToggle(model) && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode =
|
||||
supportsClaudeFastMode(model) && modelOptions?.fastMode === true ? true : undefined;
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
@@ -265,5 +202,3 @@ export function applyClaudePromptEffortPrefix(
|
||||
}
|
||||
return `Ultrathink:\n${trimmed}`;
|
||||
}
|
||||
|
||||
export { CLAUDE_CODE_EFFORT_OPTIONS, CODEX_REASONING_EFFORT_OPTIONS };
|
||||
@@ -160,6 +160,43 @@ it.layer(NodeServices.layer)("dev-runner", (it) => {
|
||||
assert.equal(env.T3CODE_HOME, resolve("/tmp/my-t3"));
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not export backend bootstrap env for dev:desktop", () =>
|
||||
Effect.gen(function* () {
|
||||
const env = yield* createDevRunnerEnv({
|
||||
mode: "dev:desktop",
|
||||
baseEnv: {
|
||||
T3CODE_PORT: "3773",
|
||||
T3CODE_AUTH_TOKEN: "stale-token",
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_NO_BROWSER: "0",
|
||||
T3CODE_HOST: "0.0.0.0",
|
||||
VITE_WS_URL: "ws://localhost:3773",
|
||||
},
|
||||
serverOffset: 0,
|
||||
webOffset: 0,
|
||||
t3Home: "/tmp/my-t3",
|
||||
authToken: "fresh-token",
|
||||
noBrowser: true,
|
||||
autoBootstrapProjectFromCwd: undefined,
|
||||
logWebSocketEvents: undefined,
|
||||
host: "127.0.0.1",
|
||||
port: 4222,
|
||||
devUrl: undefined,
|
||||
});
|
||||
|
||||
assert.equal(env.T3CODE_HOME, resolve("/tmp/my-t3"));
|
||||
assert.equal(env.PORT, "5733");
|
||||
assert.equal(env.ELECTRON_RENDERER_PORT, "5733");
|
||||
assert.equal(env.VITE_DEV_SERVER_URL, "http://localhost:5733");
|
||||
assert.equal(env.T3CODE_PORT, undefined);
|
||||
assert.equal(env.T3CODE_AUTH_TOKEN, undefined);
|
||||
assert.equal(env.T3CODE_MODE, undefined);
|
||||
assert.equal(env.T3CODE_NO_BROWSER, undefined);
|
||||
assert.equal(env.T3CODE_HOST, undefined);
|
||||
assert.equal(env.VITE_WS_URL, undefined);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
describe("findFirstAvailableOffset", () => {
|
||||
|
||||
+22
-7
@@ -147,30 +147,41 @@ export function createDevRunnerEnv({
|
||||
const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
|
||||
const webPort = BASE_WEB_PORT + webOffset;
|
||||
const resolvedBaseDir = yield* resolveBaseDir(t3Home);
|
||||
const isDesktopMode = mode === "dev:desktop";
|
||||
|
||||
const output: NodeJS.ProcessEnv = {
|
||||
...baseEnv,
|
||||
T3CODE_PORT: String(serverPort),
|
||||
PORT: String(webPort),
|
||||
ELECTRON_RENDERER_PORT: String(webPort),
|
||||
VITE_WS_URL: `ws://localhost:${serverPort}`,
|
||||
VITE_DEV_SERVER_URL: devUrl?.toString() ?? `http://localhost:${webPort}`,
|
||||
T3CODE_HOME: resolvedBaseDir,
|
||||
};
|
||||
|
||||
if (host !== undefined) {
|
||||
if (!isDesktopMode) {
|
||||
output.T3CODE_PORT = String(serverPort);
|
||||
output.VITE_WS_URL = `ws://localhost:${serverPort}`;
|
||||
} else {
|
||||
delete output.T3CODE_PORT;
|
||||
delete output.VITE_WS_URL;
|
||||
delete output.T3CODE_AUTH_TOKEN;
|
||||
delete output.T3CODE_MODE;
|
||||
delete output.T3CODE_NO_BROWSER;
|
||||
delete output.T3CODE_HOST;
|
||||
}
|
||||
|
||||
if (!isDesktopMode && host !== undefined) {
|
||||
output.T3CODE_HOST = host;
|
||||
}
|
||||
|
||||
if (authToken !== undefined) {
|
||||
if (!isDesktopMode && authToken !== undefined) {
|
||||
output.T3CODE_AUTH_TOKEN = authToken;
|
||||
} else {
|
||||
} else if (!isDesktopMode) {
|
||||
delete output.T3CODE_AUTH_TOKEN;
|
||||
}
|
||||
|
||||
if (noBrowser !== undefined) {
|
||||
if (!isDesktopMode && noBrowser !== undefined) {
|
||||
output.T3CODE_NO_BROWSER = noBrowser ? "1" : "0";
|
||||
} else {
|
||||
} else if (!isDesktopMode) {
|
||||
delete output.T3CODE_NO_BROWSER;
|
||||
}
|
||||
|
||||
@@ -196,6 +207,10 @@ export function createDevRunnerEnv({
|
||||
delete output.T3CODE_DESKTOP_WS_URL;
|
||||
}
|
||||
|
||||
if (isDesktopMode) {
|
||||
delete output.T3CODE_DESKTOP_WS_URL;
|
||||
}
|
||||
|
||||
return output;
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user