Compare commits

..
Author SHA1 Message Date
Cursor Agent 2388e7d43f fix: prevent deepMerge from corrupting arrays by treating them as leaf values
P.isObject returns true for arrays, causing deepMerge to spread arrays
into plain objects with numeric keys and recursively merge entries.
This corrupted customModels arrays in ServerSettings whenever
updateSettings was called.

Add Array.isArray guards at both the top-level check and the per-key
recursive branch so arrays are replaced wholesale instead of merged.
2026-03-26 00:07:31 +00:00
76 changed files with 3008 additions and 4430 deletions

No files matched your search

@@ -38,7 +38,6 @@ import { ProjectionPendingApprovalRepository } from "../src/persistence/Services
import { ProviderUnsupportedError } from "../src/provider/Errors.ts";
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
import { ProviderSessionDirectoryLive } from "../src/provider/Layers/ProviderSessionDirectory.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { makeProviderServiceLive } from "../src/provider/Layers/ProviderService.ts";
import { makeCodexAdapterLive } from "../src/provider/Layers/CodexAdapter.ts";
import { CodexAdapter } from "../src/provider/Services/CodexAdapter.ts";
@@ -68,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, {
@@ -324,7 +324,6 @@ export const makeOrchestrationIntegrationHarness = (
);
const layer = orchestrationReactorLayer.pipe(
Layer.provide(persistenceLayer),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(ServerConfig.layerTest(workspaceDir, rootDir)),
Layer.provideMerge(NodeServices.layer),
);
@@ -1,6 +1,5 @@
import type { ProviderRuntimeEvent } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts/settings";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Queue, Stream } from "effect";
@@ -13,7 +12,6 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
import { ProviderSessionRuntimeRepositoryLive } from "../src/persistence/Layers/ProviderSessionRuntime.ts";
@@ -62,7 +60,6 @@ const makeIntegrationFixture = Effect.gen(function* () {
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
AnalyticsService.layerTest,
).pipe(Layer.provide(SqlitePersistenceMemory));
+12 -6
View File
@@ -342,7 +342,6 @@ describe("startSession", () => {
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow("cwd missing");
@@ -391,7 +390,6 @@ describe("startSession", () => {
manager.startSession({
threadId: asThreadId("thread-1"),
provider: "codex",
binaryPath: "codex",
runtimeMode: "full-access",
}),
).rejects.toThrow(
@@ -950,8 +948,12 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
provider: "codex",
cwd: workspaceDir,
runtimeMode: "full-access",
binaryPath: process.env.CODEX_BINARY_PATH!,
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
},
});
const firstTurn = await manager.sendTurn({
@@ -981,8 +983,12 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
cwd: workspaceDir,
runtimeMode: "approval-required",
resumeCursor: firstSession.resumeCursor,
binaryPath: process.env.CODEX_BINARY_PATH!,
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
providerOptions: {
codex: {
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
},
},
});
expect(resumedSession.threadId).toBe(originalThreadId);
+20 -9
View File
@@ -14,6 +14,7 @@ import {
type ProviderApprovalDecision,
type ProviderEvent,
type ProviderSession,
type ProviderSessionStartInput,
type ProviderTurnStartResult,
RuntimeMode,
ProviderInteractionMode,
@@ -130,8 +131,7 @@ export interface CodexAppServerStartSessionInput {
readonly model?: string;
readonly serviceTier?: string;
readonly resumeCursor?: unknown;
readonly binaryPath: string;
readonly homePath?: string;
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
readonly runtimeMode: RuntimeMode;
}
@@ -541,8 +541,9 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
updatedAt: now,
};
const codexBinaryPath = input.binaryPath;
const codexHomePath = input.homePath;
const codexOptions = readCodexProviderOptions(input);
const codexBinaryPath = codexOptions.binaryPath || "codex";
const codexHomePath = codexOptions.homePath;
this.assertSupportedCodexCliVersion({
binaryPath: codexBinaryPath,
cwd: resolvedCwd,
@@ -1590,6 +1591,20 @@ function normalizeProviderThreadId(value: string | undefined): string | undefine
return brandIfNonEmpty(value, (normalized) => normalized);
}
function readCodexProviderOptions(input: CodexAppServerStartSessionInput): {
readonly binaryPath?: string;
readonly homePath?: string;
} {
const options = input.providerOptions?.codex;
if (!options) {
return {};
}
return {
...(options.binaryPath ? { binaryPath: options.binaryPath } : {}),
...(options.homePath ? { homePath: options.homePath } : {}),
};
}
function assertSupportedCodexCliVersion(input: {
readonly binaryPath: string;
readonly cwd: string;
@@ -1643,11 +1658,7 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
}
function readResumeThreadId(input: {
readonly resumeCursor?: unknown;
readonly threadId?: ThreadId;
readonly runtimeMode?: RuntimeMode;
}): string | undefined {
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
return readResumeCursorThreadId(input.resumeCursor);
}
@@ -11,6 +11,7 @@ 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";
@@ -26,7 +27,6 @@ import {
sanitizePrTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -24,20 +24,7 @@ const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
Layer.provideMerge(NodeServices.layer),
);
function makeFakeCodexBinary(
dir: string,
input: {
output: string;
exitCode?: number;
stderr?: string;
requireImage?: boolean;
requireFastServiceTier?: boolean;
requireReasoningEffort?: string;
forbidReasoningEffort?: boolean;
stdinMustContain?: string;
stdinMustNotContain?: string;
},
) {
function makeFakeCodexBinary(dir: string) {
return Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -50,16 +37,12 @@ function makeFakeCodexBinary(
[
"#!/bin/sh",
'output_path=""',
'seen_image="0"',
'seen_fast_service_tier="0"',
'seen_reasoning_effort=""',
"while [ $# -gt 0 ]; do",
' if [ "$1" = "--image" ]; then',
" shift",
' if [ -n "$1" ]; then',
' seen_image="1"',
" fi",
" shift",
" continue",
" fi",
' if [ "$1" = "--config" ]; then',
@@ -72,80 +55,55 @@ function makeFakeCodexBinary(
' seen_reasoning_effort="$1"',
" ;;",
" esac",
" shift",
" continue",
" fi",
' if [ "$1" = "--output-last-message" ]; then',
" shift",
' output_path="$1"',
" shift",
" continue",
" fi",
" shift",
"done",
'stdin_content="$(cat)"',
...(input.requireImage
? [
'if [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
` exit 2`,
"fi",
]
: []),
...(input.requireFastServiceTier
? [
'if [ "$seen_fast_service_tier" != "1" ]; then',
' printf "%s\\n" "missing fast service tier config" >&2',
` exit 5`,
"fi",
]
: []),
...(input.requireReasoningEffort !== undefined
? [
`if [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"${input.requireReasoningEffort}\\"" ]; then`,
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
` exit 6`,
"fi",
]
: []),
...(input.forbidReasoningEffort
? [
'if [ -n "$seen_reasoning_effort" ]; then',
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
` exit 7`,
"fi",
]
: []),
...(input.stdinMustContain !== undefined
? [
`if ! printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustContain)} >/dev/null; then`,
' printf "%s\\n" "stdin missing expected content" >&2',
` exit 3`,
"fi",
]
: []),
...(input.stdinMustNotContain !== undefined
? [
`if printf "%s" "$stdin_content" | grep -F -- ${JSON.stringify(input.stdinMustNotContain)} >/dev/null; then`,
' printf "%s\\n" "stdin contained forbidden content" >&2',
` exit 4`,
"fi",
]
: []),
...(input.stderr !== undefined
? [`printf "%s\\n" ${JSON.stringify(input.stderr)} >&2`]
: []),
'if [ -n "$output_path" ]; then',
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
input.output,
"__T3CODE_FAKE_CODEX_OUTPUT__",
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
' printf "%s\\n" "missing --image input" >&2',
" exit 2",
"fi",
`exit ${input.exitCode ?? 0}`,
'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',
" exit 3",
" }",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" ]; then',
' if printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN" >/dev/null; then',
' printf "%s\\n" "stdin contained forbidden content" >&2',
" exit 4",
" fi",
"fi",
'if [ -n "$T3_FAKE_CODEX_STDERR" ]; then',
' printf "%s\\n" "$T3_FAKE_CODEX_STDERR" >&2',
"fi",
'if [ -n "$output_path" ]; then',
' node -e \'const fs=require("node:fs"); const value=process.argv[2] ?? ""; fs.writeFileSync(process.argv[1], Buffer.from(value, "base64"));\' "$output_path" "${T3_FAKE_CODEX_OUTPUT_B64:-e30=}"',
"fi",
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
"",
].join("\n"),
);
yield* fs.chmod(codexPath, 0o755);
return codexPath;
return binDir;
});
}
@@ -167,29 +125,146 @@ function withFakeCodexEnv<A, E, R>(
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
const serverSettings = yield* ServerSettingsService;
const previousSettings = yield* serverSettings.getSettings;
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: codexPath,
},
},
const binDir = yield* makeFakeCodexBinary(tempDir);
const previousPath = process.env.PATH;
const previousOutput = process.env.T3_FAKE_CODEX_OUTPUT_B64;
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;
yield* Effect.sync(() => {
process.env.PATH = `${binDir}:${previousPath ?? ""}`;
process.env.T3_FAKE_CODEX_OUTPUT_B64 = Buffer.from(input.output, "utf8").toString("base64");
if (input.exitCode !== undefined) {
process.env.T3_FAKE_CODEX_EXIT_CODE = String(input.exitCode);
} else {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
}
if (input.stderr !== undefined) {
process.env.T3_FAKE_CODEX_STDERR = input.stderr;
} else {
delete process.env.T3_FAKE_CODEX_STDERR;
}
if (input.requireImage) {
process.env.T3_FAKE_CODEX_REQUIRE_IMAGE = "1";
} else {
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 {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN;
}
if (input.stdinMustNotContain !== undefined) {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = input.stdinMustNotContain;
} else {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
}
});
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
return {
previousPath,
previousOutput,
previousExitCode,
previousStderr,
previousRequireImage,
previousRequireFastServiceTier,
previousRequireReasoningEffort,
previousForbidReasoningEffort,
previousStdinMustContain,
previousStdinMustNotContain,
};
}),
() => effect,
({ serverSettings, previousBinaryPath }) =>
serverSettings
.updateSettings({
providers: {
codex: {
binaryPath: previousBinaryPath,
},
},
})
.pipe(Effect.asVoid),
(previous) =>
Effect.sync(() => {
process.env.PATH = previous.previousPath;
if (previous.previousOutput === undefined) {
delete process.env.T3_FAKE_CODEX_OUTPUT_B64;
} else {
process.env.T3_FAKE_CODEX_OUTPUT_B64 = previous.previousOutput;
}
if (previous.previousExitCode === undefined) {
delete process.env.T3_FAKE_CODEX_EXIT_CODE;
} else {
process.env.T3_FAKE_CODEX_EXIT_CODE = previous.previousExitCode;
}
if (previous.previousStderr === undefined) {
delete process.env.T3_FAKE_CODEX_STDERR;
} else {
process.env.T3_FAKE_CODEX_STDERR = previous.previousStderr;
}
if (previous.previousRequireImage === undefined) {
delete process.env.T3_FAKE_CODEX_REQUIRE_IMAGE;
} else {
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 {
process.env.T3_FAKE_CODEX_STDIN_MUST_CONTAIN = previous.previousStdinMustContain;
}
if (previous.previousStdinMustNotContain === undefined) {
delete process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN;
} else {
process.env.T3_FAKE_CODEX_STDIN_MUST_NOT_CONTAIN = previous.previousStdinMustNotContain;
}
}),
);
}
@@ -4,6 +4,7 @@ import { Effect, FileSystem, Layer, Option, Path, Schema, Scope, Stream } from "
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { CodexModelSelection } from "@t3tools/contracts";
import { normalizeCodexModelOptions } from "@t3tools/shared/model";
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
@@ -25,7 +26,6 @@ import {
sanitizePrTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
@@ -172,10 +172,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
"-",
],
{
env: {
...process.env,
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
env: codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {},
cwd,
shell: process.platform === "win32",
stdin: {
+10 -2
View File
@@ -6,6 +6,7 @@ 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";
@@ -16,8 +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 } from "./serverSettings";
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings";
const start = vi.fn(() => undefined);
const stop = vi.fn(() => undefined);
@@ -53,7 +55,13 @@ const testLayer = Layer.mergeAll(
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
ServerSettingsService.layerTest(),
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,
+5 -10
View File
@@ -22,7 +22,7 @@ import { Open } from "./open";
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
import { Server } from "./wsServer";
import { ServerLoggerLive } from "./serverLogger";
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
@@ -294,7 +294,7 @@ const LayerLive = (input: CliInput) =>
Layer.empty.pipe(
Layer.provideMerge(makeServerRuntimeServicesLayer()),
Layer.provideMerge(makeServerProviderLayer()),
Layer.provideMerge(ProviderRegistryLive),
Layer.provideMerge(ProviderHealthLive),
Layer.provideMerge(SqlitePersistence.layerConfig),
Layer.provideMerge(ServerLoggerLive),
Layer.provideMerge(AnalyticsServiceLayerLive),
@@ -333,10 +333,12 @@ export const recordStartupHeartbeat = Effect.gen(function* () {
});
});
const makeServerRuntimeProgram = (input: CliInput) =>
const makeServerProgram = (input: CliInput) =>
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
const { start, stopSignal } = yield* Server;
const openDeps = yield* Open;
yield* cliConfig.fixPath;
const config = yield* ServerConfig;
@@ -378,13 +380,6 @@ const makeServerRuntimeProgram = (input: CliInput) =>
return yield* stopSignal;
}).pipe(Effect.provide(LayerLive(input)));
const makeServerProgram = (input: CliInput) =>
Effect.gen(function* () {
const cliConfig = yield* CliConfig;
yield* cliConfig.fixPath;
return yield* makeServerRuntimeProgram(input);
});
/**
* These flags mirrors the environment variables and the config shape.
*/
@@ -24,7 +24,7 @@ import {
ProviderCommandReactor,
type ProviderCommandReactorShape,
} from "../Services/ProviderCommandReactor.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerSettingsService, deriveProviderStartOptions } from "../../serverSettings.ts";
type ProviderIntentEvent = Extract<
OrchestrationEvent,
@@ -251,13 +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,
...(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) =>
@@ -424,52 +429,48 @@ const make = Effect.gen(function* () {
const oldBranch = input.branch;
const cwd = input.worktreePath;
const attachments = input.attachments ?? [];
yield* Effect.flatMap(
Effect.map(
serverSettingsService.getSettings,
(settings) => settings.textGenerationModelSelection,
),
(modelSelection) =>
textGeneration.generateBranchName({
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection,
}),
).pipe(
Effect.catch((error) =>
Effect.logWarning(
"provider command reactor failed to generate worktree branch name; skipping rename",
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
yield* textGeneration
.generateBranchName({
cwd,
message: input.messageText,
...(attachments.length > 0 ? { attachments } : {}),
modelSelection: yield* Effect.map(
serverSettingsService.getSettings,
(settings) => settings.textGenerationModelSelection,
),
),
Effect.flatMap((generated) => {
if (!generated) return Effect.void;
})
.pipe(
Effect.catch((error) =>
Effect.logWarning(
"provider command reactor failed to generate worktree branch name; skipping rename",
{ threadId: input.threadId, cwd, oldBranch, reason: error.message },
),
),
Effect.flatMap((generated) => {
if (!generated) return Effect.void;
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return Effect.void;
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
if (targetBranch === oldBranch) return Effect.void;
return Effect.flatMap(
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
(renamed) =>
orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
}),
);
}),
Effect.catchCause((cause) =>
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
threadId: input.threadId,
cwd,
oldBranch,
cause: Cause.pretty(cause),
return Effect.flatMap(
git.renameBranch({ cwd, oldBranch, newBranch: targetBranch }),
(renamed) =>
orchestrationEngine.dispatch({
type: "thread.meta.update",
commandId: serverCommandId("worktree-branch-rename"),
threadId: input.threadId,
branch: renamed.branch,
worktreePath: cwd,
}),
);
}),
),
);
Effect.catchCause((cause) =>
Effect.logWarning(
"provider command reactor failed to generate or rename worktree branch",
{ threadId: input.threadId, cwd, oldBranch, cause: Cause.pretty(cause) },
),
),
);
});
const processTurnStartRequested = Effect.fnUntraced(function* (
@@ -12,6 +12,7 @@ import {
ApprovalRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_SERVER_SETTINGS,
EventId,
MessageId,
ProjectId,
@@ -39,11 +40,18 @@ import {
} from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
return ServerSettingsService.layerTest(overrides);
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);
@@ -21,7 +21,6 @@ import { Effect, Fiber, Layer, Random, Stream } from "effect";
import { attachmentRelativePath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { ClaudeAdapter } from "../Services/ClaudeAdapter.ts";
import { makeClaudeAdapterLive, type ClaudeAdapterLiveOptions } from "./ClaudeAdapter.ts";
@@ -169,7 +168,6 @@ function makeHarness(config?: {
config?.baseDir ?? "/tmp",
),
),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
),
query,
@@ -303,7 +301,7 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("uses bypass permissions for full-access claude sessions", () => {
it.effect("keeps explicit claude permission mode over runtime-derived defaults", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
@@ -311,11 +309,16 @@ describe("ClaudeAdapterLive", () => {
threadId: THREAD_ID,
provider: "claudeAgent",
runtimeMode: "full-access",
providerOptions: {
claudeAgent: {
permissionMode: "plan",
},
},
});
const createInput = harness.getLastCreateQueryInput();
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
assert.equal(createInput?.options.permissionMode, "plan");
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -1192,7 +1195,6 @@ describe("ClaudeAdapterLive", () => {
},
}).pipe(
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(NodeServices.layer),
);
@@ -40,7 +40,12 @@ import {
type UserInputQuestion,
ClaudeCodeEffort,
} from "@t3tools/contracts";
import { hasEffortLevel, applyClaudePromptEffortPrefix, trimOrNull } from "@t3tools/shared/model";
import {
hasEffortLevel,
applyClaudePromptEffortPrefix,
getModelCapabilities,
trimOrNull,
} from "@t3tools/shared/model";
import {
Cause,
DateTime,
@@ -58,8 +63,6 @@ import {
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "./ClaudeProvider.ts";
import {
ProviderAdapterProcessError,
ProviderAdapterRequestError,
@@ -350,6 +353,19 @@ function asRuntimeRequestId(value: ApprovalRequestId): RuntimeRequestId {
return RuntimeRequestId.makeUnsafe(value);
}
function toPermissionMode(value: unknown): PermissionMode | undefined {
switch (value) {
case "default":
case "acceptEdits":
case "bypassPermissions":
case "plan":
case "dontAsk":
return value;
default:
return undefined;
}
}
function readClaudeResumeState(resumeCursor: unknown): ClaudeResumeState | undefined {
if (!resumeCursor || typeof resumeCursor !== "object") {
return undefined;
@@ -509,7 +525,7 @@ function buildPromptText(input: ProviderSendTurnInput): string {
const requestedEffort = trimOrNull(rawEffort);
const claudeModel =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
const caps = getClaudeModelCapabilities(claudeModel);
const caps = getModelCapabilities("claudeAgent", claudeModel);
const promptEffort =
requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0
? "ultrathink"
@@ -927,7 +943,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const sessions = new Map<ThreadId, ClaudeSessionContext>();
const runtimeEventQueue = yield* Queue.unbounded<ProviderRuntimeEvent>();
const serverSettingsService = yield* ServerSettingsService;
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
const nextEventId = Effect.map(Random.nextUUIDv4, (id) => EventId.makeUnsafe(id));
@@ -2712,23 +2727,11 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
}),
);
const claudeSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.claudeAgent),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const claudeBinaryPath = claudeSettings.binaryPath;
const providerOptions = input.providerOptions?.claudeAgent;
const modelSelection =
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null);
const caps = getClaudeModelCapabilities(modelSelection?.model);
const caps = getModelCapabilities("claudeAgent", modelSelection?.model);
const effort =
requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null;
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
@@ -2738,7 +2741,8 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
: undefined;
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
const permissionMode =
input.runtimeMode === "full-access" ? "bypassPermissions" : undefined;
toPermissionMode(providerOptions?.permissionMode) ??
(input.runtimeMode === "full-access" ? "bypassPermissions" : undefined);
const settings = {
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
...(fastMode ? { fastMode: true } : {}),
@@ -2747,13 +2751,16 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
const queryOptions: ClaudeQueryOptions = {
...(input.cwd ? { cwd: input.cwd } : {}),
...(modelSelection?.model ? { model: modelSelection.model } : {}),
pathToClaudeCodeExecutable: claudeBinaryPath,
pathToClaudeCodeExecutable: providerOptions?.binaryPath || "claude",
settingSources: [...CLAUDE_SETTING_SOURCES],
...(effectiveEffort ? { effort: effectiveEffort } : {}),
...(permissionMode ? { permissionMode } : {}),
...(permissionMode === "bypassPermissions"
? { allowDangerouslySkipPermissions: true }
: {}),
...(providerOptions?.maxThinkingTokens !== undefined
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
: {}),
...(Object.keys(settings).length > 0 ? { settings } : {}),
...(existingResumeSessionId ? { resume: existingResumeSessionId } : {}),
...(newSessionId ? { sessionId: newSessionId } : {}),
@@ -2844,6 +2851,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
...(input.cwd ? { cwd: input.cwd } : {}),
...(effectiveEffort ? { effort: effectiveEffort } : {}),
...(permissionMode ? { permissionMode } : {}),
...(providerOptions?.maxThinkingTokens !== undefined
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
: {}),
...(fastMode ? { fastMode: true } : {}),
},
},
@@ -1,397 +0,0 @@
import type {
ClaudeSettings,
ClaudeModelOptions,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { getDefaultEffort, hasEffortLevel, trimOrNull } from "@t3tools/shared/model";
import {
buildServerProvider,
collectStreamAsString,
DEFAULT_TIMEOUT_MS,
detailFromResult,
extractAuthBoolean,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
type CommandResult,
} from "../providerSnapshot";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
const PROVIDER = "claudeAgent" as const;
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
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"],
} satisfies ModelCapabilities,
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
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"],
} satisfies ModelCapabilities,
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
promptInjectedEffortLevels: [],
} satisfies ModelCapabilities,
},
];
export function getClaudeModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
}
);
}
export function normalizeClaudeModelOptions(
model: string | null | undefined,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const caps = getClaudeModelCapabilities(model);
const defaultReasoningEffort = getDefaultEffort(caps);
const resolvedEffort = trimOrNull(modelOptions?.effort);
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
const effort =
resolvedEffort &&
!isPromptInjected &&
hasEffortLevel(caps, resolvedEffort) &&
resolvedEffort !== defaultReasoningEffort
? resolvedEffort
: undefined;
const thinking =
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 } : {}),
...(fastMode ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const command = ChildProcess.make(claudeSettings.binaryPath, [...args], {
shell: process.platform === "win32",
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
);
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Claude is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
}
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
},
);
export const ClaudeProviderLive = Layer.effect(
ClaudeProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkClaudeProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<ClaudeSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.claudeAgent),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.claudeAgent),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
checkProvider,
});
}),
);
@@ -22,7 +22,6 @@ import {
type CodexAppServerSendTurnInput,
} from "../../codexAppServerManager.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { ProviderAdapterValidationError } from "../Errors.ts";
import { CodexAdapter } from "../Services/CodexAdapter.ts";
import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts";
@@ -152,7 +151,6 @@ const validationManager = new FakeCodexManager();
const validationLayer = it.layer(
makeCodexAdapterLive({ manager: validationManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -203,7 +201,6 @@ validationLayer("CodexAdapterLive validation", (it) => {
assert.deepStrictEqual(validationManager.startSessionImpl.mock.calls[0]?.[0], {
provider: "codex",
threadId: asThreadId("thread-1"),
binaryPath: "codex",
model: "gpt-5.3-codex",
serviceTier: "fast",
runtimeMode: "full-access",
@@ -219,7 +216,6 @@ sessionErrorManager.sendTurnImpl.mockImplementation(async () => {
const sessionErrorLayer = it.layer(
makeCodexAdapterLive({ manager: sessionErrorManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
@@ -288,7 +284,6 @@ const lifecycleManager = new FakeCodexManager();
const lifecycleLayer = it.layer(
makeCodexAdapterLive({ manager: lifecycleManager }).pipe(
Layer.provideMerge(ServerConfig.layerTest(process.cwd(), process.cwd())),
Layer.provideMerge(ServerSettingsService.layerTest()),
Layer.provideMerge(providerSessionDirectoryTestLayer),
Layer.provideMerge(NodeServices.layer),
),
+12 -27
View File
@@ -38,7 +38,6 @@ import {
} from "../../codexAppServerManager.ts";
import { resolveAttachmentPath } from "../../attachmentStore.ts";
import { ServerConfig } from "../../config.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
const PROVIDER = "codex" as const;
@@ -1343,39 +1342,25 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
}
}),
);
const serverSettingsService = yield* ServerSettingsService;
const startSession: CodexAdapterShape["startSession"] = Effect.fn(function* (input) {
const startSession: CodexAdapterShape["startSession"] = (input) => {
if (input.provider !== undefined && input.provider !== PROVIDER) {
return yield* new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
});
return Effect.fail(
new ProviderAdapterValidationError({
provider: PROVIDER,
operation: "startSession",
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
}),
);
}
const codexSettings = yield* serverSettingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.mapError(
(error) =>
new ProviderAdapterProcessError({
provider: PROVIDER,
threadId: input.threadId,
detail: error.message,
cause: error,
}),
),
);
const binaryPath = codexSettings.binaryPath;
const homePath = codexSettings.homePath;
const managerInput: CodexAppServerStartSessionInput = {
threadId: input.threadId,
provider: "codex",
...(input.cwd !== undefined ? { cwd: input.cwd } : {}),
...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
...(input.providerOptions !== undefined ? { providerOptions: input.providerOptions } : {}),
runtimeMode: input.runtimeMode,
binaryPath,
...(homePath ? { homePath } : {}),
...(input.modelSelection?.provider === "codex"
? { model: input.modelSelection.model }
: {}),
@@ -1384,7 +1369,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
: {}),
};
return yield* Effect.tryPromise({
return Effect.tryPromise({
try: () => manager.startSession(managerInput),
catch: (cause) =>
new ProviderAdapterProcessError({
@@ -1393,8 +1378,8 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
detail: toMessage(cause, "Failed to start Codex adapter session."),
cause,
}),
});
});
}).pipe(Effect.map((session) => session));
};
const sendTurn: CodexAdapterShape["sendTurn"] = (input) =>
Effect.gen(function* () {
@@ -1,531 +0,0 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexModelOptions,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { getDefaultEffort, trimOrNull } from "@t3tools/shared/model";
import {
buildServerProvider,
collectStreamAsString,
DEFAULT_TIMEOUT_MS,
detailFromResult,
extractAuthBoolean,
isCommandMissingCause,
parseGenericCliVersion,
providerModelsFromSettings,
type CommandResult,
} from "../providerSnapshot";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import {
formatCodexCliUpgradeMessage,
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion";
import { CodexProvider } from "../Services/CodexProvider";
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
const PROVIDER = "codex" as const;
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
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",
isCustom: false,
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",
isCustom: false,
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",
isCustom: false,
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",
isCustom: false,
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",
isCustom: false,
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: [],
},
},
];
export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
}
);
}
export function normalizeCodexModelOptions(
model: string | null | undefined,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const caps = getCodexModelCapabilities(model);
const defaultReasoningEffort = getDefaultEffort(caps);
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort && reasoningEffort !== defaultReasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `codex login`") ||
lowerOutput.includes("run codex login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
};
}
export const readCodexConfigModelProvider = Effect.fn("readCodexConfigModelProvider")(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const settingsService = yield* ServerSettingsService;
const codexHome = yield* settingsService.getSettings.pipe(
Effect.map(
(settings) =>
settings.providers.codex.homePath ||
process.env.CODEX_HOME ||
path.join(OS.homedir(), ".codex"),
),
);
const configPath = path.join(codexHome, "config.toml");
const content = yield* fileSystem
.readFileString(configPath)
.pipe(Effect.orElseSucceed(() => undefined));
if (content === undefined) {
return undefined;
}
let inTopLevel = true;
for (const line of content.split("\n")) {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith("#")) continue;
if (trimmed.startsWith("[")) {
inTopLevel = false;
continue;
}
if (!inTopLevel) continue;
const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
if (match) return match[1];
}
return undefined;
});
export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
Effect.map((provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider)),
Effect.orElseSucceed(() => false),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const settingsService = yield* ServerSettingsService;
const codexSettings = yield* settingsService.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
);
const command = ChildProcess.make(codexSettings.binaryPath, [...args], {
shell: process.platform === "win32",
env: {
...process.env,
...(codexSettings.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
},
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
authStatus: "unknown",
message: "Codex is disabled in T3 Code settings.",
},
});
}
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
authStatus: "unknown",
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
authStatus: "unknown",
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
},
);
export const CodexProviderLive = Layer.effect(
CodexProvider,
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
return yield* makeManagedServerProvider<CodexSettings>({
getSettings: serverSettings.getSettings.pipe(
Effect.map((settings) => settings.providers.codex),
Effect.orDie,
),
streamSettings: serverSettings.streamChanges.pipe(
Stream.map((settings) => settings.providers.codex),
),
haveSettingsChanged: (previous, next) => !Equal.equals(previous, next),
checkProvider,
});
}),
);
@@ -0,0 +1,640 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import { Effect, FileSystem, Layer, Path, Sink, Stream } from "effect";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import {
checkClaudeProviderStatus,
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
parseClaudeAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./ProviderHealth";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout)),
stderr: Stream.make(encoder.encode(result.stderr)),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function mockSpawnerLayer(
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const cmd = command as unknown as { args: ReadonlyArray<string> };
return Effect.succeed(mockHandle(handler(cmd.args)));
}),
);
}
function failingSpawnerLayer(description: string) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description,
}),
),
),
);
}
/**
* Create a temporary CODEX_HOME scoped to the current Effect test.
* Cleanup is registered in the test scope rather than via Vitest hooks.
*/
function withTempCodexHome(configContent?: string) {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
yield* Effect.acquireRelease(
Effect.sync(() => {
const originalCodexHome = process.env.CODEX_HOME;
process.env.CODEX_HOME = tmpDir;
return originalCodexHome;
}),
(originalCodexHome) =>
Effect.sync(() => {
if (originalCodexHome !== undefined) {
process.env.CODEX_HOME = originalCodexHome;
} else {
delete process.env.CODEX_HOME;
}
}),
);
if (configContent !== undefined) {
yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
}
return { tmpDir } as const;
});
}
it.layer(NodeServices.layer)("ProviderHealth", (it) => {
// ── checkCodexProviderStatus tests ────────────────────────────────
//
// These tests control CODEX_HOME to ensure the custom-provider detection
// in hasCustomModelProvider() does not interfere with the auth-probe
// path being tested.
describe("checkCodexProviderStatus", () => {
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
// default code path (OpenAI provider, auth probe runs) is exercised.
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(status.message, "Codex CLI (`codex`) is not installed or not on PATH.");
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── Custom model provider: checkCodexProviderStatus integration ───
describe("checkCodexProviderStatus with custom model provider", () => {
it.effect("skips auth probe and returns ready when a custom model provider is configured", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
);
}).pipe(
Effect.provide(
// The spawner only handles --version; if the test attempts
// "login status" the throw proves the auth probe was NOT skipped.
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
}),
),
),
);
it.effect("still reports error when codex CLI is missing even with custom provider", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus;
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
});
describe("checkCodexProviderStatus with openai model provider", () => {
it.effect("still runs auth probe when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
const status = yield* checkCodexProviderStatus;
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseAuthStatusFromOutput pure tests ──────────────────────────
describe("parseAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
// ── readCodexConfigModelProvider tests ─────────────────────────────
describe("readCodexConfigModelProvider", () => {
it.effect("returns undefined when config file does not exist", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("returns undefined when config has no model_provider key", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("returns the provider when model_provider is set at top level", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, "portkey");
}),
);
it.effect("returns openai when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* readCodexConfigModelProvider, "openai");
}),
);
it.effect("ignores model_provider inside section headers", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model = "gpt-5-codex"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'model_provider = "should-be-ignored"',
"",
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider, undefined);
}),
);
it.effect("handles comments and whitespace", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
"# This is a comment",
"",
' model_provider = "azure" ',
"",
"[profiles.deep-review]",
'model = "gpt-5-pro"',
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider, "azure");
}),
);
it.effect("handles single-quoted values in TOML", () =>
Effect.gen(function* () {
yield* withTempCodexHome("model_provider = 'mistral'\n");
assert.strictEqual(yield* readCodexConfigModelProvider, "mistral");
}),
);
});
// ── hasCustomModelProvider tests ───────────────────────────────────
describe("hasCustomModelProvider", () => {
it.effect("returns false when no config file exists", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is not set", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns true when model_provider is portkey", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "portkey"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is azure", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "azure"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is ollama", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "ollama"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is a custom proxy", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
});
// ── checkClaudeProviderStatus tests ──────────────────────────
describe("checkClaudeProviderStatus", () => {
it.effect("returns ready when claude is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when claude is missing", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
);
it.effect("returns error when version check fails with non-zero exit code", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, false);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version")
return { stdout: "", stderr: "Something went wrong", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth status reports not logged in", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 1,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status") return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when auth status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus;
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.available, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
describe("parseClaudeAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"ok":true}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
});
@@ -0,0 +1,603 @@
/**
* ProviderHealthLive - Startup-time provider health checks.
*
* Performs one-time provider readiness probes when the server starts and
* keeps the resulting snapshot in memory for `server.getConfig`.
*
* Uses effect's ChildProcessSpawner to run CLI probes natively.
*
* @module ProviderHealthLive
*/
import * as OS from "node:os";
import type {
ServerProviderAuthStatus,
ServerProviderStatus,
ServerProviderStatusState,
} from "@t3tools/contracts";
import { Array, Effect, Fiber, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import {
formatCodexCliUpgradeMessage,
isCodexCliVersionSupported,
parseCodexCliVersion,
} from "../codexCliVersion";
import { ProviderHealth, type ProviderHealthShape } from "../Services/ProviderHealth";
const DEFAULT_TIMEOUT_MS = 4_000;
const CODEX_PROVIDER = "codex" as const;
const CLAUDE_AGENT_PROVIDER = "claudeAgent" as const;
// ── Pure helpers ────────────────────────────────────────────────────
export interface CommandResult {
readonly stdout: string;
readonly stderr: string;
readonly code: number;
}
function nonEmptyTrimmed(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
function isCommandMissingCause(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const lower = error.message.toLowerCase();
return lower.includes("enoent") || lower.includes("notfound");
}
function detailFromResult(
result: CommandResult & { readonly timedOut?: boolean },
): string | undefined {
if (result.timedOut) return "Timed out while running command.";
const stderr = nonEmptyTrimmed(result.stderr);
if (stderr) return stderr;
const stdout = nonEmptyTrimmed(result.stdout);
if (stdout) return stdout;
if (result.code !== 0) {
return `Command exited with code ${result.code}.`;
}
return undefined;
}
function extractAuthBoolean(value: unknown): boolean | undefined {
if (Array.isArray(value)) {
for (const entry of value) {
const nested = extractAuthBoolean(entry);
if (nested !== undefined) return nested;
}
return undefined;
}
if (!value || typeof value !== "object") return undefined;
const record = value as Record<string, unknown>;
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
if (typeof record[key] === "boolean") return record[key];
}
for (const key of ["auth", "status", "session", "account"] as const) {
const nested = extractAuthBoolean(record[key]);
if (nested !== undefined) return nested;
}
return undefined;
}
export function parseAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message: "Codex CLI authentication status command is unavailable in this Codex version.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `codex login`") ||
lowerOutput.includes("run codex login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
};
}
// ── Codex CLI config detection ──────────────────────────────────────
/**
* Providers that use OpenAI-native authentication via `codex login`.
* When the configured `model_provider` is one of these, the `codex login
* status` probe still runs. For any other provider value the auth probe
* is skipped because authentication is handled externally (e.g. via
* environment variables like `PORTKEY_API_KEY` or `AZURE_API_KEY`).
*/
const OPENAI_AUTH_PROVIDERS = new Set(["openai"]);
/**
* Read the `model_provider` value from the Codex CLI config file.
*
* Looks for the file at `$CODEX_HOME/config.toml` (falls back to
* `~/.codex/config.toml`). Uses a simple line-by-line scan rather than
* a full TOML parser to avoid adding a dependency for a single key.
*
* Returns `undefined` when the file does not exist or does not set
* `model_provider`.
*/
export const readCodexConfigModelProvider = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const codexHome = process.env.CODEX_HOME || path.join(OS.homedir(), ".codex");
const configPath = path.join(codexHome, "config.toml");
const content = yield* fileSystem
.readFileString(configPath)
.pipe(Effect.orElseSucceed(() => undefined));
if (content === undefined) {
return undefined;
}
// We need to find `model_provider = "..."` at the top level of the
// TOML file (i.e. before any `[section]` header). Lines inside
// `[profiles.*]`, `[model_providers.*]`, etc. are ignored.
let inTopLevel = true;
for (const line of content.split("\n")) {
const trimmed = line.trim();
// Skip comments and empty lines.
if (!trimmed || trimmed.startsWith("#")) continue;
// Detect section headers — once we leave the top level, stop.
if (trimmed.startsWith("[")) {
inTopLevel = false;
continue;
}
if (!inTopLevel) continue;
const match = trimmed.match(/^model_provider\s*=\s*["']([^"']+)["']/);
if (match) return match[1];
}
return undefined;
});
/**
* Returns `true` when the Codex CLI is configured with a custom
* (non-OpenAI) model provider, meaning `codex login` auth is not
* required because authentication is handled through provider-specific
* environment variables.
*/
export const hasCustomModelProvider = Effect.map(
readCodexConfigModelProvider,
(provider) => provider !== undefined && !OPENAI_AUTH_PROVIDERS.has(provider),
);
// ── Effect-native command execution ─────────────────────────────────
const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>): Effect.Effect<string, E> =>
Stream.runFold(
stream,
() => "",
(acc, chunk) => acc + new TextDecoder().decode(chunk),
);
const runCodexCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("codex", [...args], {
shell: process.platform === "win32",
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
const runClaudeCommand = (args: ReadonlyArray<string>) =>
Effect.gen(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const command = ChildProcess.make("claude", [...args], {
shell: process.platform === "win32",
});
const child = yield* spawner.spawn(command);
const [stdout, stderr, exitCode] = yield* Effect.all(
[
collectStreamAsString(child.stdout),
collectStreamAsString(child.stderr),
child.exitCode.pipe(Effect.map(Number)),
],
{ concurrency: "unbounded" },
);
return { stdout, stderr, code: exitCode } satisfies CommandResult;
}).pipe(Effect.scoped);
// ── Health check ────────────────────────────────────────────────────
export const checkCodexProviderStatus: Effect.Effect<
ServerProviderStatus,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path
> = Effect.gen(function* () {
const checkedAt = new Date().toISOString();
// Probe 1: `codex --version` — is the CLI reachable?
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
};
}
if (Option.isNone(versionProbe.success)) {
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: "Codex CLI is installed but failed to run. Timed out while running command.",
};
}
const version = versionProbe.success.value;
if (version.code !== 0) {
const detail = detailFromResult(version);
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
};
}
const parsedVersion = parseCodexCliVersion(`${version.stdout}\n${version.stderr}`);
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return {
provider: CODEX_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: formatCodexCliUpgradeMessage(parsedVersion),
};
}
// Probe 2: `codex login status` — is the user authenticated?
//
// Custom model providers (e.g. Portkey, Azure OpenAI proxy) handle
// authentication through their own environment variables, so `codex
// login status` will report "not logged in" even when the CLI works
// fine. Skip the auth probe entirely for non-OpenAI providers.
if (yield* hasCustomModelProvider) {
return {
provider: CODEX_PROVIDER,
status: "ready" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Using a custom Codex model provider; OpenAI login check skipped.",
} satisfies ServerProviderStatus;
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return {
provider: CODEX_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
};
}
if (Option.isNone(authProbe.success)) {
return {
provider: CODEX_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Could not verify Codex authentication status. Timed out while running command.",
};
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
return {
provider: CODEX_PROVIDER,
status: parsed.status,
available: true,
authStatus: parsed.authStatus,
checkedAt,
...(parsed.message ? { message: parsed.message } : {}),
} satisfies ServerProviderStatus;
});
// ── Claude Agent health check ───────────────────────────────────────
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
readonly status: ServerProviderStatusState;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
if (
lowerOutput.includes("unknown command") ||
lowerOutput.includes("unrecognized command") ||
lowerOutput.includes("unexpected argument")
) {
return {
status: "warning",
authStatus: "unknown",
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
}
if (
lowerOutput.includes("not logged in") ||
lowerOutput.includes("login required") ||
lowerOutput.includes("authentication required") ||
lowerOutput.includes("run `claude login`") ||
lowerOutput.includes("run claude login")
) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
// `claude auth status` returns JSON with a `loggedIn` boolean.
const parsedAuth = (() => {
const trimmed = result.stdout.trim();
if (!trimmed || (!trimmed.startsWith("{") && !trimmed.startsWith("["))) {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
try {
return {
attemptedJsonParse: true as const,
auth: extractAuthBoolean(JSON.parse(trimmed)),
};
} catch {
return { attemptedJsonParse: false as const, auth: undefined as boolean | undefined };
}
})();
if (parsedAuth.auth === true) {
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
authStatus: "unknown",
message: detail
? `Could not verify Claude authentication status. ${detail}`
: "Could not verify Claude authentication status.",
};
}
export const checkClaudeProviderStatus: Effect.Effect<
ServerProviderStatus,
never,
ChildProcessSpawner.ChildProcessSpawner
> = Effect.gen(function* () {
const checkedAt = new Date().toISOString();
// Probe 1: `claude --version` — is the CLI reachable?
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
};
}
if (Option.isNone(versionProbe.success)) {
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: "Claude Agent CLI is installed but failed to run. Timed out while running command.",
};
}
const version = versionProbe.success.value;
if (version.code !== 0) {
const detail = detailFromResult(version);
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "error" as const,
available: false,
authStatus: "unknown" as const,
checkedAt,
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
};
}
// Probe 2: `claude auth status` — is the user authenticated?
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
};
}
if (Option.isNone(authProbe.success)) {
return {
provider: CLAUDE_AGENT_PROVIDER,
status: "warning" as const,
available: true,
authStatus: "unknown" as const,
checkedAt,
message: "Could not verify Claude authentication status. Timed out while running command.",
};
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return {
provider: CLAUDE_AGENT_PROVIDER,
status: parsed.status,
available: true,
authStatus: parsed.authStatus,
checkedAt,
...(parsed.message ? { message: parsed.message } : {}),
} satisfies ServerProviderStatus;
});
// ── Layer ───────────────────────────────────────────────────────────
export const ProviderHealthLive = Layer.effect(
ProviderHealth,
Effect.gen(function* () {
const statusesFiber = yield* Effect.all([checkCodexProviderStatus, checkClaudeProviderStatus], {
concurrency: "unbounded",
}).pipe(Effect.forkScoped);
return {
getStatuses: Fiber.join(statusesFiber),
} satisfies ProviderHealthShape;
}),
);
@@ -1,879 +0,0 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, it, assert } from "@effect/vitest";
import {
Effect,
Exit,
FileSystem,
Layer,
Path,
PubSub,
Ref,
Schema,
Scope,
Sink,
Stream,
} from "effect";
import {
DEFAULT_SERVER_SETTINGS,
ServerSettings,
type ServerProvider,
type ServerSettings as ContractServerSettings,
} from "@t3tools/contracts";
import * as PlatformError from "effect/PlatformError";
import { ChildProcessSpawner } from "effect/unstable/process";
import { deepMerge } from "@t3tools/shared/Struct";
import {
checkCodexProviderStatus,
hasCustomModelProvider,
parseAuthStatusFromOutput,
readCodexConfigModelProvider,
} from "./CodexProvider";
import { checkClaudeProviderStatus, parseClaudeAuthStatusFromOutput } from "./ClaudeProvider";
import { haveProvidersChanged, ProviderRegistryLive } from "./ProviderRegistry";
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings";
import { ProviderRegistry } from "../Services/ProviderRegistry";
// ── Test helpers ────────────────────────────────────────────────────
const encoder = new TextEncoder();
function mockHandle(result: { stdout: string; stderr: string; code: number }) {
return ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(result.code)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
stdin: Sink.drain,
stdout: Stream.make(encoder.encode(result.stdout)),
stderr: Stream.make(encoder.encode(result.stderr)),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
}
function mockSpawnerLayer(
handler: (args: ReadonlyArray<string>) => { stdout: string; stderr: string; code: number },
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const cmd = command as unknown as { args: ReadonlyArray<string> };
return Effect.succeed(mockHandle(handler(cmd.args)));
}),
);
}
function mockCommandSpawnerLayer(
handler: (
command: string,
args: ReadonlyArray<string>,
) => { stdout: string; stderr: string; code: number },
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const cmd = command as unknown as { command: string; args: ReadonlyArray<string> };
return Effect.succeed(mockHandle(handler(cmd.command, cmd.args)));
}),
);
}
function failingSpawnerLayer(description: string) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.fail(
PlatformError.systemError({
_tag: "NotFound",
module: "ChildProcess",
method: "spawn",
description,
}),
),
),
);
}
function makeMutableServerSettingsService(
initial: ContractServerSettings = DEFAULT_SERVER_SETTINGS,
) {
return Effect.gen(function* () {
const settingsRef = yield* Ref.make(initial);
const changes = yield* PubSub.unbounded<ContractServerSettings>();
return {
start: Effect.void,
ready: Effect.void,
getSettings: Ref.get(settingsRef),
updateSettings: (patch) =>
Effect.gen(function* () {
const current = yield* Ref.get(settingsRef);
const next = Schema.decodeSync(ServerSettings)(deepMerge(current, patch));
yield* Ref.set(settingsRef, next);
yield* PubSub.publish(changes, next);
return next;
}),
streamChanges: Stream.fromPubSub(changes),
} satisfies ServerSettingsShape;
});
}
/**
* Create a temporary CODEX_HOME scoped to the current Effect test.
* Cleanup is registered in the test scope rather than via Vitest hooks.
*/
function withTempCodexHome(configContent?: string) {
return Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const tmpDir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-test-codex-" });
yield* Effect.acquireRelease(
Effect.sync(() => {
const originalCodexHome = process.env.CODEX_HOME;
process.env.CODEX_HOME = tmpDir;
return originalCodexHome;
}),
(originalCodexHome) =>
Effect.sync(() => {
if (originalCodexHome !== undefined) {
process.env.CODEX_HOME = originalCodexHome;
} else {
delete process.env.CODEX_HOME;
}
}),
);
if (configContent !== undefined) {
yield* fileSystem.writeFileString(path.join(tmpDir, "config.toml"), configContent);
}
return { tmpDir } as const;
});
}
it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
"ProviderRegistry",
(it) => {
// ── checkCodexProviderStatus tests ────────────────────────────────
//
// These tests control CODEX_HOME to ensure the custom-provider detection
// in hasCustomModelProvider() does not interfere with the auth-probe
// path being tested.
describe("checkCodexProviderStatus", () => {
it.effect("returns ready when codex is installed and authenticated", () =>
Effect.gen(function* () {
// Point CODEX_HOME at an empty tmp dir (no config.toml) so the
// default code path (OpenAI provider, auth probe runs) is exercised.
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") return { stdout: "Logged in\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("inherits PATH when launching the codex probe with a CODEX_HOME override", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const binDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-test-codex-bin-",
});
const codexPath = path.join(binDir, "codex");
yield* fileSystem.writeFileString(
codexPath,
[
"#!/bin/sh",
'if [ "$1" = "--version" ]; then',
' echo "codex-cli 1.0.0"',
" exit 0",
"fi",
'if [ "$1" = "login" ] && [ "$2" = "status" ]; then',
' echo "Logged in using ChatGPT"',
" exit 0",
"fi",
'echo "unexpected args: $*" >&2',
"exit 1",
"",
].join("\n"),
);
yield* fileSystem.chmod(codexPath, 0o755);
const customCodexHome = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-test-codex-home-",
});
const previousPath = process.env.PATH;
process.env.PATH = binDir;
try {
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
codex: {
homePath: customCodexHome,
},
},
});
const status = yield* checkCodexProviderStatus().pipe(
Effect.provide(serverSettingsLayer),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.authStatus, "authenticated");
} finally {
process.env.PATH = previousPath;
}
}),
);
it.effect("returns unavailable when codex is missing", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI (`codex`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
it.effect("returns unavailable when codex is below the minimum supported version", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 0.36.0\n", stderr: "", code: 0 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth probe reports login required", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "Not logged in. Run codex login.", code: 1 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when login status output includes 'not logged in'", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when login status command is unsupported", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status") {
return { stdout: "", stderr: "error: unknown command 'login'", code: 2 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
describe("ProviderRegistryLive", () => {
it("treats equal provider snapshots as unchanged", () => {
const providers = [
{
provider: "codex",
status: "ready",
enabled: true,
installed: true,
authStatus: "authenticated",
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
},
{
provider: "claudeAgent",
status: "warning",
enabled: true,
installed: true,
authStatus: "unknown",
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
},
] as const satisfies ReadonlyArray<ServerProvider>;
assert.strictEqual(haveProvidersChanged(providers, [...providers]), false);
});
it.effect("reruns codex health when codex provider settings change", () =>
Effect.gen(function* () {
const serverSettings = yield* makeMutableServerSettingsService();
const scope = yield* Scope.make();
yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
const providerRegistryLayer = ProviderRegistryLive.pipe(
Layer.provideMerge(Layer.succeed(ServerSettingsService, serverSettings)),
Layer.provideMerge(
mockCommandSpawnerLayer((command, args) => {
const joined = args.join(" ");
if (joined === "--version") {
if (command === "codex") {
return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
}
return { stdout: "", stderr: "spawn ENOENT", code: 1 };
}
if (joined === "login status") {
return { stdout: "Logged in\n", stderr: "", code: 0 };
}
throw new Error(`Unexpected args: ${joined}`);
}),
),
);
const runtimeServices = yield* Layer.build(
Layer.mergeAll(
Layer.succeed(ServerSettingsService, serverSettings),
providerRegistryLayer,
),
).pipe(Scope.provide(scope));
yield* Effect.gen(function* () {
const registry = yield* ProviderRegistry;
const initial = yield* registry.getProviders;
assert.strictEqual(
initial.find((status) => status.provider === "codex")?.status,
"ready",
);
yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: "/custom/codex",
},
},
});
for (let attempt = 0; attempt < 20; attempt += 1) {
const updated = yield* registry.getProviders;
if (updated.find((status) => status.provider === "codex")?.status === "error") {
return;
}
yield* Effect.promise(() => new Promise((resolve) => setTimeout(resolve, 0)));
}
const updated = yield* registry.getProviders;
assert.strictEqual(
updated.find((status) => status.provider === "codex")?.status,
"error",
);
}).pipe(Effect.provide(runtimeServices));
}),
);
it.effect("skips codex probes entirely when the provider is disabled", () =>
Effect.gen(function* () {
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
codex: {
enabled: false,
},
},
});
const status = yield* checkCodexProviderStatus().pipe(
Effect.provide(
Layer.mergeAll(serverSettingsLayer, failingSpawnerLayer("spawn codex ENOENT")),
),
);
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.enabled, false);
assert.strictEqual(status.status, "disabled");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.message, "Codex is disabled in T3 Code settings.");
}),
);
});
// ── Custom model provider: checkCodexProviderStatus integration ───
describe("checkCodexProviderStatus with custom model provider", () => {
it.effect(
"skips auth probe and returns ready when a custom model provider is configured",
() =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.provider, "codex");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
);
}).pipe(
Effect.provide(
// The spawner only handles --version; if the test attempts
// "login status" the throw proves the auth probe was NOT skipped.
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
throw new Error(`Auth probe should have been skipped but got args: ${joined}`);
}),
),
),
);
it.effect("still reports error when codex CLI is missing even with custom provider", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model_provider = "portkey"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'env_key = "PORTKEY_API_KEY"',
].join("\n"),
);
const status = yield* checkCodexProviderStatus();
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
}).pipe(Effect.provide(failingSpawnerLayer("spawn codex ENOENT"))),
);
});
describe("checkCodexProviderStatus with openai model provider", () => {
it.effect("still runs auth probe when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
const status = yield* checkCodexProviderStatus();
// The auth probe runs and sees "not logged in" → error
assert.strictEqual(status.status, "error");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "codex 1.0.0\n", stderr: "", code: 0 };
if (joined === "login status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseAuthStatusFromOutput pure tests ──────────────────────────
describe("parseAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"authenticated":false}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseAuthStatusFromOutput({
stdout: '[{"ok":true}]\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
// ── readCodexConfigModelProvider tests ─────────────────────────────
describe("readCodexConfigModelProvider", () => {
it.effect("returns undefined when config file does not exist", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
}),
);
it.effect("returns undefined when config has no model_provider key", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
}),
);
it.effect("returns the provider when model_provider is set at top level", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\nmodel_provider = "portkey"\n');
assert.strictEqual(yield* readCodexConfigModelProvider(), "portkey");
}),
);
it.effect("returns openai when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* readCodexConfigModelProvider(), "openai");
}),
);
it.effect("ignores model_provider inside section headers", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
'model = "gpt-5-codex"',
"",
"[model_providers.portkey]",
'base_url = "https://api.portkey.ai/v1"',
'model_provider = "should-be-ignored"',
"",
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider(), undefined);
}),
);
it.effect("handles comments and whitespace", () =>
Effect.gen(function* () {
yield* withTempCodexHome(
[
"# This is a comment",
"",
' model_provider = "azure" ',
"",
"[profiles.deep-review]",
'model = "gpt-5-pro"',
].join("\n"),
);
assert.strictEqual(yield* readCodexConfigModelProvider(), "azure");
}),
);
it.effect("handles single-quoted values in TOML", () =>
Effect.gen(function* () {
yield* withTempCodexHome("model_provider = 'mistral'\n");
assert.strictEqual(yield* readCodexConfigModelProvider(), "mistral");
}),
);
});
// ── hasCustomModelProvider tests ───────────────────────────────────
describe("hasCustomModelProvider", () => {
it.effect("returns false when no config file exists", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is not set", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model = "gpt-5-codex"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns false when model_provider is openai", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "openai"\n');
assert.strictEqual(yield* hasCustomModelProvider, false);
}),
);
it.effect("returns true when model_provider is portkey", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "portkey"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is azure", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "azure"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is ollama", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "ollama"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
it.effect("returns true when model_provider is a custom proxy", () =>
Effect.gen(function* () {
yield* withTempCodexHome('model_provider = "my-company-proxy"\n');
assert.strictEqual(yield* hasCustomModelProvider, true);
}),
);
});
// ── checkClaudeProviderStatus tests ──────────────────────────
describe("checkClaudeProviderStatus", () => {
it.effect("returns ready when claude is installed and authenticated", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "ready");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unavailable when claude is missing", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, false);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
);
}).pipe(Effect.provide(failingSpawnerLayer("spawn claude ENOENT"))),
);
it.effect("returns error when version check fails with non-zero exit code", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version")
return { stdout: "", stderr: "Something went wrong", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when auth status reports not logged in", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return {
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 1,
};
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns unauthenticated when output includes 'not logged in'", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "error");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return { stdout: "Not logged in\n", stderr: "", code: 1 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
it.effect("returns warning when auth status command is unsupported", () =>
Effect.gen(function* () {
const status = yield* checkClaudeProviderStatus();
assert.strictEqual(status.provider, "claudeAgent");
assert.strictEqual(status.status, "warning");
assert.strictEqual(status.installed, true);
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
);
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
const joined = args.join(" ");
if (joined === "--version") return { stdout: "1.0.0\n", stderr: "", code: 0 };
if (joined === "auth status")
return { stdout: "", stderr: "error: unknown command 'auth'", code: 2 };
throw new Error(`Unexpected args: ${joined}`);
}),
),
),
);
});
// ── parseClaudeAuthStatusFromOutput pure tests ────────────────────
describe("parseClaudeAuthStatusFromOutput", () => {
it("exit code 0 with no auth markers is ready", () => {
const parsed = parseClaudeAuthStatusFromOutput({ stdout: "OK\n", stderr: "", code: 0 });
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":true,"authMethod":"claude.ai"}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"loggedIn":false}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
const parsed = parseClaudeAuthStatusFromOutput({
stdout: '{"ok":true}\n',
stderr: "",
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
},
);
@@ -1,93 +0,0 @@
/**
* ProviderRegistryLive - Aggregates provider-specific snapshot services.
*
* @module ProviderRegistryLive
*/
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
import { Effect, Equal, Layer, PubSub, Ref, Stream } from "effect";
import { ClaudeProviderLive } from "./ClaudeProvider";
import { CodexProviderLive } from "./CodexProvider";
import type { ClaudeProviderShape } from "../Services/ClaudeProvider";
import { ClaudeProvider } from "../Services/ClaudeProvider";
import type { CodexProviderShape } from "../Services/CodexProvider";
import { CodexProvider } from "../Services/CodexProvider";
import { ProviderRegistry, type ProviderRegistryShape } from "../Services/ProviderRegistry";
const loadProviders = (
codexProvider: CodexProviderShape,
claudeProvider: ClaudeProviderShape,
): Effect.Effect<readonly [ServerProvider, ServerProvider]> =>
Effect.all([codexProvider.getSnapshot, claudeProvider.getSnapshot], {
concurrency: "unbounded",
});
export const haveProvidersChanged = (
previousProviders: ReadonlyArray<ServerProvider>,
nextProviders: ReadonlyArray<ServerProvider>,
): boolean => !Equal.equals(previousProviders, nextProviders);
export const ProviderRegistryLive = Layer.effect(
ProviderRegistry,
Effect.gen(function* () {
const codexProvider = yield* CodexProvider;
const claudeProvider = yield* ClaudeProvider;
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ReadonlyArray<ServerProvider>>(),
PubSub.shutdown,
);
const providersRef = yield* Ref.make<ReadonlyArray<ServerProvider>>(
yield* loadProviders(codexProvider, claudeProvider),
);
const syncProviders = (options?: { readonly publish?: boolean }) =>
Effect.gen(function* () {
const previousProviders = yield* Ref.get(providersRef);
const providers = yield* loadProviders(codexProvider, claudeProvider);
yield* Ref.set(providersRef, providers);
if (options?.publish !== false && haveProvidersChanged(previousProviders, providers)) {
yield* PubSub.publish(changesPubSub, providers);
}
return providers;
});
yield* Stream.runForEach(codexProvider.streamChanges, () => syncProviders()).pipe(
Effect.forkScoped,
);
yield* Stream.runForEach(claudeProvider.streamChanges, () => syncProviders()).pipe(
Effect.forkScoped,
);
return {
getProviders: syncProviders({ publish: false }).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
refresh: (provider?: ProviderKind) =>
Effect.gen(function* () {
switch (provider) {
case "codex":
yield* codexProvider.refresh;
break;
case "claudeAgent":
yield* claudeProvider.refresh;
break;
default:
yield* Effect.all([codexProvider.refresh, claudeProvider.refresh], {
concurrency: "unbounded",
});
break;
}
return yield* syncProviders();
}).pipe(
Effect.tapError(Effect.logError),
Effect.orElseSucceed(() => []),
),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ProviderRegistryShape;
}),
).pipe(Layer.provideMerge(CodexProviderLive), Layer.provideMerge(ClaudeProviderLive));
@@ -42,11 +42,8 @@ import {
makeSqlitePersistenceLive,
SqlitePersistenceMemory,
} from "../../persistence/Layers/Sqlite.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
const defaultServerSettingsLayer = ServerSettingsService.layerTest();
const asRequestId = (value: string): ApprovalRequestId => ApprovalRequestId.makeUnsafe(value);
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
@@ -254,7 +251,6 @@ function makeProviderServiceLayer() {
makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provideMerge(AnalyticsService.layerTest),
),
directoryLayer,
@@ -271,55 +267,6 @@ function makeProviderServiceLayer() {
};
}
it.effect("ProviderServiceLive rejects new sessions for disabled providers", () =>
Effect.gen(function* () {
const codex = makeFakeCodexAdapter();
const claude = makeFakeCodexAdapter("claudeAgent");
const registry: typeof ProviderAdapterRegistry.Service = {
getByProvider: (provider) =>
provider === "codex"
? Effect.succeed(codex.adapter)
: provider === "claudeAgent"
? Effect.succeed(claude.adapter)
: Effect.fail(new ProviderUnsupportedError({ provider })),
listProviders: () => Effect.succeed(["codex", "claudeAgent"]),
};
const providerAdapterLayer = Layer.succeed(ProviderAdapterRegistry, registry);
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
claudeAgent: {
enabled: false,
},
},
});
const runtimeRepositoryLayer = ProviderSessionRuntimeRepositoryLive.pipe(
Layer.provide(SqlitePersistenceMemory),
);
const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer));
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(providerAdapterLayer),
Layer.provide(directoryLayer),
Layer.provide(serverSettingsLayer),
Layer.provide(AnalyticsService.layerTest),
);
const failure = yield* Effect.flip(
Effect.gen(function* () {
const provider = yield* ProviderService;
return yield* provider.startSession(asThreadId("thread-disabled"), {
provider: "claudeAgent",
threadId: asThreadId("thread-disabled"),
runtimeMode: "full-access",
});
}).pipe(Effect.provide(providerLayer)),
);
assert.instanceOf(failure, ProviderValidationError);
assert.include(failure.issue, "Provider 'claudeAgent' is disabled in T3 Code settings.");
assert.equal(claude.startSession.mock.calls.length, 0);
}).pipe(Effect.provide(NodeServices.layer)),
);
const routing = makeProviderServiceLayer();
it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", () =>
Effect.gen(function* () {
@@ -352,7 +299,6 @@ it.effect("ProviderServiceLive keeps persisted resumable sessions on startup", (
const providerLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, registry)),
Layer.provide(directoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(AnalyticsService.layerTest),
);
@@ -412,7 +358,6 @@ it.effect(
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(AnalyticsService.layerTest),
);
const updatedResumeCursor = {
@@ -464,7 +409,6 @@ it.effect(
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(AnalyticsService.layerTest),
);
@@ -825,7 +769,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
const firstProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
Layer.provide(firstDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(AnalyticsService.layerTest),
);
@@ -858,7 +801,6 @@ routing.layer("ProviderServiceLive routing", (it) => {
const secondProviderLayer = makeProviderServiceLive().pipe(
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
Layer.provide(secondDirectoryLayer),
Layer.provide(defaultServerSettingsLayer),
Layer.provide(AnalyticsService.layerTest),
);
@@ -33,7 +33,6 @@ import {
} from "../Services/ProviderSessionDirectory.ts";
import { type EventNdjsonLogger, makeEventNdjsonLogger } from "./EventNdjsonLogger.ts";
import { AnalyticsService } from "../../telemetry/Services/AnalyticsService.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
export interface ProviderServiceLiveOptions {
readonly canonicalEventLogPath?: string;
@@ -92,6 +91,7 @@ function toRuntimePayloadFromSession(
session: ProviderSession,
extra?: {
readonly modelSelection?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
@@ -102,6 +102,7 @@ function toRuntimePayloadFromSession(
activeTurnId: session.activeTurnId ?? null,
lastError: session.lastError ?? null,
...(extra?.modelSelection !== undefined ? { modelSelection: extra.modelSelection } : {}),
...(extra?.providerOptions !== undefined ? { providerOptions: extra.providerOptions } : {}),
...(extra?.lastRuntimeEvent !== undefined ? { lastRuntimeEvent: extra.lastRuntimeEvent } : {}),
...(extra?.lastRuntimeEventAt !== undefined
? { lastRuntimeEventAt: extra.lastRuntimeEventAt }
@@ -119,6 +120,17 @@ function readPersistedModelSelection(
return Schema.is(ModelSelection)(raw) ? raw : undefined;
}
function readPersistedProviderOptions(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): Record<string, unknown> | undefined {
if (!runtimePayload || typeof runtimePayload !== "object" || Array.isArray(runtimePayload)) {
return undefined;
}
const raw = "providerOptions" in runtimePayload ? runtimePayload.providerOptions : undefined;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
return raw as Record<string, unknown>;
}
function readPersistedCwd(
runtimePayload: ProviderRuntimeBinding["runtimePayload"],
): string | undefined {
@@ -134,7 +146,6 @@ function readPersistedCwd(
const makeProviderService = (options?: ProviderServiceLiveOptions) =>
Effect.gen(function* () {
const analytics = yield* Effect.service(AnalyticsService);
const serverSettings = yield* ServerSettingsService;
const canonicalEventLogger =
options?.canonicalEventLogger ??
(options?.canonicalEventLogPath !== undefined
@@ -162,6 +173,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
threadId: ThreadId,
extra?: {
readonly modelSelection?: unknown;
readonly providerOptions?: unknown;
readonly lastRuntimeEvent?: string;
readonly lastRuntimeEventAt?: string;
},
@@ -227,12 +239,14 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
const persistedCwd = readPersistedCwd(input.binding.runtimePayload);
const persistedModelSelection = readPersistedModelSelection(input.binding.runtimePayload);
const persistedProviderOptions = readPersistedProviderOptions(input.binding.runtimePayload);
const resumed = yield* adapter.startSession({
threadId: input.binding.threadId,
provider: input.binding.provider,
...(persistedCwd ? { cwd: persistedCwd } : {}),
...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}),
...(persistedProviderOptions ? { providerOptions: persistedProviderOptions } : {}),
...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}),
runtimeMode: input.binding.runtimeMode ?? "full-access",
});
@@ -294,21 +308,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
threadId,
provider: parsed.provider ?? "codex",
};
const settings = yield* serverSettings.getSettings.pipe(
Effect.mapError((error) =>
toValidationError(
"ProviderService.startSession",
`Failed to load provider settings: ${error.message}`,
error,
),
),
);
if (!settings.providers[input.provider].enabled) {
return yield* toValidationError(
"ProviderService.startSession",
`Provider '${input.provider}' is disabled in T3 Code settings.`,
);
}
const persistedBinding = Option.getOrUndefined(yield* directory.getBinding(threadId));
const effectiveResumeCursor =
input.resumeCursor ??
@@ -330,6 +329,7 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
yield* upsertSessionBinding(session, threadId, {
modelSelection: input.modelSelection,
providerOptions: input.providerOptions,
});
yield* analytics.record("provider.session.started", {
provider: session.provider,
@@ -1,9 +0,0 @@
import { ServiceMap } from "effect";
import type { ServerProviderShape } from "./ServerProvider";
export interface ClaudeProviderShape extends ServerProviderShape {}
export class ClaudeProvider extends ServiceMap.Service<ClaudeProvider, ClaudeProviderShape>()(
"t3/provider/Services/ClaudeProvider",
) {}
@@ -1,9 +0,0 @@
import { ServiceMap } from "effect";
import type { ServerProviderShape } from "./ServerProvider";
export interface CodexProviderShape extends ServerProviderShape {}
export class CodexProvider extends ServiceMap.Service<CodexProvider, CodexProviderShape>()(
"t3/provider/Services/CodexProvider",
) {}
@@ -0,0 +1,22 @@
/**
* ProviderHealth - Provider readiness snapshot service.
*
* Owns provider health checks (install/auth reachability) and exposes the
* latest results to transport layers.
*
* @module ProviderHealth
*/
import type { ServerProviderStatus } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect } from "effect";
export interface ProviderHealthShape {
/**
* Read the latest provider health statuses.
*/
readonly getStatuses: Effect.Effect<ReadonlyArray<ServerProviderStatus>>;
}
export class ProviderHealth extends ServiceMap.Service<ProviderHealth, ProviderHealthShape>()(
"t3/provider/Services/ProviderHealth",
) {}
@@ -1,32 +0,0 @@
/**
* ProviderRegistry - Provider snapshot service.
*
* Owns provider install/auth/version/model snapshots and exposes the latest
* provider state to transport layers.
*
* @module ProviderRegistry
*/
import type { ProviderKind, ServerProvider } from "@t3tools/contracts";
import { ServiceMap } from "effect";
import type { Effect, Stream } from "effect";
export interface ProviderRegistryShape {
/**
* Read the latest provider snapshots.
*/
readonly getProviders: Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Refresh all providers, or a single provider when specified.
*/
readonly refresh: (provider?: ProviderKind) => Effect.Effect<ReadonlyArray<ServerProvider>>;
/**
* Stream of provider snapshot updates.
*/
readonly streamChanges: Stream.Stream<ReadonlyArray<ServerProvider>>;
}
export class ProviderRegistry extends ServiceMap.Service<ProviderRegistry, ProviderRegistryShape>()(
"t3/provider/Services/ProviderRegistry",
) {}
@@ -1,8 +0,0 @@
import type { ServerProvider } from "@t3tools/contracts";
import type { Effect, Stream } from "effect";
export interface ServerProviderShape {
readonly getSnapshot: Effect.Effect<ServerProvider>;
readonly refresh: Effect.Effect<ServerProvider>;
readonly streamChanges: Stream.Stream<ServerProvider>;
}
@@ -1,72 +0,0 @@
import type { ServerProvider } from "@t3tools/contracts";
import { Duration, Effect, PubSub, Ref, Scope, Stream } from "effect";
import * as Semaphore from "effect/Semaphore";
import type { ServerProviderShape } from "./Services/ServerProvider";
import { ServerSettingsError } from "../serverSettings";
export function makeManagedServerProvider<Settings>(input: {
readonly getSettings: Effect.Effect<Settings>;
readonly streamSettings: Stream.Stream<Settings>;
readonly haveSettingsChanged: (previous: Settings, next: Settings) => boolean;
readonly checkProvider: Effect.Effect<ServerProvider, ServerSettingsError>;
readonly refreshInterval?: Duration.Input;
}): Effect.Effect<ServerProviderShape, ServerSettingsError, Scope.Scope> {
return Effect.gen(function* () {
const refreshSemaphore = yield* Semaphore.make(1);
const changesPubSub = yield* Effect.acquireRelease(
PubSub.unbounded<ServerProvider>(),
PubSub.shutdown,
);
const initialSettings = yield* input.getSettings;
const initialSnapshot = yield* input.checkProvider;
const snapshotRef = yield* Ref.make(initialSnapshot);
const settingsRef = yield* Ref.make(initialSettings);
const applySnapshot = (nextSettings: Settings, options?: { readonly forceRefresh?: boolean }) =>
refreshSemaphore.withPermits(1)(
Effect.gen(function* () {
const forceRefresh = options?.forceRefresh === true;
const previousSettings = yield* Ref.get(settingsRef);
if (!forceRefresh && !input.haveSettingsChanged(previousSettings, nextSettings)) {
yield* Ref.set(settingsRef, nextSettings);
return yield* Ref.get(snapshotRef);
}
const nextSnapshot = yield* input.checkProvider;
yield* Ref.set(settingsRef, nextSettings);
yield* Ref.set(snapshotRef, nextSnapshot);
yield* PubSub.publish(changesPubSub, nextSnapshot);
return nextSnapshot;
}),
);
const refreshSnapshot = Effect.gen(function* () {
const nextSettings = yield* input.getSettings;
return yield* applySnapshot(nextSettings, { forceRefresh: true });
});
yield* Stream.runForEach(input.streamSettings, (nextSettings) =>
Effect.asVoid(applySnapshot(nextSettings)),
).pipe(Effect.forkScoped);
yield* Effect.forever(
Effect.sleep(input.refreshInterval ?? "60 seconds").pipe(
Effect.flatMap(() => refreshSnapshot),
Effect.ignoreCause({ log: true }),
),
).pipe(Effect.forkScoped);
return {
getSnapshot: input.getSettings.pipe(
Effect.flatMap(applySnapshot),
Effect.tapError(Effect.logError),
Effect.orDie,
),
refresh: refreshSnapshot.pipe(Effect.tapError(Effect.logError), Effect.orDie),
get streamChanges() {
return Stream.fromPubSub(changesPubSub);
},
} satisfies ServerProviderShape;
});
}
@@ -1,134 +0,0 @@
import type {
ServerProvider,
ServerProviderAuthStatus,
ServerProviderModel,
ServerProviderState,
} from "@t3tools/contracts";
import { Effect, Stream } from "effect";
import { normalizeModelSlug } from "@t3tools/shared/model";
export const DEFAULT_TIMEOUT_MS = 4_000;
export interface CommandResult {
readonly stdout: string;
readonly stderr: string;
readonly code: number;
}
export interface ProviderProbeResult {
readonly installed: boolean;
readonly version: string | null;
readonly status: Exclude<ServerProviderState, "disabled">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
}
export function nonEmptyTrimmed(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
export function isCommandMissingCause(error: unknown): boolean {
if (!(error instanceof Error)) return false;
const lower = error.message.toLowerCase();
return lower.includes("enoent") || lower.includes("notfound");
}
export function detailFromResult(
result: CommandResult & { readonly timedOut?: boolean },
): string | undefined {
if (result.timedOut) return "Timed out while running command.";
const stderr = nonEmptyTrimmed(result.stderr);
if (stderr) return stderr;
const stdout = nonEmptyTrimmed(result.stdout);
if (stdout) return stdout;
if (result.code !== 0) {
return `Command exited with code ${result.code}.`;
}
return undefined;
}
export function extractAuthBoolean(value: unknown): boolean | undefined {
if (globalThis.Array.isArray(value)) {
for (const entry of value) {
const nested = extractAuthBoolean(entry);
if (nested !== undefined) return nested;
}
return undefined;
}
if (!value || typeof value !== "object") return undefined;
const record = value as Record<string, unknown>;
for (const key of ["authenticated", "isAuthenticated", "loggedIn", "isLoggedIn"] as const) {
if (typeof record[key] === "boolean") return record[key];
}
for (const key of ["auth", "status", "session", "account"] as const) {
const nested = extractAuthBoolean(record[key]);
if (nested !== undefined) return nested;
}
return undefined;
}
export function parseGenericCliVersion(output: string): string | null {
const match = output.match(/\b(\d+\.\d+\.\d+)\b/);
return match?.[1] ?? null;
}
export function providerModelsFromSettings(
builtInModels: ReadonlyArray<ServerProviderModel>,
provider: ServerProvider["provider"],
customModels: ReadonlyArray<string>,
): ReadonlyArray<ServerProviderModel> {
const resolvedBuiltInModels = [...builtInModels];
const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
const customEntries: ServerProviderModel[] = [];
for (const candidate of customModels) {
const normalized = normalizeModelSlug(candidate, provider);
if (!normalized || seen.has(normalized)) {
continue;
}
seen.add(normalized);
customEntries.push({
slug: normalized,
name: normalized,
isCustom: true,
capabilities: null,
});
}
return [...resolvedBuiltInModels, ...customEntries];
}
export function buildServerProvider(input: {
provider: ServerProvider["provider"];
enabled: boolean;
checkedAt: string;
models: ReadonlyArray<ServerProviderModel>;
probe: ProviderProbeResult;
}): ServerProvider {
return {
provider: input.provider,
enabled: input.enabled,
installed: input.probe.installed,
version: input.probe.version,
status: input.enabled ? input.probe.status : "disabled",
authStatus: input.probe.authStatus,
checkedAt: input.checkedAt,
...(input.probe.message ? { message: input.probe.message } : {}),
models: input.models,
};
}
export const collectStreamAsString = <E>(
stream: Stream.Stream<Uint8Array, E>,
): Effect.Effect<string, E> =>
stream.pipe(
Stream.decodeText(),
Stream.runFold(
() => "",
(acc, chunk) => acc + chunk,
),
);
+1 -6
View File
@@ -24,7 +24,6 @@ import { makeProviderServiceLive } from "./provider/Layers/ProviderService";
import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory";
import { ProviderService } from "./provider/Services/ProviderService";
import { makeEventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger";
import { ServerSettingsService } from "./serverSettings";
import { TerminalManagerLive } from "./terminal/Layers/Manager";
import { KeybindingsLive } from "./keybindings";
@@ -55,11 +54,7 @@ const makeRuntimePtyAdapterLayer = () =>
export function makeServerProviderLayer(): Layer.Layer<
ProviderService,
ProviderUnsupportedError,
| SqlClient.SqlClient
| ServerConfig
| ServerSettingsService
| FileSystem.FileSystem
| AnalyticsService
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
> {
return Effect.gen(function* () {
const { providerEventLogPath } = yield* ServerConfig;
+1 -79
View File
@@ -1,7 +1,7 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { DEFAULT_SERVER_SETTINGS, ServerSettingsPatch } from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import { Effect, FileSystem, Layer, Schema } from "effect";
import { Effect, Layer, Schema } from "effect";
import { ServerConfig } from "./config";
import { ServerSettingsLive, ServerSettingsService } from "./serverSettings";
@@ -83,13 +83,11 @@ it.layer(NodeServices.layer)("server settings", (it) => {
});
assert.deepEqual(next.providers.codex, {
enabled: true,
binaryPath: "/opt/homebrew/bin/codex",
homePath: "/Users/julius/.codex",
customModels: [],
});
assert.deepEqual(next.providers.claudeAgent, {
enabled: true,
binaryPath: "/usr/local/bin/claude",
customModels: ["claude-custom"],
});
@@ -103,80 +101,4 @@ it.layer(NodeServices.layer)("server settings", (it) => {
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("trims provider path settings when updates are applied", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const next = yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: " /opt/homebrew/bin/codex ",
homePath: " ",
},
claudeAgent: {
binaryPath: " /opt/homebrew/bin/claude ",
},
},
});
assert.deepEqual(next.providers.codex, {
enabled: true,
binaryPath: "/opt/homebrew/bin/codex",
homePath: "",
customModels: [],
});
assert.deepEqual(next.providers.claudeAgent, {
enabled: true,
binaryPath: "/opt/homebrew/bin/claude",
customModels: [],
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("defaults blank binary paths to provider executables", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const next = yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: " ",
},
claudeAgent: {
binaryPath: "",
},
},
});
assert.equal(next.providers.codex.binaryPath, "codex");
assert.equal(next.providers.claudeAgent.binaryPath, "claude");
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("writes only non-default server settings to disk", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const next = yield* serverSettings.updateSettings({
providers: {
codex: {
binaryPath: "/opt/homebrew/bin/codex",
},
},
});
assert.equal(next.providers.codex.binaryPath, "/opt/homebrew/bin/codex");
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
providers: {
codex: {
binaryPath: "/opt/homebrew/bin/codex",
},
},
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
});
+60 -99
View File
@@ -11,10 +11,8 @@
* @module ServerSettings
*/
import {
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
DEFAULT_SERVER_SETTINGS,
type ModelSelection,
type ProviderKind,
type ProviderStartOptions,
ServerSettings,
type ServerSettingsPatch,
} from "@t3tools/contracts";
@@ -30,14 +28,14 @@ import {
PubSub,
Ref,
Schema,
SchemaIssue,
SchemaGetter,
Scope,
ServiceMap,
Stream,
} from "effect";
import * as Semaphore from "effect/Semaphore";
import { ServerConfig } from "./config";
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
import { deepMerge } from "@t3tools/shared/Struct";
import { fromLenientJson } from "@t3tools/shared/schemaJson";
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
@@ -76,87 +74,58 @@ export class ServerSettingsService extends ServiceMap.Service<
ServerSettingsService,
ServerSettingsShape
>()("t3/serverSettings/ServerSettingsService") {
static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
Layer.effect(
ServerSettingsService,
Effect.gen(function* () {
const currentSettingsRef = yield* Ref.make<ServerSettings>(
deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
);
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);
}
return {
start: Effect.void,
ready: Effect.void,
getSettings: Ref.get(currentSettingsRef),
updateSettings: (patch) =>
Ref.get(currentSettingsRef).pipe(
Effect.map((currentSettings) => deepMerge(currentSettings, patch)),
Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
),
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.providers.codex
? {
codex: {
...(settings.providers.codex.binaryPath
? { binaryPath: settings.providers.codex.binaryPath }
: {}),
...(settings.providers.codex.homePath
? { homePath: settings.providers.codex.homePath }
: {}),
},
}
: {}),
...(settings.providers.claudeAgent
? {
claudeAgent: {
binaryPath: settings.providers.claudeAgent.binaryPath,
},
}
: {}),
};
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
}
const ServerSettingsJson = fromLenientJson(ServerSettings);
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
/**
* Ensure the `textGenerationModelSelection` points to an enabled provider.
* If the selected provider is disabled, fall back to the first enabled
* provider with its default model. This is applied at read-time so the
* persisted preference is preserved for when a provider is re-enabled.
*/
function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
const selection = settings.textGenerationModelSelection;
if (settings.providers[selection.provider].enabled) {
return settings;
}
const fallback = PROVIDER_ORDER.find((p) => settings.providers[p].enabled);
if (!fallback) {
// No providers enabled — return as-is; callers will report the error.
return settings;
}
return {
...settings,
textGenerationModelSelection: {
provider: fallback,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback],
} as ModelSelection,
};
}
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
if (Array.isArray(current) || Array.isArray(defaults)) {
return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current;
}
if (
current !== null &&
defaults !== null &&
typeof current === "object" &&
typeof defaults === "object"
) {
const currentRecord = current as Record<string, unknown>;
const defaultsRecord = defaults as Record<string, unknown>;
const next: Record<string, unknown> = {};
for (const key of Object.keys(currentRecord)) {
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
if (stripped !== undefined) {
next[key] = stripped;
}
}
return Object.keys(next).length > 0 ? next : undefined;
}
return Object.is(current, defaults) ? undefined : current;
}
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;
@@ -220,9 +189,9 @@ const makeServerSettings = Effect.gen(function* () {
const writeSettingsAtomically = (settings: ServerSettings) => {
const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
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)),
@@ -285,11 +254,12 @@ const makeServerSettings = Effect.gen(function* () {
});
const start = Effect.gen(function* () {
const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
if (!shouldStart) {
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);
@@ -308,29 +278,20 @@ const makeServerSettings = Effect.gen(function* () {
return {
start,
ready: Deferred.await(startedDeferred),
getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)),
getSettings: getSettingsFromCache,
updateSettings: (patch) =>
writeSemaphore.withPermits(1)(
Effect.gen(function* () {
const current = yield* getSettingsFromCache;
const next = yield* Schema.decodeEffect(ServerSettings)(deepMerge(current, patch)).pipe(
Effect.mapError(
(cause) =>
new ServerSettingsError({
settingsPath: "<memory>",
detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
cause,
}),
),
);
const next = deepMerge(current, patch);
yield* writeSettingsAtomically(next);
yield* Cache.set(settingsCache, cacheKey, next);
yield* emitChange(next);
return resolveTextGenerationProvider(next);
return next;
}),
),
get streamChanges() {
return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider));
return Stream.fromPubSub(changesPubSub);
},
} satisfies ServerSettingsShape;
});
+14 -18
View File
@@ -26,7 +26,7 @@ import {
WS_METHODS,
type WebSocketResponse,
type ProviderRuntimeEvent,
type ServerProvider,
type ServerProviderStatus,
type KeybindingsConfig,
type ResolvedKeybindingsConfig,
type WsPushChannel,
@@ -47,7 +47,7 @@ import { TerminalManager, type TerminalManagerShape } from "./terminal/Services/
import { makeSqlitePersistenceLive, SqlitePersistenceMemory } from "./persistence/Layers/Sqlite";
import { SqlClient, SqlError } from "effect/unstable/sql";
import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService";
import { ProviderRegistry, type ProviderRegistryShape } from "./provider/Services/ProviderRegistry";
import { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth";
import { Open, type OpenShape } from "./open";
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
import type { GitCoreShape } from "./git/Services/GitCore.ts";
@@ -67,23 +67,18 @@ const defaultOpenService: OpenShape = {
openInEditor: () => Effect.void,
};
const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
const defaultProviderStatuses: ReadonlyArray<ServerProviderStatus> = [
{
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
];
const defaultProviderRegistryService: ProviderRegistryShape = {
getProviders: Effect.succeed(defaultProviderStatuses),
refresh: () => Effect.succeed(defaultProviderStatuses),
streamChanges: Stream.empty,
const defaultProviderHealthService: ProviderHealthShape = {
getStatuses: Effect.succeed(defaultProviderStatuses),
};
const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
@@ -497,7 +492,7 @@ describe("WebSocket Server", () => {
baseDir?: string;
staticDir?: string;
providerLayer?: Layer.Layer<ProviderService, never>;
providerRegistry?: ProviderRegistryShape;
providerHealth?: ProviderHealthShape;
open?: OpenShape;
gitManager?: GitManagerShape;
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
@@ -515,9 +510,9 @@ describe("WebSocket Server", () => {
const scope = await Effect.runPromise(Scope.make("sequential"));
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
const providerRegistryLayer = Layer.succeed(
ProviderRegistry,
options.providerRegistry ?? defaultProviderRegistryService,
const providerHealthLayer = Layer.succeed(
ProviderHealth,
options.providerHealth ?? defaultProviderHealthService,
);
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
const serverConfigLayer = Layer.succeed(ServerConfig, {
@@ -554,7 +549,7 @@ describe("WebSocket Server", () => {
);
const dependenciesLayer = Layer.empty.pipe(
Layer.provideMerge(runtimeLayer),
Layer.provideMerge(providerRegistryLayer),
Layer.provideMerge(providerHealthLayer),
Layer.provideMerge(openLayer),
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
Layer.provideMerge(serverConfigLayer),
@@ -967,7 +962,7 @@ describe("WebSocket Server", () => {
keybindingsConfigPath: string;
keybindings: ResolvedKeybindingsConfig;
issues: Array<{ kind: string; index?: number; message: string }>;
providers: ReadonlyArray<ServerProvider>;
providers: ReadonlyArray<ServerProviderStatus>;
availableEditors: unknown;
};
expect(result.cwd).toBe("/my/workspace");
@@ -1015,6 +1010,7 @@ describe("WebSocket Server", () => {
);
expect(malformedPush.data).toEqual({
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
providers: defaultProviderStatuses,
});
const successPush = await rewriteKeybindingsAndWaitForPush(
@@ -1023,7 +1019,7 @@ describe("WebSocket Server", () => {
"[]",
(push) => Array.isArray(push.data.issues) && push.data.issues.length === 0,
);
expect(successPush.data).toEqual({ issues: [] });
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
});
it("routes shell.openInEditor through the injected open service", async () => {
+7 -15
View File
@@ -55,7 +55,7 @@ import { OrchestrationEngineService } from "./orchestration/Services/Orchestrati
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
import { ProviderService } from "./provider/Services/ProviderService";
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
import { ProviderHealth } from "./provider/Services/ProviderHealth";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open, resolveAvailableEditors } from "./open";
@@ -209,7 +209,7 @@ export type ServerCoreRuntimeServices =
| CheckpointDiffQuery
| OrchestrationReactor
| ProviderService
| ProviderRegistry;
| ProviderHealth;
export type ServerRuntimeServices =
| ServerCoreRuntimeServices
@@ -256,7 +256,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const terminalManager = yield* TerminalManager;
const keybindingsManager = yield* Keybindings;
const serverSettingsManager = yield* ServerSettingsService;
const providerRegistry = yield* ProviderRegistry;
const providerHealth = yield* ProviderHealth;
const git = yield* GitCore;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -271,7 +271,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
),
);
const providersRef = yield* Ref.make(yield* providerRegistry.getProviders);
const providerStatuses = yield* providerHealth.getStatuses;
const clients = yield* Ref.make(new Set<WebSocket>());
const logger = createLogger("ws");
@@ -622,25 +622,18 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
yield* Stream.runForEach(keybindingsManager.streamChanges, (event) =>
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: event.issues,
providers: providerStatuses,
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Stream.runForEach(serverSettingsManager.streamChanges, (settings) =>
pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: [],
providers: providerStatuses,
settings,
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Stream.runForEach(providerRegistry.streamChanges, (providers) =>
Effect.gen(function* () {
yield* Ref.set(providersRef, providers);
yield* pushBus.publishAll(WS_CHANNELS.serverProvidersUpdated, {
providers,
});
}),
).pipe(Effect.forkIn(subscriptionsScope));
yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
yield* readiness.markOrchestrationSubscriptionsReady;
@@ -904,13 +897,12 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
case WS_METHODS.serverGetConfig: {
const keybindingsConfig = yield* keybindingsManager.loadConfigState;
const settings = yield* serverSettingsManager.getSettings;
const providers = yield* Ref.get(providersRef);
return {
cwd,
keybindingsConfigPath,
keybindings: keybindingsConfig.keybindings,
issues: keybindingsConfig.issues,
providers,
providers: providerStatuses,
availableEditors,
settings,
};
+3
View File
@@ -53,6 +53,7 @@ describe("makeServerPushBus", () => {
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: [{ kind: "keybindings.malformed-config", message: "queued-before-connect" }],
providers: [],
});
const delivered = yield* pushBus.publishClient(
@@ -69,6 +70,7 @@ describe("makeServerPushBus", () => {
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
issues: [],
providers: [],
});
yield* Effect.promise(() => client.waitForSentCount(2));
@@ -93,6 +95,7 @@ describe("makeServerPushBus", () => {
channel: WS_CHANNELS.serverConfigUpdated,
data: {
issues: [],
providers: [],
},
});
}),
+50
View File
@@ -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({});
+2 -5
View File
@@ -31,7 +31,7 @@ import { isMacPlatform } from "../lib/utils";
import { getRouter } from "../router";
import { useStore } from "../store";
import { estimateTimelineMessageHeight } from "./timelineHeight";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import { DEFAULT_CLIENT_SETTINGS } from "~/clientSettings";
const THREAD_ID = "thread-browser-test" as ThreadId;
const UUID_ROUTE_RE = /^\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
@@ -112,13 +112,10 @@ function createBaseServerConfig(): ServerConfig {
providers: [
{
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: NOW_ISO,
models: [],
},
],
availableEditors: [],
+47 -74
View File
@@ -13,7 +13,7 @@ import {
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
type ResolvedKeybindingsConfig,
type ServerProvider,
type ServerProviderStatus,
type ThreadId,
type TurnId,
type EditorId,
@@ -22,7 +22,11 @@ import {
ProviderInteractionMode,
RuntimeMode,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import {
applyClaudePromptEffortPrefix,
getModelCapabilities,
normalizeModelSlug,
} from "@t3tools/shared/model";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useDebouncedValue } from "@tanstack/react-pacer";
@@ -116,13 +120,8 @@ import {
import { SidebarTrigger } from "./ui/sidebar";
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
import { readNativeApi } from "~/nativeApi";
import {
getProviderModelCapabilities,
getProviderModels,
resolveSelectableProvider,
} from "../providerModels";
import { useSettings } from "../hooks/useSettings";
import { resolveAppModelSelection } from "../modelSelection";
import { getCustomModelOptionsByProvider, resolveAppModelSelection } from "../modelSelection";
import { isTerminalFocused } from "../lib/terminalFocus";
import {
type ComposerImageAttachment,
@@ -161,7 +160,7 @@ import {
renderProviderTraitsMenuContent,
renderProviderTraitsPicker,
} from "./chat/composerProviderRegistry";
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
import { ProviderHealthBanner } from "./chat/ProviderHealthBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
buildExpiredTerminalContextToastCopy,
@@ -188,17 +187,16 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PROVIDER_STATUSES: ServerProviderStatus[] = [];
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
function formatOutgoingPrompt(params: {
provider: ProviderKind;
model: string | null;
models: ReadonlyArray<ServerProvider["models"][number]>;
effort: string | null;
text: string;
}): string {
const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
const caps = getModelCapabilities(params.provider, params.model);
if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) {
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
}
@@ -606,32 +604,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
: null;
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDERS;
const unlockedSelectedProvider = resolveSelectableProvider(
providerStatuses,
selectedProviderByThreadId ?? threadProvider ?? "codex",
);
const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider;
const selectedProvider: ProviderKind =
lockedProvider ?? selectedProviderByThreadId ?? threadProvider ?? "codex";
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
threadId,
providers: providerStatuses,
selectedProvider,
threadModelSelection: activeThread?.modelSelection,
projectModelSelection: activeProject?.defaultModelSelection,
settings,
});
const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider);
const composerProviderState = useMemo(
() =>
getComposerProviderState({
provider: selectedProvider,
model: selectedModel,
models: selectedProviderModels,
prompt,
modelOptions: composerModelOptions,
}),
[composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels],
[composerModelOptions, prompt, selectedModel, selectedProvider],
);
const selectedPromptEffort = composerProviderState.promptEffort;
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
@@ -644,6 +634,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
[selectedModel, selectedModelOptionsForDispatch, selectedProvider],
);
const selectedModelForPicker = selectedModel;
const modelOptionsByProvider = useMemo(
() => getCustomModelOptionsByProvider(settings, selectedProvider, selectedModel),
[settings, selectedProvider, selectedModel],
);
const selectedModelForPickerWithCustomFallback = useMemo(() => {
const currentOptions = modelOptionsByProvider[selectedProvider];
return currentOptions.some((option) => option.slug === selectedModelForPicker)
? selectedModelForPicker
: (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);
}, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]);
const searchableModelOptions = useMemo(
() =>
AVAILABLE_PROVIDER_OPTIONS.filter(
(option) => lockedProvider === null || option.value === lockedProvider,
).flatMap((option) =>
modelOptionsByProvider[option.value].map(({ slug, name }) => ({
provider: option.value,
providerLabel: option.label,
slug,
name,
searchSlug: slug.toLowerCase(),
searchName: name.toLowerCase(),
searchProvider: option.label.toLowerCase(),
})),
),
[lockedProvider, modelOptionsByProvider],
);
const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle";
const isPreparingWorktree = sendPhase === "preparing-worktree";
@@ -1006,39 +1023,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
const modelOptionsByProvider = useMemo(
() => ({
codex: providerStatuses.find((provider) => provider.provider === "codex")?.models ?? [],
claudeAgent:
providerStatuses.find((provider) => provider.provider === "claudeAgent")?.models ?? [],
}),
[providerStatuses],
);
const selectedModelForPickerWithCustomFallback = useMemo(() => {
const currentOptions = modelOptionsByProvider[selectedProvider];
return currentOptions.some((option) => option.slug === selectedModelForPicker)
? selectedModelForPicker
: (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);
}, [modelOptionsByProvider, selectedModelForPicker, selectedProvider]);
const searchableModelOptions = useMemo(
() =>
AVAILABLE_PROVIDER_OPTIONS.filter(
(option) => lockedProvider === null || option.value === lockedProvider,
).flatMap((option) =>
modelOptionsByProvider[option.value].map(({ slug, name }) => ({
provider: option.value,
providerLabel: option.label,
slug,
name,
searchSlug: slug.toLowerCase(),
searchName: name.toLowerCase(),
searchProvider: option.label.toLowerCase(),
})),
),
[lockedProvider, modelOptionsByProvider],
);
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const workspaceEntriesQuery = useQuery(
projectSearchEntriesQueryOptions({
cwd: gitCwd,
@@ -1126,6 +1111,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
() => new Set(nonPersistedComposerImageIds),
[nonPersistedComposerImageIds],
);
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
const availableEditors = serverConfigQuery.data?.availableEditors ?? EMPTY_AVAILABLE_EDITORS;
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDER_STATUSES;
const activeProviderStatus = useMemo(
() => providerStatuses.find((status) => status.provider === selectedProvider) ?? null,
[selectedProvider, providerStatuses],
@@ -2466,7 +2454,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const outgoingMessageText = formatOutgoingPrompt({
provider: selectedProvider,
model: selectedModel,
models: selectedProviderModels,
effort: selectedPromptEffort,
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
});
@@ -2888,7 +2875,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const outgoingMessageText = formatOutgoingPrompt({
provider: selectedProvider,
model: selectedModel,
models: selectedProviderModels,
effort: selectedPromptEffort,
text: trimmed,
});
@@ -2979,7 +2965,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
setComposerDraftInteractionMode,
setThreadError,
selectedModel,
@@ -3008,7 +2993,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
const outgoingImplementationPrompt = formatOutgoingPrompt({
provider: selectedProvider,
model: selectedModel,
models: selectedProviderModels,
effort: selectedPromptEffort,
text: implementationPrompt,
});
@@ -3099,7 +3083,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
syncServerReadModel,
selectedModel,
]);
@@ -3111,15 +3094,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
scheduleComposerFocus();
return;
}
const resolvedProvider = resolveSelectableProvider(providerStatuses, provider);
const resolvedModel = resolveAppModelSelection(
resolvedProvider,
settings,
providerStatuses,
model,
);
const resolvedModel = resolveAppModelSelection(provider, settings, model);
const nextModelSelection: ModelSelection = {
provider: resolvedProvider,
provider,
model: resolvedModel,
};
setComposerDraftModelSelection(activeThread.id, nextModelSelection);
@@ -3132,7 +3109,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
scheduleComposerFocus,
setComposerDraftModelSelection,
setStickyComposerModelSelection,
providerStatuses,
settings,
],
);
@@ -3156,7 +3132,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
provider: selectedProvider,
threadId,
model: selectedModel,
models: selectedProviderModels,
modelOptions: composerModelOptions?.[selectedProvider],
prompt,
onPromptChange: setPromptFromTraits,
@@ -3165,7 +3140,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
provider: selectedProvider,
threadId,
model: selectedModel,
models: selectedProviderModels,
modelOptions: composerModelOptions?.[selectedProvider],
prompt,
onPromptChange: setPromptFromTraits,
@@ -3529,7 +3503,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
</header>
{/* Error banner */}
<ProviderStatusBanner status={activeProviderStatus} />
<ProviderHealthBanner status={activeProviderStatus} />
<ThreadErrorBanner
error={activeThread.error}
onDismiss={() => setThreadError(activeThread.id, null)}
@@ -3806,7 +3780,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
provider={selectedProvider}
model={selectedModelForPickerWithCustomFallback}
lockedProvider={lockedProvider}
providers={providerStatuses}
modelOptionsByProvider={modelOptionsByProvider}
{...(composerProviderState.modelPickerIconClassName
? {
@@ -46,13 +46,10 @@ function createBaseServerConfig(): ServerConfig {
providers: [
{
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: NOW_ISO,
models: [],
},
],
availableEditors: [],
@@ -61,8 +58,8 @@ function createBaseServerConfig(): ServerConfig {
defaultThreadEnvMode: "local" as const,
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
providers: {
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
codex: { binaryPath: "", homePath: "", customModels: [] },
claudeAgent: { binaryPath: "", customModels: [] },
},
},
};
+1 -1
View File
@@ -1,5 +1,5 @@
import { memo, useState, useCallback } from "react";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { type TimestampFormat } from "../clientSettings";
import { Badge } from "./ui/badge";
import { Button } from "./ui/button";
import { ScrollArea } from "./ui/scroll-area";
+1 -1
View File
@@ -1,4 +1,4 @@
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../clientSettings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
import {
+1 -4
View File
@@ -38,10 +38,7 @@ import {
} from "@t3tools/contracts";
import { useMutation, useQueries, useQuery, useQueryClient } from "@tanstack/react-query";
import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
import {
type SidebarProjectSortOrder,
type SidebarThreadSortOrder,
} from "@t3tools/contracts/settings";
import { type SidebarProjectSortOrder, type SidebarThreadSortOrder } from "../clientSettings";
import { isElectron } from "../env";
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
@@ -43,70 +43,6 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
document.body.append(host);
const onPromptChange = vi.fn();
const providerOptions = props?.modelSelection?.options;
const models =
provider === "claudeAgent"
? [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
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-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
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: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
},
},
];
const screen = await render(
<CompactComposerControlsMenu
activePlan={false}
@@ -116,7 +52,6 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
traitsMenuContent={
<TraitsMenuContent
provider={provider}
models={models}
threadId={threadId}
model={model}
prompt={props?.prompt ?? ""}
@@ -48,7 +48,7 @@ import {
type ParsedTerminalContextEntry,
} from "~/lib/terminalContext";
import { cn } from "~/lib/utils";
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { type TimestampFormat } from "../../clientSettings";
import { formatTimestamp } from "../../timestampFormat";
import {
buildInlineTerminalContextText,
@@ -1,14 +1,14 @@
import { PROVIDER_DISPLAY_NAMES, type ServerProvider } 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";
export const ProviderStatusBanner = memo(function ProviderStatusBanner({
export const ProviderHealthBanner = memo(function ProviderHealthBanner({
status,
}: {
status: ServerProvider | null;
status: ServerProviderStatus | null;
}) {
if (!status || status.status === "ready" || status.status === "disabled") {
if (!status || status.status === "ready") {
return null;
}
@@ -1,134 +1,37 @@
import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts";
import { type ModelSlug, type ProviderKind } from "@t3tools/contracts";
import { page } from "vitest/browser";
import { afterEach, describe, expect, it, vi } from "vitest";
import { render } from "vitest-browser-react";
import { ProviderModelPicker } from "./ProviderModelPicker";
import { getCustomModelOptionsByProvider } from "../../modelSelection";
import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";
function effort(value: string, isDefault = false) {
return {
value,
label: value,
...(isDefault ? { isDefault: true } : {}),
};
}
const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
{
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
authStatus: "authenticated",
checkedAt: new Date().toISOString(),
models: [
{
slug: "gpt-5-codex",
name: "GPT-5 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
},
},
{
slug: "gpt-5.3-codex",
name: "GPT-5.3 Codex",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: true,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
},
},
],
},
{
provider: "claudeAgent",
enabled: true,
installed: true,
version: "1.0.0",
status: "ready",
authStatus: "authenticated",
checkedAt: new Date().toISOString(),
models: [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
effort("low"),
effort("medium", true),
effort("high"),
effort("max"),
],
supportsFastMode: false,
supportsThinkingToggle: true,
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
effort("low"),
effort("medium", true),
effort("high"),
effort("max"),
],
supportsFastMode: false,
supportsThinkingToggle: true,
promptInjectedEffortLevels: [],
},
},
{
slug: "claude-haiku-4-5",
name: "Claude Haiku 4.5",
isCustom: false,
capabilities: {
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
supportsFastMode: false,
supportsThinkingToggle: true,
promptInjectedEffortLevels: [],
},
},
],
},
];
const MODEL_OPTIONS_BY_PROVIDER = {
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" },
],
codex: [
{ slug: "gpt-5-codex", name: "GPT-5 Codex" },
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
],
} as const satisfies Record<ProviderKind, ReadonlyArray<{ slug: ModelSlug; name: string }>>;
async function mountPicker(props: {
provider: ProviderKind;
model: ModelSlug;
lockedProvider: ProviderKind | null;
providers?: ReadonlyArray<ServerProvider>;
triggerVariant?: "ghost" | "outline";
}) {
const host = document.createElement("div");
document.body.append(host);
const onProviderModelChange = vi.fn();
const providers = props.providers ?? TEST_PROVIDERS;
const modelOptionsByProvider = getCustomModelOptionsByProvider(
DEFAULT_UNIFIED_SETTINGS,
providers,
props.provider,
props.model,
);
const screen = await render(
<ProviderModelPicker
provider={props.provider}
model={props.model}
lockedProvider={props.lockedProvider}
providers={providers}
modelOptionsByProvider={modelOptionsByProvider}
modelOptionsByProvider={MODEL_OPTIONS_BY_PROVIDER}
triggerVariant={props.triggerVariant}
onProviderModelChange={onProviderModelChange}
/>,
@@ -256,40 +159,6 @@ describe("ProviderModelPicker", () => {
}
});
it("shows disabled providers as non-selectable entries", async () => {
const disabledProviders = TEST_PROVIDERS.slice();
const claudeIndex = disabledProviders.findIndex(
(provider) => provider.provider === "claudeAgent",
);
if (claudeIndex >= 0) {
const claudeProvider = disabledProviders[claudeIndex]!;
disabledProviders[claudeIndex] = {
...claudeProvider,
enabled: false,
status: "disabled",
};
}
const mounted = await mountPicker({
provider: "codex",
model: "gpt-5-codex",
lockedProvider: null,
providers: disabledProviders,
});
try {
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Claude");
expect(text).toContain("Disabled");
expect(text).not.toContain("Claude Sonnet 4.6");
});
} finally {
await mounted.cleanup();
}
});
it("accepts outline trigger styling", async () => {
const mounted = await mountPicker({
provider: "codex",
@@ -1,4 +1,4 @@
import { type ModelSlug, type ProviderKind, type ServerProvider } from "@t3tools/contracts";
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";
@@ -20,7 +20,6 @@ import {
} from "../ui/menu";
import { ClaudeAI, CursorIcon, Gemini, Icon, OpenAI, OpenCodeIcon } from "../Icons";
import { cn } from "~/lib/utils";
import { getProviderSnapshot } from "../../providerModels";
function isAvailableProviderOption(option: (typeof PROVIDER_OPTIONS)[number]): option is {
value: ProviderKind;
@@ -54,7 +53,6 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
provider: ProviderKind;
model: ModelSlug;
lockedProvider: ProviderKind | null;
providers?: ReadonlyArray<ServerProvider>;
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
activeProviderIconClassName?: string;
compact?: boolean;
@@ -147,31 +145,6 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
<>
{AVAILABLE_PROVIDER_OPTIONS.map((option) => {
const OptionIcon = PROVIDER_ICON_BY_PROVIDER[option.value];
const liveProvider = props.providers
? getProviderSnapshot(props.providers, option.value)
: undefined;
if (liveProvider && liveProvider.status !== "ready") {
const unavailableLabel = !liveProvider.enabled
? "Disabled"
: !liveProvider.installed
? "Not installed"
: "Unavailable";
return (
<MenuItem key={option.value} disabled>
<OptionIcon
aria-hidden="true"
className={cn(
"size-4 shrink-0 opacity-80",
providerIconClassName(option.value, "text-muted-foreground/85"),
)}
/>
<span>{option.label}</span>
<span className="ms-auto text-[11px] text-muted-foreground/80 uppercase tracking-[0.08em]">
{unavailableLabel}
</span>
</MenuItem>
);
}
return (
<MenuSub key={option.value}>
<MenuSubTrigger>
@@ -7,7 +7,6 @@ import {
DEFAULT_MODEL_BY_PROVIDER,
DEFAULT_SERVER_SETTINGS,
ProjectId,
type ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import { page } from "vitest/browser";
@@ -23,93 +22,11 @@ import {
useComposerThreadDraft,
useEffectiveComposerModelState,
} from "../../composerDraftStore";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import { DEFAULT_CLIENT_SETTINGS } from "~/clientSettings";
// ── Claude TraitsPicker tests ─────────────────────────────────────────
const CLAUDE_THREAD_ID = ThreadId.makeUnsafe("thread-claude-traits");
const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
{
provider: "codex",
enabled: true,
installed: true,
version: "0.1.0",
status: "ready",
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
},
},
],
},
{
provider: "claudeAgent",
enabled: true,
installed: true,
version: "0.1.0",
status: "ready",
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
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",
isCustom: false,
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",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
promptInjectedEffortLevels: [],
},
},
],
},
];
function ClaudeTraitsPickerHarness(props: {
model: string;
@@ -120,7 +37,6 @@ function ClaudeTraitsPickerHarness(props: {
const setPrompt = useComposerDraftStore((store) => store.setPrompt);
const { modelOptions, selectedModel } = useEffectiveComposerModelState({
threadId: CLAUDE_THREAD_ID,
providers: TEST_PROVIDERS,
selectedProvider: "claudeAgent",
threadModelSelection: props.fallbackModelSelection,
projectModelSelection: null,
@@ -139,7 +55,6 @@ function ClaudeTraitsPickerHarness(props: {
return (
<TraitsPicker
provider="claudeAgent"
models={TEST_PROVIDERS[1]!.models}
threadId={CLAUDE_THREAD_ID}
model={selectedModel ?? props.model}
prompt={prompt}
@@ -383,7 +298,6 @@ async function mountCodexPicker(props: { model?: string; options?: CodexModelOpt
const screen = await render(
<TraitsPicker
provider="codex"
models={TEST_PROVIDERS[0]!.models}
threadId={threadId}
model={props.model ?? DEFAULT_MODEL_BY_PROVIDER.codex}
prompt=""
@@ -450,10 +364,10 @@ describe("TraitsPicker (Codex)", () => {
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Extra High");
expect(text).toContain("Low");
expect(text).toContain("Medium");
expect(text).toContain("High");
expect(text).not.toContain("Low");
expect(text).not.toContain("Medium");
expect(text).toContain("Extra High");
});
});
+4 -10
View File
@@ -3,11 +3,11 @@ import {
type CodexModelOptions,
type ProviderKind,
type ProviderModelOptions,
type ServerProviderModel,
type ThreadId,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
getModelCapabilities,
isClaudeUltrathinkPrompt,
trimOrNull,
getDefaultEffort,
@@ -27,7 +27,6 @@ import {
MenuTrigger,
} from "../ui/menu";
import { useComposerDraftStore } from "../../composerDraftStore";
import { getProviderModelCapabilities } from "../../providerModels";
import { cn } from "~/lib/utils";
type ProviderOptions = ProviderModelOptions[ProviderKind];
@@ -66,13 +65,12 @@ function buildNextOptions(
function getSelectedTraits(
provider: ProviderKind,
models: ReadonlyArray<ServerProviderModel>,
model: string | null | undefined,
prompt: string,
modelOptions: ProviderOptions | null | undefined,
allowPromptInjectedEffort: boolean,
) {
const caps = getProviderModelCapabilities(models, model, provider);
const caps = getModelCapabilities(provider, model);
const effortLevels = allowPromptInjectedEffort
? caps.reasoningEffortLevels
: caps.reasoningEffortLevels.filter(
@@ -122,7 +120,6 @@ function getSelectedTraits(
export interface TraitsMenuContentProps {
provider: ProviderKind;
models: ReadonlyArray<ServerProviderModel>;
model: string | null | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
@@ -134,7 +131,6 @@ export interface TraitsMenuContentProps {
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
provider,
models,
model,
prompt,
onPromptChange,
@@ -160,7 +156,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
thinkingEnabled,
fastModeEnabled,
ultrathinkPromptControlled,
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
} = getSelectedTraits(provider, model, prompt, modelOptions, allowPromptInjectedEffort);
const defaultEffort = getDefaultEffort(caps);
const handleEffortChange = useCallback(
@@ -264,7 +260,6 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
export const TraitsPicker = memo(function TraitsPicker({
provider,
models,
model,
prompt,
onPromptChange,
@@ -282,7 +277,7 @@ export const TraitsPicker = memo(function TraitsPicker({
thinkingEnabled,
fastModeEnabled,
ultrathinkPromptControlled,
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
} = getSelectedTraits(provider, model, prompt, modelOptions, allowPromptInjectedEffort);
const effortLabel = effort
? (effortLevels.find((l) => l.value === effort)?.label ?? effort)
@@ -338,7 +333,6 @@ export const TraitsPicker = memo(function TraitsPicker({
<MenuPopup align="start">
<TraitsMenuContent
provider={provider}
models={models}
model={model}
prompt={prompt}
onPromptChange={onPromptChange}
@@ -1,78 +1,11 @@
import { describe, expect, it } from "vitest";
import type { ServerProviderModel } from "@t3tools/contracts";
import { getComposerProviderState } from "./composerProviderRegistry";
const CODEX_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
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: [],
},
},
];
const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
{
slug: "claude-opus-4-6",
name: "Claude Opus 4.6",
isCustom: false,
capabilities: {
reasoningEffortLevels: [
{ 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",
isCustom: false,
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",
isCustom: false,
capabilities: {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: true,
promptInjectedEffortLevels: [],
},
},
];
describe("getComposerProviderState", () => {
it("returns codex defaults when no codex draft options exist", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: undefined,
});
@@ -88,7 +21,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: {
codex: {
@@ -112,7 +44,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: {
codex: {
@@ -134,7 +65,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "codex",
model: "gpt-5.4",
models: CODEX_MODELS,
prompt: "",
modelOptions: {
codex: {
@@ -155,7 +85,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: undefined,
});
@@ -171,7 +100,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-sonnet-4-6",
models: CLAUDE_MODELS,
prompt: "Ultrathink:\nInvestigate this failure",
modelOptions: {
claudeAgent: {
@@ -196,7 +124,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-haiku-4-5",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
@@ -219,7 +146,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
@@ -241,7 +167,6 @@ describe("getComposerProviderState", () => {
const state = getComposerProviderState({
provider: "claudeAgent",
model: "claude-opus-4-6",
models: CLAUDE_MODELS,
prompt: "",
modelOptions: {
claudeAgent: {
@@ -2,27 +2,23 @@ import {
type ModelSlug,
type ProviderKind,
type ProviderModelOptions,
type ServerProviderModel,
type ThreadId,
} from "@t3tools/contracts";
import {
getModelCapabilities,
isClaudeUltrathinkPrompt,
normalizeClaudeModelOptions,
normalizeCodexModelOptions,
trimOrNull,
getDefaultEffort,
hasEffortLevel,
} from "@t3tools/shared/model";
import type { ReactNode } from "react";
import {
getProviderModelCapabilities,
normalizeClaudeModelOptionsWithCapabilities,
normalizeCodexModelOptionsWithCapabilities,
} from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
export type ComposerProviderStateInput = {
provider: ProviderKind;
model: ModelSlug;
models: ReadonlyArray<ServerProviderModel>;
prompt: string;
modelOptions: ProviderModelOptions | null | undefined;
};
@@ -41,7 +37,6 @@ type ProviderRegistryEntry = {
renderTraitsMenuContent: (input: {
threadId: ThreadId;
model: ModelSlug;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
@@ -49,7 +44,6 @@ type ProviderRegistryEntry = {
renderTraitsPicker: (input: {
threadId: ThreadId;
model: ModelSlug;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
@@ -59,8 +53,8 @@ type ProviderRegistryEntry = {
function getProviderStateFromCapabilities(
input: ComposerProviderStateInput,
): ComposerProviderState {
const { provider, model, models, prompt, modelOptions } = input;
const caps = getProviderModelCapabilities(models, model, provider);
const { provider, model, prompt, modelOptions } = input;
const caps = getModelCapabilities(provider, model);
const providerOptions = modelOptions?.[provider];
// Resolve effort
@@ -87,8 +81,8 @@ function getProviderStateFromCapabilities(
// Normalize options for dispatch
const normalizedOptions =
provider === "codex"
? normalizeCodexModelOptionsWithCapabilities(caps, providerOptions)
: normalizeClaudeModelOptionsWithCapabilities(caps, providerOptions);
? normalizeCodexModelOptions(model, providerOptions)
: normalizeClaudeModelOptions(model, providerOptions);
// Ultrathink styling (driven by capabilities data, not provider identity)
const ultrathinkActive =
@@ -109,17 +103,9 @@ function getProviderStateFromCapabilities(
const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
codex: {
getState: (input) => getProviderStateFromCapabilities(input),
renderTraitsMenuContent: ({
threadId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) => (
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
<TraitsMenuContent
provider="codex"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
@@ -127,10 +113,9 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
onPromptChange={onPromptChange}
/>
),
renderTraitsPicker: ({ threadId, model, models, modelOptions, prompt, onPromptChange }) => (
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
<TraitsPicker
provider="codex"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
@@ -141,17 +126,9 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
},
claudeAgent: {
getState: (input) => getProviderStateFromCapabilities(input),
renderTraitsMenuContent: ({
threadId,
model,
models,
modelOptions,
prompt,
onPromptChange,
}) => (
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
<TraitsMenuContent
provider="claudeAgent"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
@@ -159,10 +136,9 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
onPromptChange={onPromptChange}
/>
),
renderTraitsPicker: ({ threadId, model, models, modelOptions, prompt, onPromptChange }) => (
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
<TraitsPicker
provider="claudeAgent"
models={models}
threadId={threadId}
model={model}
modelOptions={modelOptions}
@@ -181,7 +157,6 @@ export function renderProviderTraitsMenuContent(input: {
provider: ProviderKind;
threadId: ThreadId;
model: ModelSlug;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
@@ -189,7 +164,6 @@ export function renderProviderTraitsMenuContent(input: {
return composerProviderRegistry[input.provider].renderTraitsMenuContent({
threadId: input.threadId,
model: input.model,
models: input.models,
modelOptions: input.modelOptions,
prompt: input.prompt,
onPromptChange: input.onPromptChange,
@@ -200,7 +174,6 @@ export function renderProviderTraitsPicker(input: {
provider: ProviderKind;
threadId: ThreadId;
model: ModelSlug;
models: ReadonlyArray<ServerProviderModel>;
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
prompt: string;
onPromptChange: (prompt: string) => void;
@@ -208,7 +181,6 @@ export function renderProviderTraitsPicker(input: {
return composerProviderRegistry[input.provider].renderTraitsPicker({
threadId: input.threadId,
model: input.model,
models: input.models,
modelOptions: input.modelOptions,
prompt: input.prompt,
onPromptChange: input.onPromptChange,
+13 -19
View File
@@ -9,13 +9,16 @@ import {
ProviderKind,
ProviderModelOptions,
RuntimeMode,
type ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import * as Schema from "effect/Schema";
import * as Equal from "effect/Equal";
import { DeepMutable } from "effect/Types";
import { getDefaultModel, 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";
@@ -28,8 +31,7 @@ import {
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { createDebouncedStorage, createMemoryStorage } from "./lib/storage";
import { getDefaultServerModel } from "./providerModels";
import { UnifiedSettings } from "@t3tools/contracts/settings";
import { UnifiedSettings } from "./hooks/useSettings";
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
const COMPOSER_DRAFT_STORAGE_VERSION = 3;
@@ -612,25 +614,20 @@ export function deriveEffectiveComposerModelState(input: {
| Pick<ComposerThreadDraftState, "modelSelectionByProvider" | "activeProvider">
| null
| undefined;
providers: ReadonlyArray<ServerProvider>;
selectedProvider: ProviderKind;
threadModelSelection: ModelSelection | null | undefined;
projectModelSelection: ModelSelection | null | undefined;
settings: UnifiedSettings;
}): EffectiveComposerModelState {
const baseModel =
normalizeModelSlug(
input.threadModelSelection?.model ?? input.projectModelSelection?.model,
input.selectedProvider,
) ?? getDefaultServerModel(input.providers, input.selectedProvider);
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.settings,
input.providers,
activeSelection.model,
)
? resolveAppModelSelection(input.selectedProvider, input.settings, activeSelection.model)
: baseModel;
const modelOptions =
modelSelectionByProviderToOptions(input.draft?.modelSelectionByProvider) ??
@@ -2157,7 +2154,6 @@ export function useComposerThreadDraft(threadId: ThreadId): ComposerThreadDraftS
export function useEffectiveComposerModelState(input: {
threadId: ThreadId;
providers: ReadonlyArray<ServerProvider>;
selectedProvider: ProviderKind;
threadModelSelection: ModelSelection | null | undefined;
projectModelSelection: ModelSelection | null | undefined;
@@ -2169,7 +2165,6 @@ export function useEffectiveComposerModelState(input: {
() =>
deriveEffectiveComposerModelState({
draft,
providers: input.providers,
selectedProvider: input.selectedProvider,
threadModelSelection: input.threadModelSelection,
projectModelSelection: input.projectModelSelection,
@@ -2177,7 +2172,6 @@ export function useEffectiveComposerModelState(input: {
}),
[
draft,
input.providers,
input.settings,
input.projectModelSelection,
input.selectedProvider,
+35 -64
View File
@@ -19,26 +19,23 @@ import {
ThreadEnvMode,
} from "@t3tools/contracts";
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
import {
type ClientSettings,
ClientSettingsSchema,
DEFAULT_CLIENT_SETTINGS,
DEFAULT_UNIFIED_SETTINGS,
SidebarProjectSortOrder,
SidebarThreadSortOrder,
TimestampFormat,
UnifiedSettings,
} from "@t3tools/contracts/settings";
import { serverConfigQueryOptions, serverQueryKeys } from "~/lib/serverReactQuery";
import { ensureNativeApi } from "~/nativeApi";
import { useLocalStorage } from "./useLocalStorage";
import { normalizeCustomModelSlugs } from "~/modelSelection";
import {
ClientSettingsSchema,
type ClientSettings,
DEFAULT_CLIENT_SETTINGS,
CLIENT_SETTINGS_STORAGE_KEY,
} from "~/clientSettings";
import { Predicate, Schema, Struct } from "effect";
import { DeepMutable } from "effect/Types";
import { deepMerge } from "@t3tools/shared/Struct";
const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
// ── Unified type ─────────────────────────────────────────────────────
export type UnifiedSettings = ServerSettings & ClientSettings;
// ── Key sets for routing patches ─────────────────────────────────────
@@ -130,17 +127,24 @@ export function useUpdateSettings() {
);
const resetSettings = useCallback(() => {
updateSettings(DEFAULT_UNIFIED_SETTINGS);
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";
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
const patch: DeepMutable<ServerSettingsPatch> = {};
@@ -173,7 +177,6 @@ export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<s
patch.providers.codex ??= {};
patch.providers.codex.customModels = normalizeCustomModelSlugs(
legacySettings.customCodexModels,
new Set<string>(),
"codex",
);
}
@@ -189,7 +192,6 @@ export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<s
patch.providers.claudeAgent ??= {};
patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
legacySettings.customClaudeModels,
new Set<string>(),
"claudeAgent",
);
}
@@ -197,70 +199,39 @@ export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<s
return patch;
}
export function buildLegacyClientSettingsMigrationPatch(
legacySettings: Record<string, unknown>,
): Partial<DeepMutable<ClientSettings>> {
const patch: Partial<DeepMutable<ClientSettings>> = {};
if (Predicate.isBoolean(legacySettings.confirmThreadDelete)) {
patch.confirmThreadDelete = legacySettings.confirmThreadDelete;
}
if (Predicate.isBoolean(legacySettings.diffWordWrap)) {
patch.diffWordWrap = legacySettings.diffWordWrap;
}
if (Schema.is(SidebarProjectSortOrder)(legacySettings.sidebarProjectSortOrder)) {
patch.sidebarProjectSortOrder = legacySettings.sidebarProjectSortOrder;
}
if (Schema.is(SidebarThreadSortOrder)(legacySettings.sidebarThreadSortOrder)) {
patch.sidebarThreadSortOrder = legacySettings.sidebarThreadSortOrder;
}
if (Schema.is(TimestampFormat)(legacySettings.timestampFormat)) {
patch.timestampFormat = legacySettings.timestampFormat;
}
return patch;
}
/**
* Call once on app startup.
* If the legacy localStorage key exists, migrate its values to the new server
* and client storage formats, then remove the legacy key so this only runs once.
* 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) return;
if (!raw) {
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
return;
}
try {
const old = JSON.parse(raw);
if (!Predicate.isObject(old)) return;
// Migrate server-relevant keys via RPC
const api = ensureNativeApi();
const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
if (Object.keys(serverPatch).length > 0) {
const api = ensureNativeApi();
void api.server.updateSettings(serverPatch);
if (Object.keys(serverPatch).length === 0) {
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
return;
}
// Migrate client-only keys to the new localStorage key
const clientPatch = buildLegacyClientSettingsMigrationPatch(old);
if (Object.keys(clientPatch).length > 0) {
const existing = localStorage.getItem(CLIENT_SETTINGS_STORAGE_KEY);
const current = existing ? (JSON.parse(existing) as Record<string, unknown>) : {};
localStorage.setItem(
CLIENT_SETTINGS_STORAGE_KEY,
JSON.stringify({ ...current, ...clientPatch }),
);
}
void api.server.updateSettings(serverPatch);
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
} catch (error) {
console.error("[MIGRATION] Error migrating local settings:", error);
console.error("[MIGRATION] Error migrating local settings to server:", error);
} finally {
// Remove the legacy key regardless to keep migration one-shot behavior.
localStorage.removeItem(OLD_SETTINGS_KEY);
// Mark as migrated no matter what to avoid retrying
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
}
}
+27 -46
View File
@@ -2,16 +2,15 @@ import {
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
type ModelSelection,
type ProviderKind,
type ServerProvider,
} from "@t3tools/contracts";
import { normalizeModelSlug, resolveSelectableModel } from "@t3tools/shared/model";
import { getComposerProviderState } from "./components/chat/composerProviderRegistry";
import { UnifiedSettings } from "@t3tools/contracts/settings";
import {
getDefaultServerModel,
getProviderModels,
resolveSelectableProvider,
} from "./providerModels";
getDefaultModel,
getModelOptions,
normalizeModelSlug,
resolveSelectableModel,
} from "@t3tools/shared/model";
import { getComposerProviderState } from "./components/chat/composerProviderRegistry";
import { UnifiedSettings } from "./hooks/useSettings";
const MAX_CUSTOM_MODEL_COUNT = 32;
export const MAX_CUSTOM_MODEL_LENGTH = 256;
@@ -47,15 +46,20 @@ const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConf
},
};
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>,
builtInModelSlugs: ReadonlySet<string>,
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);
@@ -80,27 +84,19 @@ export function normalizeCustomModelSlugs(
export function getAppModelOptions(
settings: UnifiedSettings,
providers: ReadonlyArray<ServerProvider>,
provider: ProviderKind,
selectedModel?: string | null,
): AppModelOption[] {
const options: AppModelOption[] = getProviderModels(providers, provider).map(
({ slug, name, isCustom }) => ({
slug,
name,
isCustom,
}),
);
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();
const builtInModelSlugs = new Set(
getProviderModels(providers, provider)
.filter((model) => !model.isCustom)
.map((model) => model.slug),
);
const customModels = settings.providers[provider].customModels;
for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, provider)) {
for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
if (seen.has(slug)) {
continue;
}
@@ -135,65 +131,50 @@ export function getAppModelOptions(
export function resolveAppModelSelection(
provider: ProviderKind,
settings: UnifiedSettings,
providers: ReadonlyArray<ServerProvider>,
selectedModel: string | null | undefined,
): string {
const resolvedProvider = resolveSelectableProvider(providers, provider);
const options = getAppModelOptions(settings, providers, resolvedProvider, selectedModel);
return (
resolveSelectableModel(resolvedProvider, selectedModel, options) ??
getDefaultServerModel(providers, resolvedProvider)
);
const options = getAppModelOptions(settings, provider, selectedModel);
return resolveSelectableModel(provider, selectedModel, options) ?? getDefaultModel(provider);
}
export function getCustomModelOptionsByProvider(
settings: UnifiedSettings,
providers: ReadonlyArray<ServerProvider>,
selectedProvider?: ProviderKind | null,
selectedModel?: string | null,
): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
return {
codex: getAppModelOptions(
settings,
providers,
"codex",
selectedProvider === "codex" ? selectedModel : undefined,
),
claudeAgent: getAppModelOptions(
settings,
providers,
"claudeAgent",
selectedProvider === "claudeAgent" ? selectedModel : undefined,
),
};
}
export function resolveAppModelSelectionState(
settings: UnifiedSettings,
providers: ReadonlyArray<ServerProvider>,
): ModelSelection {
export function resolveAppModelSelectionState(settings: UnifiedSettings): ModelSelection {
const selection = settings.textGenerationModelSelection ?? {
provider: "codex" as const,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
};
const provider = resolveSelectableProvider(providers, selection.provider);
// When the provider changed due to fallback (e.g. selected provider was disabled),
// don't carry over the old provider's model — use the fallback provider's default.
const selectedModel = provider === selection.provider ? selection.model : null;
const model = resolveAppModelSelection(provider, settings, providers, selectedModel);
const model = resolveAppModelSelection(selection.provider, settings, selection.model);
const { modelOptionsForDispatch } = getComposerProviderState({
provider,
provider: selection.provider,
model,
models: getProviderModels(providers, provider),
prompt: "",
modelOptions: {
[provider]: provider === selection.provider ? selection.options : undefined,
[selection.provider]: selection.options,
},
});
return {
provider,
provider: selection.provider,
model,
...(modelOptionsForDispatch ? { options: modelOptionsForDispatch } : {}),
};
-116
View File
@@ -1,116 +0,0 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
type ClaudeModelOptions,
type CodexModelOptions,
type ModelCapabilities,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import {
getDefaultEffort,
hasEffortLevel,
normalizeModelSlug,
trimOrNull,
} from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
};
export function getProviderModels(
providers: ReadonlyArray<ServerProvider>,
provider: ProviderKind,
): ReadonlyArray<ServerProviderModel> {
return providers.find((candidate) => candidate.provider === provider)?.models ?? [];
}
export function getProviderSnapshot(
providers: ReadonlyArray<ServerProvider>,
provider: ProviderKind,
): ServerProvider | undefined {
return providers.find((candidate) => candidate.provider === provider);
}
export function isProviderEnabled(
providers: ReadonlyArray<ServerProvider>,
provider: ProviderKind,
): boolean {
return getProviderSnapshot(providers, provider)?.enabled ?? true;
}
export function resolveSelectableProvider(
providers: ReadonlyArray<ServerProvider>,
provider: ProviderKind | null | undefined,
): ProviderKind {
const requested = provider ?? "codex";
if (isProviderEnabled(providers, requested)) {
return requested;
}
return providers.find((candidate) => candidate.enabled)?.provider ?? requested;
}
export function getProviderModelCapabilities(
models: ReadonlyArray<ServerProviderModel>,
model: string | null | undefined,
provider: ProviderKind,
): ModelCapabilities {
const slug = normalizeModelSlug(model, provider);
return models.find((candidate) => candidate.slug === slug)?.capabilities ?? EMPTY_CAPABILITIES;
}
export function getDefaultServerModel(
providers: ReadonlyArray<ServerProvider>,
provider: ProviderKind,
): string {
const models = getProviderModels(providers, provider);
return (
models.find((model) => !model.isCustom)?.slug ??
models[0]?.slug ??
DEFAULT_MODEL_BY_PROVIDER[provider]
);
}
export function normalizeCodexModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
const defaultReasoningEffort = getDefaultEffort(caps);
const reasoningEffort = trimOrNull(modelOptions?.reasoningEffort) ?? defaultReasoningEffort;
const fastModeEnabled = modelOptions?.fastMode === true;
const nextOptions: CodexModelOptions = {
...(reasoningEffort && reasoningEffort !== defaultReasoningEffort
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
: {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeClaudeModelOptionsWithCapabilities(
caps: ModelCapabilities,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const defaultReasoningEffort = getDefaultEffort(caps);
const resolvedEffort = trimOrNull(modelOptions?.effort);
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
const effort =
resolvedEffort &&
!isPromptInjected &&
hasEffortLevel(caps, resolvedEffort) &&
resolvedEffort !== defaultReasoningEffort
? resolvedEffort
: undefined;
const thinking =
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 } : {}),
...(fastMode ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
+1 -5
View File
@@ -20,7 +20,7 @@ import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDra
import { useStore } from "../store";
import { useTerminalStateStore } from "../terminalStateStore";
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
import { providerQueryKeys } from "../lib/providerReactQuery";
import { projectQueryKeys } from "../lib/projectReactQuery";
@@ -309,9 +309,6 @@ function EventRouter() {
},
});
});
const unsubProvidersUpdated = onServerProvidersUpdated(() => {
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
});
subscribed = true;
return () => {
disposed = true;
@@ -321,7 +318,6 @@ function EventRouter() {
unsubTerminalEvent();
unsubWelcome();
unsubServerConfigUpdated();
unsubProvidersUpdated();
};
}, [
navigate,
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1,4 +1,4 @@
import { type TimestampFormat } from "@t3tools/contracts/settings";
import { type TimestampFormat } from "./clientSettings";
export function getTimestampFormatOptions(
timestampFormat: TimestampFormat,
+7 -27
View File
@@ -13,7 +13,7 @@ import {
WS_CHANNELS,
WS_METHODS,
type WsPush,
type ServerProvider,
type ServerProviderStatus,
} from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -92,16 +92,13 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
return testGlobal.window;
}
const defaultProviders: ReadonlyArray<ServerProvider> = [
const defaultProviders: ReadonlyArray<ServerProviderStatus> = [
{
provider: "codex",
enabled: true,
installed: true,
version: "0.116.0",
status: "ready",
available: true,
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
];
@@ -200,6 +197,7 @@ describe("wsNativeApi", () => {
message: "Entry at index 1 is invalid.",
},
],
providers: defaultProviders,
} as const;
emitPush(WS_CHANNELS.serverConfigUpdated, payload);
@@ -221,36 +219,18 @@ describe("wsNativeApi", () => {
emitPush(WS_CHANNELS.serverConfigUpdated, {
issues: [{ kind: "keybindings.malformed-config", message: "bad json" }],
providers: defaultProviders,
});
emitPush(WS_CHANNELS.serverConfigUpdated, {
issues: [],
providers: defaultProviders,
});
expect(listener).toHaveBeenCalledTimes(2);
expect(listener).toHaveBeenLastCalledWith({
issues: [],
});
});
it("delivers and caches valid server.providersUpdated payloads", async () => {
const { createWsNativeApi, onServerProvidersUpdated } = await import("./wsNativeApi");
createWsNativeApi();
const listener = vi.fn();
onServerProvidersUpdated(listener);
const payload = {
providers: defaultProviders,
} as const;
emitPush(WS_CHANNELS.serverProvidersUpdated, payload);
expect(listener).toHaveBeenCalledTimes(1);
expect(listener).toHaveBeenCalledWith(payload);
const lateListener = vi.fn();
onServerProvidersUpdated(lateListener);
expect(lateListener).toHaveBeenCalledTimes(1);
expect(lateListener).toHaveBeenCalledWith(payload);
});
});
it("forwards valid terminal and orchestration events", async () => {
-32
View File
@@ -5,7 +5,6 @@ import {
type ContextMenuItem,
type NativeApi,
ServerConfigUpdatedPayload,
ServerProviderUpdatedPayload,
WS_CHANNELS,
WS_METHODS,
type WsWelcomePayload,
@@ -17,7 +16,6 @@ import { WsTransport } from "./wsTransport";
let instance: { api: NativeApi; transport: WsTransport } | null = null;
const welcomeListeners = new Set<(payload: WsWelcomePayload) => void>();
const serverConfigUpdatedListeners = new Set<(payload: ServerConfigUpdatedPayload) => void>();
const providersUpdatedListeners = new Set<(payload: ServerProviderUpdatedPayload) => void>();
const gitActionProgressListeners = new Set<(payload: GitActionProgressEvent) => void>();
/**
@@ -66,26 +64,6 @@ export function onServerConfigUpdated(
};
}
export function onServerProvidersUpdated(
listener: (payload: ServerProviderUpdatedPayload) => void,
): () => void {
providersUpdatedListeners.add(listener);
const latestProviders =
instance?.transport.getLatestPush(WS_CHANNELS.serverProvidersUpdated)?.data ?? null;
if (latestProviders) {
try {
listener(latestProviders);
} catch {
// Swallow listener errors
}
}
return () => {
providersUpdatedListeners.delete(listener);
};
}
export function createWsNativeApi(): NativeApi {
if (instance) return instance.api;
@@ -111,16 +89,6 @@ export function createWsNativeApi(): NativeApi {
}
}
});
transport.subscribe(WS_CHANNELS.serverProvidersUpdated, (message) => {
const payload = message.data;
for (const listener of providersUpdatedListeners) {
try {
listener(payload);
} catch {
// Swallow listener errors
}
}
});
transport.subscribe(WS_CHANNELS.gitActionProgress, (message) => {
const payload = message.data;
for (const listener of gitActionProgressListeners) {
+4 -4
View File
@@ -98,7 +98,7 @@ describe("WsTransport", () => {
type: "push",
sequence: 1,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [] },
data: { issues: [], providers: [] },
}),
);
@@ -107,7 +107,7 @@ describe("WsTransport", () => {
type: "push",
sequence: 1,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [] },
data: { issues: [], providers: [] },
});
transport.dispose();
@@ -160,7 +160,7 @@ describe("WsTransport", () => {
type: "push",
sequence: 3,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [] },
data: { issues: [], providers: [] },
}),
);
@@ -169,7 +169,7 @@ describe("WsTransport", () => {
type: "push",
sequence: 3,
channel: WS_CHANNELS.serverConfigUpdated,
data: { issues: [] },
data: { issues: [], providers: [] },
});
expect(warnSpy).toHaveBeenCalledTimes(2);
expect(warnSpy).toHaveBeenNthCalledWith(
-5
View File
@@ -10,11 +10,6 @@
"module": "./dist/index.mjs",
"types": "./src/index.ts",
"exports": {
"./settings": {
"types": "./src/settings.ts",
"import": "./src/settings.ts",
"require": "./src/settings.ts"
},
".": {
"types": "./src/index.ts",
"import": "./src/index.ts",
-1
View File
@@ -7,7 +7,6 @@ export * from "./model";
export * from "./ws";
export * from "./keybindings";
export * from "./server";
export * from "./settings";
export * from "./git";
export * from "./orchestration";
export * from "./editor";
+2 -3
View File
@@ -25,7 +25,7 @@ import type {
ProjectWriteFileInput,
ProjectWriteFileResult,
} from "./project";
import type { ServerConfig, ServerUpsertKeybindingResult } from "./server";
import type { ServerConfig, ServerSettings, ServerSettingsPatch } from "./server";
import type {
TerminalClearInput,
TerminalCloseInput,
@@ -36,7 +36,7 @@ import type {
TerminalSessionSnapshot,
TerminalWriteInput,
} from "./terminal";
import type { ServerUpsertKeybindingInput } from "./server";
import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
import type {
ClientOrchestrationCommand,
OrchestrationGetFullThreadDiffInput,
@@ -47,7 +47,6 @@ import type {
OrchestrationReadModel,
} from "./orchestration";
import { EditorId } from "./editor";
import { ServerSettings, ServerSettingsPatch } from "./settings";
export interface ContextMenuItem<T extends string = string> {
id: T;
+173 -15
View File
@@ -1,5 +1,4 @@
import { Schema } from "effect";
import { TrimmedNonEmptyString } from "./baseSchemas";
import type { ProviderKind } from "./orchestration";
export const CODEX_REASONING_EFFORT_OPTIONS = ["xhigh", "high", "medium", "low"] as const;
@@ -27,28 +26,178 @@ export const ProviderModelOptions = Schema.Struct({
});
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
export const EffortOption = Schema.Struct({
value: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
isDefault: Schema.optional(Schema.Boolean),
});
export type EffortOption = typeof EffortOption.Type;
export type EffortOption = {
readonly value: string;
readonly label: string;
readonly isDefault?: true;
};
export const ModelCapabilities = Schema.Struct({
reasoningEffortLevels: Schema.Array(EffortOption),
supportsFastMode: Schema.Boolean,
supportsThinkingToggle: Schema.Boolean,
promptInjectedEffortLevels: Schema.Array(TrimmedNonEmptyString),
});
export type ModelCapabilities = typeof ModelCapabilities.Type;
export type ModelCapabilities = {
readonly reasoningEffortLevels: readonly EffortOption[];
readonly supportsFastMode: boolean;
readonly supportsThinkingToggle: boolean;
readonly promptInjectedEffortLevels: readonly string[];
};
export type ModelSlug = 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",
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",
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 ModelDefinition[]>;
export type ModelOptionsByProvider = typeof MODEL_OPTIONS_BY_PROVIDER;
type BuiltInModelSlug = (typeof MODEL_OPTIONS_BY_PROVIDER)[ProviderKind][number]["slug"];
export type ModelSlug = BuiltInModelSlug | (string & {});
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, ModelSlug> = {
codex: "gpt-5.4",
claudeAgent: "claude-sonnet-4-6",
};
// 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;
/** Per-provider text generation model defaults. */
@@ -81,6 +230,15 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string,
},
};
// ── Model capabilities index ──────────────────────────────────────────
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> = {
+18
View File
@@ -61,6 +61,23 @@ export type ClaudeModelSelection = typeof ClaudeModelSelection.Type;
export const ModelSelection = Schema.Union([CodexModelSelection, ClaudeModelSelection]);
export type ModelSelection = typeof ModelSelection.Type;
export const CodexProviderStartOptions = Schema.Struct({
binaryPath: Schema.optional(TrimmedNonEmptyString),
homePath: Schema.optional(TrimmedNonEmptyString),
});
export const ClaudeProviderStartOptions = Schema.Struct({
binaryPath: Schema.optional(TrimmedNonEmptyString),
permissionMode: Schema.optional(TrimmedNonEmptyString),
maxThinkingTokens: Schema.optional(NonNegativeInt),
});
export const ProviderStartOptions = Schema.Struct({
codex: Schema.optional(CodexProviderStartOptions),
claudeAgent: Schema.optional(ClaudeProviderStartOptions),
});
export type ProviderStartOptions = typeof ProviderStartOptions.Type;
export const RuntimeMode = Schema.Literals(["approval-required", "full-access"]);
export type RuntimeMode = typeof RuntimeMode.Type;
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
@@ -681,6 +698,7 @@ export const ThreadTurnStartRequestedPayload = Schema.Struct({
threadId: ThreadId,
messageId: MessageId,
modelSelection: Schema.optional(ModelSelection),
providerOptions: Schema.optional(ProviderStartOptions),
assistantDeliveryMode: Schema.optional(AssistantDeliveryMode),
runtimeMode: RuntimeMode.pipe(Schema.withDecodingDefault(() => DEFAULT_RUNTIME_MODE)),
interactionMode: ProviderInteractionMode.pipe(
+18
View File
@@ -21,6 +21,12 @@ describe("ProviderSessionStartInput", () => {
},
},
runtimeMode: "full-access",
providerOptions: {
codex: {
binaryPath: "/usr/local/bin/codex",
homePath: "/tmp/.codex",
},
},
});
expect(parsed.runtimeMode).toBe("full-access");
expect(parsed.modelSelection?.provider).toBe("codex");
@@ -30,6 +36,8 @@ describe("ProviderSessionStartInput", () => {
}
expect(parsed.modelSelection.options?.reasoningEffort).toBe("high");
expect(parsed.modelSelection.options?.fastMode).toBe(true);
expect(parsed.providerOptions?.codex?.binaryPath).toBe("/usr/local/bin/codex");
expect(parsed.providerOptions?.codex?.homePath).toBe("/tmp/.codex");
});
it("rejects payloads without runtime mode", () => {
@@ -55,6 +63,13 @@ describe("ProviderSessionStartInput", () => {
fastMode: true,
},
},
providerOptions: {
claudeAgent: {
binaryPath: "/usr/local/bin/claude",
permissionMode: "plan",
maxThinkingTokens: 12_000,
},
},
runtimeMode: "full-access",
});
expect(parsed.provider).toBe("claudeAgent");
@@ -66,6 +81,9 @@ describe("ProviderSessionStartInput", () => {
expect(parsed.modelSelection.options?.thinking).toBe(true);
expect(parsed.modelSelection.options?.effort).toBe("max");
expect(parsed.modelSelection.options?.fastMode).toBe(true);
expect(parsed.providerOptions?.claudeAgent?.binaryPath).toBe("/usr/local/bin/claude");
expect(parsed.providerOptions?.claudeAgent?.permissionMode).toBe("plan");
expect(parsed.providerOptions?.claudeAgent?.maxThinkingTokens).toBe(12_000);
expect(parsed.runtimeMode).toBe("full-access");
});
});
+2
View File
@@ -19,6 +19,7 @@ import {
ProviderKind,
ProviderRequestKind,
ProviderSandboxMode,
ProviderStartOptions,
ProviderUserInputAnswers,
RuntimeMode,
} from "./orchestration";
@@ -54,6 +55,7 @@ export const ProviderSessionStartInput = Schema.Struct({
resumeCursor: Schema.optional(Schema.Unknown),
approvalPolicy: Schema.optional(ProviderApprovalPolicy),
sandboxMode: Schema.optional(ProviderSandboxMode),
providerOptions: Schema.optional(ProviderStartOptions),
runtimeMode: RuntimeMode,
});
export type ProviderSessionStartInput = typeof ProviderSessionStartInput.Type;
+103 -27
View File
@@ -2,9 +2,100 @@ import { Schema } from "effect";
import { IsoDateTime, TrimmedNonEmptyString } from "./baseSchemas";
import { KeybindingRule, ResolvedKeybindingsConfig } from "./keybindings";
import { EditorId } from "./editor";
import { ModelCapabilities } from "./model";
import { ProviderKind } from "./orchestration";
import { ServerSettings } from "./settings";
import {
ClaudeModelOptions,
CodexModelOptions,
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(() => "")),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type CodexSettings = typeof CodexSettings.Type;
export const ClaudeSettings = Schema.Struct({
binaryPath: Schema.String.pipe(Schema.withDecodingDefault(() => "")),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
),
textGenerationModelSelection: ModelSelection.pipe(
Schema.withDecodingDefault(() => ({
provider: "codex" as const,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
})),
),
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
}).pipe(Schema.withDecodingDefault(() => ({}))),
});
export type ServerSettings = typeof ServerSettings.Type;
export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeUnknownSync(ServerSettings)({});
const CodexModelOptionsPatch = Schema.Struct({
reasoningEffort: Schema.optionalKey(CodexModelOptions.fields.reasoningEffort),
fastMode: Schema.optionalKey(CodexModelOptions.fields.fastMode),
});
const ClaudeModelOptionsPatch = Schema.Struct({
thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking),
effort: Schema.optionalKey(ClaudeModelOptions.fields.effort),
fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode),
});
const ModelSelectionPatch = Schema.Union([
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("codex")),
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(CodexModelOptionsPatch),
}),
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("claudeAgent")),
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(ClaudeModelOptionsPatch),
}),
]);
const CodexSettingsPatch = Schema.Struct({
binaryPath: Schema.optionalKey(Schema.String),
homePath: Schema.optionalKey(Schema.String),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const ClaudeSettingsPatch = Schema.Struct({
binaryPath: Schema.optionalKey(Schema.String),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
export const ServerSettingsPatch = Schema.Struct({
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
providers: Schema.optionalKey(
Schema.Struct({
codex: Schema.optionalKey(CodexSettingsPatch),
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
}),
),
});
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
const KeybindingsMalformedConfigIssue = Schema.Struct({
kind: Schema.Literal("keybindings.malformed-config"),
@@ -25,8 +116,8 @@ export type ServerConfigIssue = typeof ServerConfigIssue.Type;
const ServerConfigIssues = Schema.Array(ServerConfigIssue);
export const ServerProviderState = Schema.Literals(["ready", "warning", "error", "disabled"]);
export type ServerProviderState = typeof ServerProviderState.Type;
export const ServerProviderStatusState = Schema.Literals(["ready", "warning", "error"]);
export type ServerProviderStatusState = typeof ServerProviderStatusState.Type;
export const ServerProviderAuthStatus = Schema.Literals([
"authenticated",
@@ -35,35 +126,24 @@ export const ServerProviderAuthStatus = Schema.Literals([
]);
export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
export const ServerProviderModel = Schema.Struct({
slug: TrimmedNonEmptyString,
name: TrimmedNonEmptyString,
isCustom: Schema.Boolean,
capabilities: Schema.NullOr(ModelCapabilities),
});
export type ServerProviderModel = typeof ServerProviderModel.Type;
export const ServerProvider = Schema.Struct({
export const ServerProviderStatus = Schema.Struct({
provider: ProviderKind,
enabled: Schema.Boolean,
installed: Schema.Boolean,
version: Schema.NullOr(TrimmedNonEmptyString),
status: ServerProviderState,
status: ServerProviderStatusState,
available: Schema.Boolean,
authStatus: ServerProviderAuthStatus,
checkedAt: IsoDateTime,
message: Schema.optional(TrimmedNonEmptyString),
models: Schema.Array(ServerProviderModel),
});
export type ServerProvider = typeof ServerProvider.Type;
export type ServerProviderStatus = typeof ServerProviderStatus.Type;
const ServerProviders = Schema.Array(ServerProvider);
const ServerProviderStatuses = Schema.Array(ServerProviderStatus);
export const ServerConfig = Schema.Struct({
cwd: TrimmedNonEmptyString,
keybindingsConfigPath: TrimmedNonEmptyString,
keybindings: ResolvedKeybindingsConfig,
issues: ServerConfigIssues,
providers: ServerProviders,
providers: ServerProviderStatuses,
availableEditors: Schema.Array(EditorId),
settings: ServerSettings,
});
@@ -80,11 +160,7 @@ 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;
export const ServerProviderUpdatedPayload = Schema.Struct({
providers: ServerProviders,
});
export type ServerProviderUpdatedPayload = typeof ServerProviderUpdatedPayload.Type;
-153
View File
@@ -1,153 +0,0 @@
import { Effect } from "effect";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas";
import {
ClaudeModelOptions,
CodexModelOptions,
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
} from "./model";
import { ModelSelection } from "./orchestration";
// ── Client Settings (local-only) ───────────────────────────────
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";
export const ClientSettingsSchema = Schema.Struct({
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
diffWordWrap: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
sidebarProjectSortOrder: SidebarProjectSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_PROJECT_SORT_ORDER),
),
sidebarThreadSortOrder: SidebarThreadSortOrder.pipe(
Schema.withDecodingDefault(() => DEFAULT_SIDEBAR_THREAD_SORT_ORDER),
),
timestampFormat: TimestampFormat.pipe(Schema.withDecodingDefault(() => DEFAULT_TIMESTAMP_FORMAT)),
});
export type ClientSettings = typeof ClientSettingsSchema.Type;
export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
// ── Server Settings (server-authoritative) ────────────────────
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
export type ThreadEnvMode = typeof ThreadEnvMode.Type;
const makeBinaryPathSetting = (fallback: string) =>
TrimmedString.pipe(
Schema.decodeTo(
Schema.String,
SchemaTransformation.transformOrFail({
decode: (value) => Effect.succeed(value || fallback),
encode: (value) => Effect.succeed(value),
}),
),
Schema.withDecodingDefault(() => fallback),
);
export const CodexSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("codex"),
homePath: TrimmedString.pipe(Schema.withDecodingDefault(() => "")),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type CodexSettings = typeof CodexSettings.Type;
export const ClaudeSettings = Schema.Struct({
enabled: Schema.Boolean.pipe(Schema.withDecodingDefault(() => true)),
binaryPath: makeBinaryPathSetting("claude"),
customModels: Schema.Array(Schema.String).pipe(Schema.withDecodingDefault(() => [])),
});
export type ClaudeSettings = typeof ClaudeSettings.Type;
export const ServerSettings = Schema.Struct({
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(() => false)),
defaultThreadEnvMode: ThreadEnvMode.pipe(
Schema.withDecodingDefault(() => "local" as const satisfies ThreadEnvMode),
),
textGenerationModelSelection: ModelSelection.pipe(
Schema.withDecodingDefault(() => ({
provider: "codex" as const,
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
})),
),
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
claudeAgent: ClaudeSettings.pipe(Schema.withDecodingDefault(() => ({}))),
}).pipe(Schema.withDecodingDefault(() => ({}))),
});
export type ServerSettings = typeof ServerSettings.Type;
export const DEFAULT_SERVER_SETTINGS: ServerSettings = Schema.decodeSync(ServerSettings)({});
// ── Unified type ─────────────────────────────────────────────────────
export type UnifiedSettings = ServerSettings & ClientSettings;
export const DEFAULT_UNIFIED_SETTINGS: UnifiedSettings = {
...DEFAULT_SERVER_SETTINGS,
...DEFAULT_CLIENT_SETTINGS,
};
// ── Server Settings Patch (replace with a Schema.deepPartial if available) ──────────────────────────────────────────
const CodexModelOptionsPatch = Schema.Struct({
reasoningEffort: Schema.optionalKey(CodexModelOptions.fields.reasoningEffort),
fastMode: Schema.optionalKey(CodexModelOptions.fields.fastMode),
});
const ClaudeModelOptionsPatch = Schema.Struct({
thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking),
effort: Schema.optionalKey(ClaudeModelOptions.fields.effort),
fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode),
});
const ModelSelectionPatch = Schema.Union([
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("codex")),
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(CodexModelOptionsPatch),
}),
Schema.Struct({
provider: Schema.optionalKey(Schema.Literal("claudeAgent")),
model: Schema.optionalKey(TrimmedNonEmptyString),
options: Schema.optionalKey(ClaudeModelOptionsPatch),
}),
]);
const CodexSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
homePath: Schema.optionalKey(Schema.String),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
const ClaudeSettingsPatch = Schema.Struct({
enabled: Schema.optionalKey(Schema.Boolean),
binaryPath: Schema.optionalKey(Schema.String),
customModels: Schema.optionalKey(Schema.Array(Schema.String)),
});
export const ServerSettingsPatch = Schema.Struct({
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
providers: Schema.optionalKey(
Schema.Struct({
codex: Schema.optionalKey(CodexSettingsPatch),
claudeAgent: Schema.optionalKey(ClaudeSettingsPatch),
}),
),
});
export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
-19
View File
@@ -119,25 +119,6 @@ it.effect("accepts git.actionProgress push envelopes", () =>
}),
);
it.effect("accepts server.providersUpdated push envelopes", () =>
Effect.gen(function* () {
const parsed = yield* decodeWsResponse({
type: "push",
sequence: 4,
channel: WS_CHANNELS.serverProvidersUpdated,
data: {
providers: [],
},
});
if (!("type" in parsed) || parsed.type !== "push") {
assert.fail("expected websocket response to decode as a push envelope");
}
assert.strictEqual(parsed.channel, WS_CHANNELS.serverProvidersUpdated);
}),
);
it.effect("rejects push envelopes when channel payload does not match the channel schema", () =>
Effect.gen(function* () {
const result = yield* Effect.exit(
+1 -10
View File
@@ -37,8 +37,7 @@ import {
import { KeybindingRule } from "./keybindings";
import { ProjectSearchEntriesInput, ProjectWriteFileInput } from "./project";
import { OpenInEditorInput } from "./editor";
import { ServerConfigUpdatedPayload, ServerProviderUpdatedPayload } from "./server";
import { ServerSettingsPatch } from "./settings";
import { ServerConfigUpdatedPayload, ServerSettingsPatch } from "./server";
// ── WebSocket RPC Method Names ───────────────────────────────────────
@@ -88,7 +87,6 @@ export const WS_CHANNELS = {
terminalEvent: "terminal.event",
serverWelcome: "server.welcome",
serverConfigUpdated: "server.configUpdated",
serverProvidersUpdated: "server.providersUpdated",
} as const;
// -- Tagged Union of all request body schemas ─────────────────────────
@@ -180,7 +178,6 @@ export type WsWelcomePayload = typeof WsWelcomePayload.Type;
export interface WsPushPayloadByChannel {
readonly [WS_CHANNELS.serverWelcome]: WsWelcomePayload;
readonly [WS_CHANNELS.serverConfigUpdated]: typeof ServerConfigUpdatedPayload.Type;
readonly [WS_CHANNELS.serverProvidersUpdated]: typeof ServerProviderUpdatedPayload.Type;
readonly [WS_CHANNELS.gitActionProgress]: typeof GitActionProgressEvent.Type;
readonly [WS_CHANNELS.terminalEvent]: typeof TerminalEvent.Type;
readonly [ORCHESTRATION_WS_CHANNELS.domainEvent]: OrchestrationEvent;
@@ -205,10 +202,6 @@ export const WsPushServerConfigUpdated = makeWsPushSchema(
WS_CHANNELS.serverConfigUpdated,
ServerConfigUpdatedPayload,
);
export const WsPushServerProvidersUpdated = makeWsPushSchema(
WS_CHANNELS.serverProvidersUpdated,
ServerProviderUpdatedPayload,
);
export const WsPushGitActionProgress = makeWsPushSchema(
WS_CHANNELS.gitActionProgress,
GitActionProgressEvent,
@@ -223,7 +216,6 @@ export const WsPushChannelSchema = Schema.Literals([
WS_CHANNELS.gitActionProgress,
WS_CHANNELS.serverWelcome,
WS_CHANNELS.serverConfigUpdated,
WS_CHANNELS.serverProvidersUpdated,
WS_CHANNELS.terminalEvent,
ORCHESTRATION_WS_CHANNELS.domainEvent,
]);
@@ -232,7 +224,6 @@ export type WsPushChannelSchema = typeof WsPushChannelSchema.Type;
export const WsPush = Schema.Union([
WsPushServerWelcome,
WsPushServerConfigUpdated,
WsPushServerProvidersUpdated,
WsPushGitActionProgress,
WsPushTerminalEvent,
WsPushOrchestrationDomainEvent,
+11 -9
View File
@@ -1,13 +1,12 @@
import * as P from "effect/Predicate";
export type DeepPartial<T> = T extends readonly (infer U)[]
? readonly DeepPartial<U>[]
: T extends object
? { [K in keyof T]?: DeepPartial<T[K]> }
: T;
export function deepMerge<T extends Record<string, unknown>>(current: T, patch: DeepPartial<T>): T {
if (!P.isObject(current) || !P.isObject(patch)) {
export function deepMerge<T>(current: T, patch: unknown): T {
if (
!P.isObject(current) ||
!P.isObject(patch) ||
Array.isArray(current) ||
Array.isArray(patch)
) {
return patch as T;
}
@@ -16,7 +15,10 @@ export function deepMerge<T extends Record<string, unknown>>(current: T, patch:
if (value === undefined) continue;
const existing = next[key];
next[key] = P.isObject(existing) && P.isObject(value) ? deepMerge(existing, value) : value;
next[key] =
P.isObject(existing) && P.isObject(value) && !Array.isArray(existing) && !Array.isArray(value)
? deepMerge(existing, value)
: value;
}
return next as T;
+270 -57
View File
@@ -2,46 +2,31 @@ import { describe, expect, it } from "vitest";
import {
DEFAULT_MODEL,
DEFAULT_MODEL_BY_PROVIDER,
type ModelCapabilities,
MODEL_OPTIONS,
MODEL_OPTIONS_BY_PROVIDER,
CODEX_REASONING_EFFORT_OPTIONS,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
getDefaultEffort,
hasEffortLevel,
getDefaultModel,
getModelCapabilities,
getModelOptions,
isClaudeUltrathinkPrompt,
normalizeClaudeModelOptions,
normalizeCodexModelOptions,
normalizeModelSlug,
resolveSelectableModel,
resolveModelSlug,
resolveModelSlugForProvider,
resolveSelectableModel,
trimOrNull,
getDefaultEffort,
hasEffortLevel,
} from "./model";
const codexCaps: ModelCapabilities = {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
],
supportsFastMode: true,
supportsThinkingToggle: false,
promptInjectedEffortLevels: [],
};
const claudeCaps: ModelCapabilities = {
reasoningEffortLevels: [
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "ultrathink", label: "Ultrathink" },
],
supportsFastMode: false,
supportsThinkingToggle: false,
promptInjectedEffortLevels: ["ultrathink"],
};
describe("normalizeModelSlug", () => {
it("maps known aliases to canonical slugs", () => {
expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("sonnet", "claudeAgent")).toBe("claude-sonnet-4-6");
expect(normalizeModelSlug("gpt-5.3")).toBe("gpt-5.3-codex");
});
it("returns null for empty or missing values", () => {
@@ -50,62 +35,290 @@ describe("normalizeModelSlug", () => {
expect(normalizeModelSlug(null)).toBeNull();
expect(normalizeModelSlug(undefined)).toBeNull();
});
it("preserves non-aliased model slugs", () => {
expect(normalizeModelSlug("gpt-5.2")).toBe("gpt-5.2");
expect(normalizeModelSlug("gpt-5.2-codex")).toBe("gpt-5.2-codex");
});
it("does not leak prototype properties as aliases", () => {
expect(normalizeModelSlug("toString")).toBe("toString");
expect(normalizeModelSlug("constructor")).toBe("constructor");
});
it("uses provider-specific aliases", () => {
expect(normalizeModelSlug("sonnet", "claudeAgent")).toBe("claude-sonnet-4-6");
expect(normalizeModelSlug("opus-4.6", "claudeAgent")).toBe("claude-opus-4-6");
expect(normalizeModelSlug("claude-haiku-4-5-20251001", "claudeAgent")).toBe("claude-haiku-4-5");
});
});
describe("resolveModelSlug", () => {
it("returns defaults when the model is missing", () => {
it("returns default only when the model is missing", () => {
expect(resolveModelSlug(undefined)).toBe(DEFAULT_MODEL);
expect(resolveModelSlug(null)).toBe(DEFAULT_MODEL);
});
it("preserves unknown custom models", () => {
expect(resolveModelSlug("gpt-4.1")).toBe(DEFAULT_MODEL);
expect(resolveModelSlug("custom/internal-model")).toBe(DEFAULT_MODEL);
});
it("resolves only supported model options", () => {
for (const model of MODEL_OPTIONS) {
expect(resolveModelSlug(model.slug)).toBe(model.slug);
}
});
it("supports provider-aware resolution", () => {
expect(resolveModelSlugForProvider("claudeAgent", undefined)).toBe(
DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
);
expect(resolveModelSlugForProvider("claudeAgent", "sonnet")).toBe("claude-sonnet-4-6");
expect(resolveModelSlugForProvider("claudeAgent", "gpt-5.3-codex")).toBe(
DEFAULT_MODEL_BY_PROVIDER.claudeAgent,
);
});
it("preserves normalized unknown models", () => {
expect(resolveModelSlug("custom/internal-model")).toBe("custom/internal-model");
it("keeps codex defaults for backward compatibility", () => {
expect(getDefaultModel()).toBe(DEFAULT_MODEL);
expect(getModelOptions()).toEqual(MODEL_OPTIONS);
expect(getModelOptions("claudeAgent")).toEqual(MODEL_OPTIONS_BY_PROVIDER.claudeAgent);
});
});
describe("resolveSelectableModel", () => {
it("resolves exact slugs, labels, and aliases", () => {
const options = [
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
];
expect(resolveSelectableModel("codex", "gpt-5.3-codex", options)).toBe("gpt-5.3-codex");
expect(resolveSelectableModel("codex", "gpt-5.3 codex", options)).toBe("gpt-5.3-codex");
expect(resolveSelectableModel("claudeAgent", "sonnet", options)).toBe("claude-sonnet-4-6");
it("resolves exact slug matches", () => {
expect(
resolveSelectableModel("codex", "gpt-5.3-codex", [
{ slug: "gpt-5.4", name: "GPT-5.4" },
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
]),
).toBe("gpt-5.3-codex");
});
it("resolves case-insensitive display-name matches", () => {
expect(
resolveSelectableModel("codex", "gpt-5.3 codex", [
{ slug: "gpt-5.4", name: "GPT-5.4" },
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
]),
).toBe("gpt-5.3-codex");
});
it("resolves provider-specific aliases after normalization", () => {
expect(
resolveSelectableModel("claudeAgent", "sonnet", [
{ slug: "claude-opus-4-6", name: "Claude Opus 4.6" },
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
]),
).toBe("claude-sonnet-4-6");
});
it("returns null for empty input", () => {
expect(resolveSelectableModel("codex", "", [{ slug: "gpt-5.4", name: "GPT-5.4" }])).toBeNull();
expect(
resolveSelectableModel("codex", " ", [{ slug: "gpt-5.4", name: "GPT-5.4" }]),
).toBeNull();
expect(
resolveSelectableModel("codex", null, [{ slug: "gpt-5.4", name: "GPT-5.4" }]),
).toBeNull();
});
it("returns null for unknown values that are not present in options", () => {
expect(
resolveSelectableModel("codex", "gpt-4.1", [{ slug: "gpt-5.4", name: "GPT-5.4" }]),
).toBeNull();
});
it("does not accept normalized custom-looking slugs unless they exist in options", () => {
expect(
resolveSelectableModel("codex", "custom/internal-model", [
{ slug: "gpt-5.4", name: "GPT-5.4" },
]),
).toBeNull();
});
it("respects provider boundaries", () => {
expect(
resolveSelectableModel("codex", "sonnet", [{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" }]),
).toBeNull();
expect(
resolveSelectableModel("claudeAgent", "5.3", [
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
]),
).toBeNull();
});
});
describe("capability helpers", () => {
it("reads default efforts", () => {
expect(getDefaultEffort(codexCaps)).toBe("high");
expect(getDefaultEffort(claudeCaps)).toBe("high");
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(values("codex", "gpt-5.4")).toEqual([...CODEX_REASONING_EFFORT_OPTIONS]);
});
it("checks effort support", () => {
it("returns claude effort options for Opus 4.6", () => {
expect(values("claudeAgent", "claude-opus-4-6")).toEqual([
"low",
"medium",
"high",
"max",
"ultrathink",
]);
});
it("returns claude effort options for Sonnet 4.6", () => {
expect(values("claudeAgent", "claude-sonnet-4-6")).toEqual([
"low",
"medium",
"high",
"ultrathink",
]);
});
it("returns no claude effort options for Haiku 4.5", () => {
expect(values("claudeAgent", "claude-haiku-4-5")).toEqual([]);
});
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("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();
});
});
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);
});
});
describe("misc helpers", () => {
it("detects ultrathink prompts", () => {
expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true);
expect(isClaudeUltrathinkPrompt("Investigate")).toBe(false);
});
it("prefixes ultrathink prompts once", () => {
expect(applyClaudePromptEffortPrefix("Investigate", "ultrathink")).toBe(
"Ultrathink:\nInvestigate",
describe("applyClaudePromptEffortPrefix", () => {
it("prefixes ultrathink prompts exactly once", () => {
expect(applyClaudePromptEffortPrefix("Investigate this", "ultrathink")).toBe(
"Ultrathink:\nInvestigate this",
);
expect(applyClaudePromptEffortPrefix("Ultrathink:\nInvestigate", "ultrathink")).toBe(
"Ultrathink:\nInvestigate",
expect(applyClaudePromptEffortPrefix("Ultrathink:\nInvestigate this", "ultrathink")).toBe(
"Ultrathink:\nInvestigate this",
);
});
it("trims strings to null", () => {
expect(trimOrNull(" hi ")).toBe("hi");
expect(trimOrNull(" ")).toBeNull();
it("leaves non-ultrathink prompts unchanged", () => {
expect(applyClaudePromptEffortPrefix("Investigate this", "high")).toBe("Investigate this");
});
});
describe("normalizeCodexModelOptions", () => {
it("drops default-only codex options", () => {
expect(
normalizeCodexModelOptions("gpt-5.4", { reasoningEffort: "high", fastMode: false }),
).toBeUndefined();
});
it("preserves non-default codex options", () => {
expect(
normalizeCodexModelOptions("gpt-5.4", { reasoningEffort: "xhigh", fastMode: true }),
).toEqual({
reasoningEffort: "xhigh",
fastMode: true,
});
});
});
describe("normalizeClaudeModelOptions", () => {
it("drops unsupported fast mode and max effort for Sonnet", () => {
expect(
normalizeClaudeModelOptions("claude-sonnet-4-6", {
effort: "max",
fastMode: true,
}),
).toBeUndefined();
});
it("keeps the Haiku thinking toggle and removes unsupported effort", () => {
expect(
normalizeClaudeModelOptions("claude-haiku-4-5", {
thinking: false,
effort: "high",
}),
).toEqual({
thinking: false,
});
});
});
describe("getModelCapabilities Claude capability flags", () => {
it("only enables adaptive reasoning for Opus 4.6 and Sonnet 4.6", () => {
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);
});
it("only enables max effort for Opus 4.6", () => {
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);
});
it("only enables Claude fast mode for Opus 4.6", () => {
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);
});
it("only enables ultrathink keyword handling for Opus 4.6 and Sonnet 4.6", () => {
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);
});
it("only enables the Claude thinking toggle for Haiku 4.5", () => {
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);
});
});
describe("isClaudeUltrathinkPrompt", () => {
it("detects ultrathink prompts case-insensitively", () => {
expect(isClaudeUltrathinkPrompt("Please ultrathink about this")).toBe(true);
expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true);
expect(isClaudeUltrathinkPrompt("Think hard about this")).toBe(false);
expect(isClaudeUltrathinkPrompt(undefined)).toBe(false);
});
});
+77 -1
View File
@@ -1,17 +1,31 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
MODEL_CAPABILITIES_INDEX,
MODEL_OPTIONS_BY_PROVIDER,
MODEL_SLUG_ALIASES_BY_PROVIDER,
type ClaudeModelOptions,
type ClaudeCodeEffort,
type CodexModelOptions,
type ModelCapabilities,
type ModelSlug,
type ProviderKind,
CodexReasoningEffort,
} from "@t3tools/contracts";
const MODEL_SLUG_SET_BY_PROVIDER: Record<ProviderKind, ReadonlySet<ModelSlug>> = {
claudeAgent: new Set(MODEL_OPTIONS_BY_PROVIDER.claudeAgent.map((option) => option.slug)),
codex: new Set(MODEL_OPTIONS_BY_PROVIDER.codex.map((option) => option.slug)),
};
export interface SelectableModelOption {
slug: string;
name: string;
}
export function getModelOptions(provider: ProviderKind = "codex") {
return MODEL_OPTIONS_BY_PROVIDER[provider];
}
export function getDefaultModel(provider: ProviderKind = "codex"): ModelSlug {
return DEFAULT_MODEL_BY_PROVIDER[provider];
}
@@ -28,6 +42,24 @@ export function getDefaultEffort(caps: ModelCapabilities): string | null {
return caps.reasoningEffortLevels.find((l) => l.isDefault)?.value ?? null;
}
// ── Data-driven capability resolver ───────────────────────────────────
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 {
return typeof text === "string" && /\bultrathink\b/i.test(text);
}
@@ -93,7 +125,10 @@ export function resolveModelSlug(
if (!normalized) {
return DEFAULT_MODEL_BY_PROVIDER[provider];
}
return normalized;
return MODEL_SLUG_SET_BY_PROVIDER[provider].has(normalized)
? normalized
: DEFAULT_MODEL_BY_PROVIDER[provider];
}
export function resolveModelSlugForProvider(
@@ -110,6 +145,47 @@ export function trimOrNull<T extends string>(value: T | null | undefined): T | n
return trimmed || null;
}
export function normalizeCodexModelOptions(
model: string | null | undefined,
modelOptions: CodexModelOptions | null | undefined,
): CodexModelOptions | undefined {
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 } : {}),
...(fastModeEnabled ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function normalizeClaudeModelOptions(
model: string | null | undefined,
modelOptions: ClaudeModelOptions | null | undefined,
): ClaudeModelOptions | undefined {
const caps = getModelCapabilities("claudeAgent", model);
const defaultReasoningEffort = getDefaultEffort(caps);
const resolvedEffort = trimOrNull(modelOptions?.effort);
const isPromptInjected = caps.promptInjectedEffortLevels.includes(resolvedEffort ?? "");
const effort =
resolvedEffort &&
!isPromptInjected &&
hasEffortLevel(caps, resolvedEffort) &&
resolvedEffort !== defaultReasoningEffort
? resolvedEffort
: undefined;
const thinking =
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 } : {}),
...(fastMode ? { fastMode: true } : {}),
};
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
}
export function applyClaudePromptEffortPrefix(
text: string,
effort: ClaudeCodeEffort | null | undefined,