Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8c367df4a | ||
|
|
ea3e9987d7 | ||
|
|
12ecd648ba | ||
|
|
d8a485ea7e | ||
|
|
e980a2fd8f | ||
|
|
02989fe600 | ||
|
|
648f0676bd | ||
|
|
add5f34619 | ||
|
|
9403429a7a | ||
|
|
37cf0c1144 | ||
|
|
bf1f3e1c4f | ||
|
|
2aa11ae076 | ||
|
|
8888f6a0c9 |
No files matched your search
@@ -38,6 +38,7 @@ 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";
|
||||
@@ -67,7 +68,6 @@ 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,6 +324,7 @@ 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,5 +1,6 @@
|
||||
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";
|
||||
@@ -12,6 +13,7 @@ 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";
|
||||
@@ -60,6 +62,7 @@ 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));
|
||||
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import crypto from "node:crypto";
|
||||
import type { IncomingHttpHeaders } from "node:http";
|
||||
|
||||
import { Effect, FileSystem, Layer, Path, Ref, Schema, ServiceMap } from "effect";
|
||||
|
||||
import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
|
||||
const BOOTSTRAP_TOKEN_TTL_MS = 5 * 60 * 1_000;
|
||||
const AUTH_COOKIE_MAX_AGE_SECONDS = 30 * 24 * 60 * 60;
|
||||
const AUTH_COOKIE_NAME = "t3_auth";
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const COOKIE_SECRET_FILENAME = "browser-auth-secret";
|
||||
|
||||
interface BootstrapState {
|
||||
readonly token: string;
|
||||
readonly expiresAt: number;
|
||||
readonly consumedAt: number | null;
|
||||
}
|
||||
|
||||
interface AuthCookiePayload {
|
||||
readonly v: 1;
|
||||
readonly purpose: "browser-auth";
|
||||
readonly iat: number;
|
||||
readonly exp: number;
|
||||
}
|
||||
|
||||
export class BrowserAuthError extends Schema.TaggedErrorClass<BrowserAuthError>()(
|
||||
"BrowserAuthError",
|
||||
{
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {}
|
||||
|
||||
export interface BrowserAuthShape {
|
||||
readonly getPairingUrl: (baseUrl: string) => Effect.Effect<string, never>;
|
||||
readonly getAllowedOrigins: Effect.Effect<ReadonlySet<string>, never>;
|
||||
readonly isAllowedOrigin: (origin: string | undefined) => Effect.Effect<boolean, never>;
|
||||
readonly consumeBootstrapToken: (token: string) => Effect.Effect<boolean, never>;
|
||||
readonly isAuthenticatedRequest: (headers: IncomingHttpHeaders) => Effect.Effect<boolean, never>;
|
||||
readonly createAuthCookie: (isSecure: boolean) => Effect.Effect<string, never>;
|
||||
}
|
||||
|
||||
export class BrowserAuth extends ServiceMap.Service<BrowserAuth, BrowserAuthShape>()(
|
||||
"t3/browserAuth",
|
||||
) {}
|
||||
|
||||
function makeBootstrapToken(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function makeCookieSecret(): string {
|
||||
return crypto.randomBytes(32).toString("base64url");
|
||||
}
|
||||
|
||||
function toBase64Url(input: string): string {
|
||||
return Buffer.from(input, "utf8").toString("base64url");
|
||||
}
|
||||
|
||||
function fromBase64Url(input: string): string {
|
||||
return Buffer.from(input, "base64url").toString("utf8");
|
||||
}
|
||||
|
||||
function signCookie(payload: AuthCookiePayload, secret: string): string {
|
||||
const payloadEncoded = toBase64Url(JSON.stringify(payload));
|
||||
const signature = crypto.createHmac("sha256", secret).update(payloadEncoded).digest("base64url");
|
||||
return `${payloadEncoded}.${signature}`;
|
||||
}
|
||||
|
||||
function verifyCookie(cookie: string, secret: string, now = Date.now()): boolean {
|
||||
const separatorIndex = cookie.lastIndexOf(".");
|
||||
if (separatorIndex <= 0 || separatorIndex >= cookie.length - 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const payloadEncoded = cookie.slice(0, separatorIndex);
|
||||
const providedSignature = cookie.slice(separatorIndex + 1);
|
||||
const expectedSignature = crypto
|
||||
.createHmac("sha256", secret)
|
||||
.update(payloadEncoded)
|
||||
.digest("base64url");
|
||||
|
||||
const providedBuffer = Buffer.from(providedSignature, "utf8");
|
||||
const expectedBuffer = Buffer.from(expectedSignature, "utf8");
|
||||
if (providedBuffer.length !== expectedBuffer.length) {
|
||||
return false;
|
||||
}
|
||||
if (!crypto.timingSafeEqual(providedBuffer, expectedBuffer)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(fromBase64Url(payloadEncoded)) as Partial<AuthCookiePayload>;
|
||||
if (parsed.v !== 1 || parsed.purpose !== "browser-auth") {
|
||||
return false;
|
||||
}
|
||||
if (typeof parsed.exp !== "number" || !Number.isFinite(parsed.exp)) {
|
||||
return false;
|
||||
}
|
||||
return parsed.exp > now;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function parseCookies(cookieHeader: string | string[] | undefined): Map<string, string> {
|
||||
const raw = Array.isArray(cookieHeader) ? cookieHeader.join("; ") : cookieHeader;
|
||||
if (!raw) return new Map();
|
||||
|
||||
const cookies = new Map<string, string>();
|
||||
for (const segment of raw.split(";")) {
|
||||
const trimmed = segment.trim();
|
||||
if (trimmed.length === 0) continue;
|
||||
const separatorIndex = trimmed.indexOf("=");
|
||||
if (separatorIndex <= 0) continue;
|
||||
const key = trimmed.slice(0, separatorIndex).trim();
|
||||
const value = trimmed.slice(separatorIndex + 1).trim();
|
||||
if (key.length === 0 || value.length === 0) continue;
|
||||
cookies.set(key, value);
|
||||
}
|
||||
return cookies;
|
||||
}
|
||||
|
||||
function normalizeOriginSet(serverConfig: ServerConfigShape): ReadonlySet<string> {
|
||||
const origins = new Set<string>();
|
||||
origins.add(`http://localhost:${serverConfig.port}`);
|
||||
origins.add(`http://127.0.0.1:${serverConfig.port}`);
|
||||
origins.add(`http://[::1]:${serverConfig.port}`);
|
||||
|
||||
if (
|
||||
serverConfig.host &&
|
||||
serverConfig.host !== "0.0.0.0" &&
|
||||
serverConfig.host !== "::" &&
|
||||
serverConfig.host !== "[::]"
|
||||
) {
|
||||
const host =
|
||||
serverConfig.host.includes(":") && !serverConfig.host.startsWith("[")
|
||||
? `[${serverConfig.host}]`
|
||||
: serverConfig.host;
|
||||
origins.add(`http://${host}:${serverConfig.port}`);
|
||||
}
|
||||
|
||||
if (serverConfig.devUrl) {
|
||||
origins.add(serverConfig.devUrl.origin);
|
||||
}
|
||||
|
||||
return origins;
|
||||
}
|
||||
|
||||
function formatAuthCookie(cookieValue: string, isSecure: boolean): string {
|
||||
const attributes = [
|
||||
`${AUTH_COOKIE_NAME}=${cookieValue}`,
|
||||
"HttpOnly",
|
||||
"Path=/",
|
||||
"SameSite=Strict",
|
||||
`Max-Age=${AUTH_COOKIE_MAX_AGE_SECONDS}`,
|
||||
];
|
||||
if (isSecure) {
|
||||
attributes.push("Secure");
|
||||
}
|
||||
return attributes.join("; ");
|
||||
}
|
||||
|
||||
export const BrowserAuthLive = Layer.effect(
|
||||
BrowserAuth,
|
||||
Effect.gen(function* () {
|
||||
const serverConfig = yield* ServerConfig;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const cookieSecretPath = path.join(serverConfig.stateDir, COOKIE_SECRET_FILENAME);
|
||||
|
||||
const existingSecret = yield* fileSystem
|
||||
.readFileString(cookieSecretPath)
|
||||
.pipe(Effect.catch(() => Effect.succeed(null)));
|
||||
const cookieSecret =
|
||||
existingSecret && existingSecret.trim().length > 0
|
||||
? existingSecret.trim()
|
||||
: makeCookieSecret();
|
||||
|
||||
if (existingSecret === null || existingSecret.trim().length === 0) {
|
||||
yield* fileSystem.makeDirectory(path.dirname(cookieSecretPath), { recursive: true });
|
||||
yield* fileSystem.writeFileString(cookieSecretPath, `${cookieSecret}\n`);
|
||||
}
|
||||
|
||||
const bootstrapState = yield* Ref.make<BootstrapState>({
|
||||
token: makeBootstrapToken(),
|
||||
expiresAt: Date.now() + BOOTSTRAP_TOKEN_TTL_MS,
|
||||
consumedAt: null,
|
||||
});
|
||||
const allowedOrigins = normalizeOriginSet(serverConfig);
|
||||
|
||||
const getPairingUrl: BrowserAuthShape["getPairingUrl"] = (baseUrl) =>
|
||||
Ref.get(bootstrapState).pipe(
|
||||
Effect.map((state) => {
|
||||
const target = new URL(baseUrl);
|
||||
target.hash = `${BOOTSTRAP_HASH_KEY}=${state.token}`;
|
||||
return target.toString();
|
||||
}),
|
||||
);
|
||||
|
||||
const isAllowedOrigin: BrowserAuthShape["isAllowedOrigin"] = (origin) =>
|
||||
Effect.succeed(typeof origin === "string" && allowedOrigins.has(origin));
|
||||
|
||||
const consumeBootstrapToken: BrowserAuthShape["consumeBootstrapToken"] = (token) =>
|
||||
Ref.modify(bootstrapState, (state) => {
|
||||
const now = Date.now();
|
||||
const matches =
|
||||
token.length > 0 &&
|
||||
state.consumedAt === null &&
|
||||
state.expiresAt > now &&
|
||||
state.token === token;
|
||||
return [matches, matches ? { ...state, consumedAt: now } : state] as const;
|
||||
});
|
||||
|
||||
const isAuthenticatedRequest: BrowserAuthShape["isAuthenticatedRequest"] = (headers) =>
|
||||
Effect.succeed(
|
||||
verifyCookie(parseCookies(headers.cookie).get(AUTH_COOKIE_NAME) ?? "", cookieSecret),
|
||||
);
|
||||
|
||||
const createAuthCookie: BrowserAuthShape["createAuthCookie"] = (isSecure) =>
|
||||
Effect.succeed(
|
||||
formatAuthCookie(
|
||||
signCookie(
|
||||
{
|
||||
v: 1,
|
||||
purpose: "browser-auth",
|
||||
iat: Date.now(),
|
||||
exp: Date.now() + AUTH_COOKIE_MAX_AGE_SECONDS * 1_000,
|
||||
},
|
||||
cookieSecret,
|
||||
),
|
||||
isSecure,
|
||||
),
|
||||
);
|
||||
|
||||
return {
|
||||
getPairingUrl,
|
||||
getAllowedOrigins: Effect.succeed(allowedOrigins),
|
||||
isAllowedOrigin,
|
||||
consumeBootstrapToken,
|
||||
isAuthenticatedRequest,
|
||||
createAuthCookie,
|
||||
} satisfies BrowserAuthShape;
|
||||
}),
|
||||
);
|
||||
@@ -342,6 +342,7 @@ describe("startSession", () => {
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow("cwd missing");
|
||||
@@ -390,6 +391,7 @@ describe("startSession", () => {
|
||||
manager.startSession({
|
||||
threadId: asThreadId("thread-1"),
|
||||
provider: "codex",
|
||||
binaryPath: "codex",
|
||||
runtimeMode: "full-access",
|
||||
}),
|
||||
).rejects.toThrow(
|
||||
@@ -948,12 +950,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
||||
provider: "codex",
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
},
|
||||
},
|
||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
});
|
||||
|
||||
const firstTurn = await manager.sendTurn({
|
||||
@@ -983,12 +981,8 @@ describe.skipIf(!process.env.CODEX_BINARY_PATH)("startSession live Codex resume"
|
||||
cwd: workspaceDir,
|
||||
runtimeMode: "approval-required",
|
||||
resumeCursor: firstSession.resumeCursor,
|
||||
providerOptions: {
|
||||
codex: {
|
||||
...(process.env.CODEX_BINARY_PATH ? { binaryPath: process.env.CODEX_BINARY_PATH } : {}),
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
},
|
||||
},
|
||||
binaryPath: process.env.CODEX_BINARY_PATH!,
|
||||
...(process.env.CODEX_HOME_PATH ? { homePath: process.env.CODEX_HOME_PATH } : {}),
|
||||
});
|
||||
|
||||
expect(resumedSession.threadId).toBe(originalThreadId);
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
type ProviderApprovalDecision,
|
||||
type ProviderEvent,
|
||||
type ProviderSession,
|
||||
type ProviderSessionStartInput,
|
||||
type ProviderTurnStartResult,
|
||||
RuntimeMode,
|
||||
ProviderInteractionMode,
|
||||
@@ -131,7 +130,8 @@ export interface CodexAppServerStartSessionInput {
|
||||
readonly model?: string;
|
||||
readonly serviceTier?: string;
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly providerOptions?: ProviderSessionStartInput["providerOptions"];
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly runtimeMode: RuntimeMode;
|
||||
}
|
||||
|
||||
@@ -541,9 +541,8 @@ export class CodexAppServerManager extends EventEmitter<CodexAppServerManagerEve
|
||||
updatedAt: now,
|
||||
};
|
||||
|
||||
const codexOptions = readCodexProviderOptions(input);
|
||||
const codexBinaryPath = codexOptions.binaryPath ?? "codex";
|
||||
const codexHomePath = codexOptions.homePath;
|
||||
const codexBinaryPath = input.binaryPath;
|
||||
const codexHomePath = input.homePath;
|
||||
this.assertSupportedCodexCliVersion({
|
||||
binaryPath: codexBinaryPath,
|
||||
cwd: resolvedCwd,
|
||||
@@ -1591,20 +1590,6 @@ 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;
|
||||
@@ -1658,7 +1643,11 @@ function readResumeCursorThreadId(resumeCursor: unknown): string | undefined {
|
||||
return typeof rawThreadId === "string" ? normalizeProviderThreadId(rawThreadId) : undefined;
|
||||
}
|
||||
|
||||
function readResumeThreadId(input: CodexAppServerStartSessionInput): string | undefined {
|
||||
function readResumeThreadId(input: {
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly threadId?: ThreadId;
|
||||
readonly runtimeMode?: RuntimeMode;
|
||||
}): string | undefined {
|
||||
return readResumeCursorThreadId(input.resumeCursor);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +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 { resolveApiModelId } from "@t3tools/shared/model";
|
||||
import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@t3tools/shared/git";
|
||||
|
||||
import { TextGenerationError } from "../Errors.ts";
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
sanitizePrTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
@@ -90,7 +91,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
|
||||
const claudeSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.claude,
|
||||
(settings) => settings.providers.claudeAgent,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runClaudeCommand = Effect.gen(function* () {
|
||||
@@ -103,7 +104,7 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
"--json-schema",
|
||||
jsonSchemaStr,
|
||||
"--model",
|
||||
modelSelection.model,
|
||||
resolveApiModelId(modelSelection),
|
||||
...(normalizedOptions?.effort ? ["--effort", normalizedOptions.effort] : []),
|
||||
...(Object.keys(settings).length > 0 ? ["--settings", JSON.stringify(settings)] : []),
|
||||
"--dangerously-skip-permissions",
|
||||
|
||||
@@ -24,7 +24,20 @@ const CodexTextGenerationTestLayer = CodexTextGenerationLive.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
function makeFakeCodexBinary(dir: string) {
|
||||
function makeFakeCodexBinary(
|
||||
dir: string,
|
||||
input: {
|
||||
output: string;
|
||||
exitCode?: number;
|
||||
stderr?: string;
|
||||
requireImage?: boolean;
|
||||
requireFastServiceTier?: boolean;
|
||||
requireReasoningEffort?: string;
|
||||
forbidReasoningEffort?: boolean;
|
||||
stdinMustContain?: string;
|
||||
stdinMustNotContain?: string;
|
||||
},
|
||||
) {
|
||||
return Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -37,12 +50,16 @@ function makeFakeCodexBinary(dir: string) {
|
||||
[
|
||||
"#!/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',
|
||||
@@ -55,55 +72,80 @@ function makeFakeCodexBinary(dir: string) {
|
||||
' 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)"',
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_IMAGE" = "1" ] && [ "$seen_image" != "1" ]; then',
|
||||
' printf "%s\\n" "missing --image input" >&2',
|
||||
" exit 2",
|
||||
"fi",
|
||||
'if [ "$T3_FAKE_CODEX_REQUIRE_FAST_SERVICE_TIER" = "1" ] && [ "$seen_fast_service_tier" != "1" ]; then',
|
||||
' printf "%s\\n" "missing fast service tier config" >&2',
|
||||
" exit 5",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT" ] && [ "$seen_reasoning_effort" != "model_reasoning_effort=\\"$T3_FAKE_CODEX_REQUIRE_REASONING_EFFORT\\"" ]; then',
|
||||
' printf "%s\\n" "unexpected reasoning effort config: $seen_reasoning_effort" >&2',
|
||||
" exit 6",
|
||||
"fi",
|
||||
'if [ "$T3_FAKE_CODEX_FORBID_REASONING_EFFORT" = "1" ] && [ -n "$seen_reasoning_effort" ]; then',
|
||||
' printf "%s\\n" "reasoning effort config should be omitted: $seen_reasoning_effort" >&2',
|
||||
" exit 7",
|
||||
"fi",
|
||||
'if [ -n "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" ]; then',
|
||||
' printf "%s" "$stdin_content" | grep -F -- "$T3_FAKE_CODEX_STDIN_MUST_CONTAIN" >/dev/null || {',
|
||||
' printf "%s\\n" "stdin missing expected content" >&2',
|
||||
" 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",
|
||||
...(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',
|
||||
' 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=}"',
|
||||
" cat > \"$output_path\" <<'__T3CODE_FAKE_CODEX_OUTPUT__'",
|
||||
input.output,
|
||||
"__T3CODE_FAKE_CODEX_OUTPUT__",
|
||||
"fi",
|
||||
'exit "${T3_FAKE_CODEX_EXIT_CODE:-0}"',
|
||||
`exit ${input.exitCode ?? 0}`,
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
yield* fs.chmod(codexPath, 0o755);
|
||||
return binDir;
|
||||
return codexPath;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -125,146 +167,29 @@ function withFakeCodexEnv<A, E, R>(
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const tempDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-codex-text-" });
|
||||
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;
|
||||
}
|
||||
const codexPath = yield* makeFakeCodexBinary(tempDir, input);
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const previousSettings = yield* serverSettings.getSettings;
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: codexPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
previousPath,
|
||||
previousOutput,
|
||||
previousExitCode,
|
||||
previousStderr,
|
||||
previousRequireImage,
|
||||
previousRequireFastServiceTier,
|
||||
previousRequireReasoningEffort,
|
||||
previousForbidReasoningEffort,
|
||||
previousStdinMustContain,
|
||||
previousStdinMustNotContain,
|
||||
};
|
||||
return { serverSettings, previousBinaryPath: previousSettings.providers.codex.binaryPath };
|
||||
}),
|
||||
() => effect,
|
||||
(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;
|
||||
}
|
||||
}),
|
||||
({ serverSettings, previousBinaryPath }) =>
|
||||
serverSettings
|
||||
.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: previousBinaryPath,
|
||||
},
|
||||
},
|
||||
})
|
||||
.pipe(Effect.asVoid),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,6 @@ 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";
|
||||
@@ -26,6 +25,7 @@ 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";
|
||||
@@ -142,7 +142,7 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
|
||||
const codexSettings = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.codex,
|
||||
(settings) => settings.providers.codex,
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
@@ -172,7 +172,10 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
"-",
|
||||
],
|
||||
{
|
||||
env: codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {},
|
||||
env: {
|
||||
...process.env,
|
||||
...(codexSettings?.homePath ? { CODEX_HOME: codexSettings.homePath } : {}),
|
||||
},
|
||||
cwd,
|
||||
shell: process.platform === "win32",
|
||||
stdin: {
|
||||
|
||||
@@ -20,11 +20,7 @@ import { GitCoreLive } from "./GitCore.ts";
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import { makeGitManager } from "./GitManager.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
|
||||
const DEFAULT_TEST_MODEL_SELECTION = {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
} as const;
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
interface FakeGhScenario {
|
||||
prListSequence?: string[];
|
||||
@@ -466,7 +462,6 @@ function runStackedAction(
|
||||
{
|
||||
...input,
|
||||
actionId: input.actionId ?? "test-action-id",
|
||||
modelSelection: DEFAULT_TEST_MODEL_SELECTION,
|
||||
},
|
||||
options,
|
||||
);
|
||||
@@ -493,6 +488,8 @@ function makeManager(input?: {
|
||||
prefix: "t3-git-manager-test-",
|
||||
});
|
||||
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
|
||||
const gitCoreLayer = GitCoreLive.pipe(
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
Layer.provideMerge(ServerConfigLayer),
|
||||
@@ -502,6 +499,7 @@ function makeManager(input?: {
|
||||
Layer.succeed(GitHubCli, gitHubCli),
|
||||
Layer.succeed(TextGeneration, textGeneration),
|
||||
gitCoreLayer,
|
||||
serverSettingsLayer,
|
||||
).pipe(Layer.provideMerge(NodeServices.layer));
|
||||
|
||||
return makeGitManager.pipe(
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { GitCore } from "../Services/GitCore.ts";
|
||||
import { GitHubCli } from "../Services/GitHubCli.ts";
|
||||
import { TextGeneration } from "../Services/TextGeneration.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
const COMMIT_TIMEOUT_MS = 10 * 60_000;
|
||||
const MAX_PROGRESS_TEXT_LENGTH = 500;
|
||||
@@ -358,6 +359,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
const gitCore = yield* GitCore;
|
||||
const gitHubCli = yield* GitHubCli;
|
||||
const textGeneration = yield* TextGeneration;
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
const createProgressEmitter = (
|
||||
input: { cwd: string; action: "commit" | "commit_push" | "commit_push_pr" },
|
||||
@@ -1173,6 +1175,13 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
let commitMessageForStep = input.commitMessage;
|
||||
let preResolvedCommitSuggestion: CommitAndBranchSuggestion | undefined = undefined;
|
||||
|
||||
const modelSelection = yield* serverSettingsService.getSettings.pipe(
|
||||
Effect.map((settings) => settings.textGenerationModelSelection),
|
||||
Effect.mapError((cause) =>
|
||||
gitManagerError("runStackedAction", "Failed to get server settings.", cause),
|
||||
),
|
||||
);
|
||||
|
||||
if (input.featureBranch) {
|
||||
currentPhase = "branch";
|
||||
yield* progress.emit({
|
||||
@@ -1181,7 +1190,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
label: "Preparing feature branch...",
|
||||
});
|
||||
const result = yield* runFeatureBranchStep(
|
||||
input.modelSelection,
|
||||
modelSelection,
|
||||
input.cwd,
|
||||
initialStatus.branch,
|
||||
input.commitMessage,
|
||||
@@ -1198,7 +1207,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
|
||||
currentPhase = "commit";
|
||||
const commit = yield* runCommitStep(
|
||||
input.modelSelection,
|
||||
modelSelection,
|
||||
input.cwd,
|
||||
input.action,
|
||||
currentBranch,
|
||||
@@ -1237,7 +1246,7 @@ export const makeGitManager = Effect.gen(function* () {
|
||||
Effect.flatMap(() =>
|
||||
Effect.gen(function* () {
|
||||
currentPhase = "pr";
|
||||
return yield* runPrStep(input.modelSelection, input.cwd, currentBranch);
|
||||
return yield* runPrStep(modelSelection, input.cwd, currentBranch);
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -23,6 +23,7 @@ import {
|
||||
Cache,
|
||||
Cause,
|
||||
Deferred,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
@@ -42,6 +43,7 @@ import {
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class KeybindingsConfigError extends Schema.TaggedErrorClass<KeybindingsConfigError>()(
|
||||
"KeybindingsConfigParseError",
|
||||
@@ -408,7 +410,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string {
|
||||
|
||||
const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS);
|
||||
|
||||
const RawKeybindingsEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown));
|
||||
const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown));
|
||||
const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
@@ -672,6 +674,7 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
Effect.tap(() => fs.makeDirectory(path.dirname(keybindingsConfigPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, keybindingsConfigPath)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new KeybindingsConfigError({
|
||||
@@ -817,16 +820,25 @@ const makeKeybindings = Effect.gen(function* () {
|
||||
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => {
|
||||
const isTargetConfigEvent =
|
||||
event.path === keybindingsConfigFile ||
|
||||
event.path === keybindingsConfigPath ||
|
||||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved;
|
||||
if (!isTargetConfigEvent) {
|
||||
return Effect.void;
|
||||
}
|
||||
return revalidateAndEmitSafely;
|
||||
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
|
||||
// Debounce watch events so the file is fully written before we read it.
|
||||
// Editors emit multiple events per save (truncate, write, rename) and
|
||||
// `fs.watch` can fire before the content has been flushed to disk.
|
||||
const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe(
|
||||
Stream.filter((event) => {
|
||||
return (
|
||||
event.path === keybindingsConfigFile ||
|
||||
event.path === keybindingsConfigPath ||
|
||||
path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved
|
||||
);
|
||||
}),
|
||||
Stream.debounce(Duration.millis(100)),
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkIn(watcherScope),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
|
||||
@@ -6,7 +6,6 @@ import * as ConfigProvider from "effect/ConfigProvider";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Stream from "effect/Stream";
|
||||
import * as Command from "effect/unstable/cli/Command";
|
||||
import { FetchHttpClient } from "effect/unstable/http";
|
||||
import { beforeEach } from "vitest";
|
||||
@@ -17,9 +16,8 @@ import { ServerConfig, type ServerConfigShape } from "./config";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { DEFAULT_SERVER_SETTINGS } from "@t3tools/contracts";
|
||||
import { Server, type ServerShape } from "./wsServer";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "./serverSettings";
|
||||
import { ServerSettingsService } from "./serverSettings";
|
||||
|
||||
const start = vi.fn(() => undefined);
|
||||
const stop = vi.fn(() => undefined);
|
||||
@@ -55,13 +53,7 @@ const testLayer = Layer.mergeAll(
|
||||
openBrowser: (_target: string) => Effect.void,
|
||||
openInEditor: () => Effect.void,
|
||||
} satisfies OpenShape),
|
||||
Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
updateSettings: () => Effect.succeed(DEFAULT_SERVER_SETTINGS),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape),
|
||||
ServerSettingsService.layerTest(),
|
||||
AnalyticsService.layerTest,
|
||||
FetchHttpClient.layer,
|
||||
NodeServices.layer,
|
||||
@@ -267,7 +259,7 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.port, 4666);
|
||||
assert.equal(resolvedConfig?.host, undefined);
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -309,6 +301,19 @@ it.layer(testLayer)("server CLI command", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses fixed loopback defaults in web mode", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli([], {
|
||||
T3CODE_MODE: "web",
|
||||
T3CODE_NO_BROWSER: "true",
|
||||
});
|
||||
|
||||
assert.equal(start.mock.calls.length, 1);
|
||||
assert.equal(resolvedConfig?.mode, "web");
|
||||
assert.equal(resolvedConfig?.host, "127.0.0.1");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("allows overriding desktop host with --host", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* runCli(["--host", "0.0.0.0"], {
|
||||
|
||||
+46
-17
@@ -22,13 +22,14 @@ import { Open } from "./open";
|
||||
import * as SqlitePersistence from "./persistence/Layers/Sqlite";
|
||||
import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
|
||||
import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
|
||||
import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
|
||||
import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry";
|
||||
import { Server } from "./wsServer";
|
||||
import { ServerLoggerLive } from "./serverLogger";
|
||||
import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
|
||||
import { readBootstrapEnvelope } from "./bootstrap";
|
||||
import { ServerSettingsLive } from "./serverSettings";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth";
|
||||
|
||||
export class StartupError extends Data.TaggedError("StartupError")<{
|
||||
readonly message: string;
|
||||
@@ -268,7 +269,7 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
Option.fromUndefinedOr(env.host),
|
||||
Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
|
||||
),
|
||||
() => (mode === "desktop" ? "127.0.0.1" : undefined),
|
||||
() => "127.0.0.1",
|
||||
);
|
||||
|
||||
const config: ServerConfigShape = {
|
||||
@@ -291,20 +292,28 @@ const ServerConfigLive = (input: CliInput) =>
|
||||
);
|
||||
|
||||
const LayerLive = (input: CliInput) =>
|
||||
Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderHealthLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(ServerConfigLive(input)),
|
||||
);
|
||||
(() => {
|
||||
const serverConfigLayer = ServerConfigLive(input);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
return Layer.empty.pipe(
|
||||
Layer.provideMerge(makeServerRuntimeServicesLayer()),
|
||||
Layer.provideMerge(makeServerProviderLayer()),
|
||||
Layer.provideMerge(ProviderRegistryLive),
|
||||
Layer.provideMerge(SqlitePersistence.layerConfig),
|
||||
Layer.provideMerge(ServerLoggerLive),
|
||||
Layer.provideMerge(AnalyticsServiceLayerLive),
|
||||
Layer.provideMerge(ServerSettingsLive),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
);
|
||||
})();
|
||||
|
||||
const isWildcardHost = (host: string | undefined): boolean =>
|
||||
host === "0.0.0.0" || host === "::" || host === "[::]";
|
||||
|
||||
const isLoopbackHost = (host: string | undefined): boolean =>
|
||||
host === "127.0.0.1" || host === "::1" || host === "[::1]" || host === "localhost";
|
||||
|
||||
const formatHostForUrl = (host: string): string =>
|
||||
host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
|
||||
|
||||
@@ -333,12 +342,11 @@ export const recordStartupHeartbeat = Effect.gen(function* () {
|
||||
});
|
||||
});
|
||||
|
||||
const makeServerProgram = (input: CliInput) =>
|
||||
const makeServerRuntimeProgram = (input: CliInput) =>
|
||||
Effect.gen(function* () {
|
||||
const cliConfig = yield* CliConfig;
|
||||
const { start, stopSignal } = yield* Server;
|
||||
const openDeps = yield* Open;
|
||||
yield* cliConfig.fixPath;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
|
||||
const config = yield* ServerConfig;
|
||||
|
||||
@@ -359,15 +367,29 @@ const makeServerProgram = (input: CliInput) =>
|
||||
config.host && !isWildcardHost(config.host)
|
||||
? `http://${formatHostForUrl(config.host)}:${config.port}`
|
||||
: localUrl;
|
||||
const browserBaseUrl =
|
||||
config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)
|
||||
? bindUrl
|
||||
: localUrl;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl(browserBaseUrl);
|
||||
const { authToken, devUrl, ...safeConfig } = config;
|
||||
yield* Effect.logInfo("T3 Code running", {
|
||||
...safeConfig,
|
||||
devUrl: devUrl?.toString(),
|
||||
authEnabled: Boolean(authToken),
|
||||
localUrl,
|
||||
pairingUrl,
|
||||
});
|
||||
|
||||
if (config.host && !isWildcardHost(config.host) && !isLoopbackHost(config.host)) {
|
||||
yield* Effect.logWarning("server is exposed beyond loopback", {
|
||||
host: config.host,
|
||||
bindUrl,
|
||||
});
|
||||
}
|
||||
|
||||
if (!config.noBrowser) {
|
||||
const target = config.devUrl?.toString() ?? bindUrl;
|
||||
const target = pairingUrl;
|
||||
yield* openDeps.openBrowser(target).pipe(
|
||||
Effect.catch(() =>
|
||||
Effect.logInfo("browser auto-open unavailable", {
|
||||
@@ -380,6 +402,13 @@ const makeServerProgram = (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.
|
||||
*/
|
||||
@@ -411,7 +440,7 @@ const noBrowserFlag = Flag.boolean("no-browser").pipe(
|
||||
Flag.optional,
|
||||
);
|
||||
const authTokenFlag = Flag.string("auth-token").pipe(
|
||||
Flag.withDescription("Auth token required for WebSocket connections."),
|
||||
Flag.withDescription("Legacy auth token for non-browser WebSocket clients."),
|
||||
Flag.withAlias("token"),
|
||||
Flag.optional,
|
||||
);
|
||||
|
||||
@@ -40,6 +40,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLaunch, {
|
||||
command: "code-insiders",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const vscodiumLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLaunch, {
|
||||
command: "codium",
|
||||
args: ["/tmp/workspace"],
|
||||
});
|
||||
|
||||
const zedLaunch = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -80,6 +98,24 @@ it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodeInsidersLineAndColumn, {
|
||||
command: "code-insiders",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
|
||||
"darwin",
|
||||
);
|
||||
assert.deepEqual(vscodiumLineAndColumn, {
|
||||
command: "codium",
|
||||
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
|
||||
});
|
||||
|
||||
const zedLineAndColumn = yield* resolveEditorLaunch(
|
||||
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
|
||||
"darwin",
|
||||
@@ -220,13 +256,14 @@ it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
|
||||
const path = yield* Path.Path;
|
||||
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
|
||||
|
||||
yield* fs.writeFileString(path.join(dir, "cursor.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
|
||||
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
|
||||
const editors = resolveAvailableEditors("win32", {
|
||||
PATH: dir,
|
||||
PATHEXT: ".COM;.EXE;.BAT;.CMD",
|
||||
});
|
||||
assert.deepEqual(editors, ["cursor", "file-manager"]);
|
||||
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -39,10 +39,8 @@ interface CommandAvailabilityOptions {
|
||||
|
||||
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
|
||||
|
||||
function shouldUseGotoFlag(editorId: EditorId, target: string): boolean {
|
||||
return (
|
||||
(editorId === "cursor" || editorId === "vscode") && LINE_COLUMN_SUFFIX_PATTERN.test(target)
|
||||
);
|
||||
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
|
||||
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
|
||||
}
|
||||
|
||||
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
|
||||
@@ -213,7 +211,7 @@ export const resolveEditorLaunch = Effect.fnUntraced(function* (
|
||||
}
|
||||
|
||||
if (editorDef.command) {
|
||||
return shouldUseGotoFlag(editorDef.id, input.cwd)
|
||||
return shouldUseGotoFlag(editorDef, input.cwd)
|
||||
? { command: editorDef.command, args: ["--goto", input.cwd] }
|
||||
: { command: editorDef.command, args: [input.cwd] };
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
ProviderCommandReactor,
|
||||
type ProviderCommandReactorShape,
|
||||
} from "../Services/ProviderCommandReactor.ts";
|
||||
import { ServerSettingsService, deriveProviderStartOptions } from "../../serverSettings.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
|
||||
type ProviderIntentEvent = Extract<
|
||||
OrchestrationEvent,
|
||||
@@ -251,18 +251,13 @@ const make = Effect.gen(function* () {
|
||||
readonly resumeCursor?: unknown;
|
||||
readonly provider?: ProviderKind;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* serverSettingsService.getSettings;
|
||||
const providerOptions = deriveProviderStartOptions(serverSettings);
|
||||
return yield* providerService.startSession(threadId, {
|
||||
threadId,
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
modelSelection: desiredModelSelection,
|
||||
...(providerOptions !== undefined ? { providerOptions } : {}),
|
||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
});
|
||||
providerService.startSession(threadId, {
|
||||
threadId,
|
||||
...(preferredProvider ? { provider: preferredProvider } : {}),
|
||||
...(effectiveCwd ? { cwd: effectiveCwd } : {}),
|
||||
modelSelection: desiredModelSelection,
|
||||
...(input?.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}),
|
||||
runtimeMode: desiredRuntimeMode,
|
||||
});
|
||||
|
||||
const bindSessionToThread = (session: ProviderSession) =>
|
||||
@@ -429,48 +424,39 @@ const make = Effect.gen(function* () {
|
||||
const oldBranch = input.branch;
|
||||
const cwd = input.worktreePath;
|
||||
const attachments = input.attachments ?? [];
|
||||
yield* textGeneration
|
||||
.generateBranchName({
|
||||
yield* Effect.gen(function* () {
|
||||
const { textGenerationModelSelection: modelSelection } =
|
||||
yield* serverSettingsService.getSettings;
|
||||
|
||||
const generated = yield* textGeneration.generateBranchName({
|
||||
cwd,
|
||||
message: input.messageText,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
modelSelection: yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => settings.textGenerationModelSelection,
|
||||
),
|
||||
})
|
||||
.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;
|
||||
modelSelection,
|
||||
});
|
||||
if (!generated) return;
|
||||
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return Effect.void;
|
||||
const targetBranch = buildGeneratedWorktreeBranchName(generated.branch);
|
||||
if (targetBranch === oldBranch) return;
|
||||
|
||||
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,
|
||||
}),
|
||||
);
|
||||
const renamed = yield* git.renameBranch({ cwd, oldBranch, newBranch: targetBranch });
|
||||
yield* orchestrationEngine.dispatch({
|
||||
type: "thread.meta.update",
|
||||
commandId: serverCommandId("worktree-branch-rename"),
|
||||
threadId: input.threadId,
|
||||
branch: renamed.branch,
|
||||
worktreePath: cwd,
|
||||
});
|
||||
}).pipe(
|
||||
Effect.catchCause((cause) =>
|
||||
Effect.logWarning("provider command reactor failed to generate or rename worktree branch", {
|
||||
threadId: input.threadId,
|
||||
cwd,
|
||||
oldBranch,
|
||||
cause: Cause.pretty(cause),
|
||||
}),
|
||||
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,7 +12,6 @@ import {
|
||||
ApprovalRequestId,
|
||||
CommandId,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
EventId,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
@@ -40,18 +39,11 @@ import {
|
||||
} from "../Services/OrchestrationEngine.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService, type ServerSettingsShape } from "../../serverSettings.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
|
||||
function makeTestServerSettingsLayer(overrides: Partial<ServerSettings> = {}) {
|
||||
const settings: ServerSettings = { ...DEFAULT_SERVER_SETTINGS, ...overrides };
|
||||
return Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed(settings),
|
||||
updateSettings: () => Effect.succeed(settings),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
return ServerSettingsService.layerTest(overrides);
|
||||
}
|
||||
|
||||
const asProjectId = (value: string): ProjectId => ProjectId.makeUnsafe(value);
|
||||
|
||||
@@ -188,7 +188,6 @@ describe("decider project scripts", () => {
|
||||
if (turnStartEvent?.type !== "thread.turn-start-requested") {
|
||||
return;
|
||||
}
|
||||
expect(turnStartEvent.payload.assistantDeliveryMode).toBe("buffered");
|
||||
expect(turnStartEvent.payload).toMatchObject({
|
||||
threadId: ThreadId.makeUnsafe("thread-1"),
|
||||
messageId: asMessageId("message-user-1"),
|
||||
|
||||
@@ -21,6 +21,7 @@ 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";
|
||||
@@ -168,6 +169,7 @@ function makeHarness(config?: {
|
||||
config?.baseDir ?? "/tmp",
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
),
|
||||
query,
|
||||
@@ -301,7 +303,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("keeps explicit claude permission mode over runtime-derived defaults", () => {
|
||||
it.effect("uses bypass permissions for full-access claude sessions", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
@@ -309,16 +311,11 @@ describe("ClaudeAdapterLive", () => {
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
providerOptions: {
|
||||
claudeAgent: {
|
||||
permissionMode: "plan",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.permissionMode, "plan");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, undefined);
|
||||
assert.equal(createInput?.options.permissionMode, "bypassPermissions");
|
||||
assert.equal(createInput?.options.allowDangerouslySkipPermissions, true);
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -350,7 +347,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("ignores unsupported max effort for Sonnet 4.6", () => {
|
||||
it.effect("falls back to default effort when unsupported max is requested for Sonnet 4.6", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
@@ -368,7 +365,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -535,7 +532,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
});
|
||||
|
||||
const createInput = harness.getLastCreateQueryInput();
|
||||
assert.equal(createInput?.options.effort, undefined);
|
||||
assert.equal(createInput?.options.effort, "high");
|
||||
const promptText = yield* Effect.promise(() => readFirstPromptText(createInput));
|
||||
assert.equal(promptText, "Ultrathink:\nInvestigate the edge cases");
|
||||
}).pipe(
|
||||
@@ -1195,6 +1192,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
},
|
||||
}).pipe(
|
||||
Layer.provideMerge(ServerConfig.layerTest("/tmp/claude-adapter-test", "/tmp")),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
|
||||
|
||||
@@ -41,9 +41,9 @@ import {
|
||||
ClaudeCodeEffort,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
hasEffortLevel,
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelCapabilities,
|
||||
resolveApiModelId,
|
||||
resolveEffort,
|
||||
trimOrNull,
|
||||
} from "@t3tools/shared/model";
|
||||
import {
|
||||
@@ -63,6 +63,8 @@ import {
|
||||
|
||||
import { resolveAttachmentPath } from "../../attachmentStore.ts";
|
||||
import { ServerConfig } from "../../config.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "./ClaudeProvider.ts";
|
||||
import {
|
||||
ProviderAdapterProcessError,
|
||||
ProviderAdapterRequestError,
|
||||
@@ -353,19 +355,6 @@ 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;
|
||||
@@ -522,16 +511,15 @@ const CLAUDE_SETTING_SOURCES = [
|
||||
function buildPromptText(input: ProviderSendTurnInput): string {
|
||||
const rawEffort =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.options?.effort : null;
|
||||
const requestedEffort = trimOrNull(rawEffort);
|
||||
const claudeModel =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection.model : undefined;
|
||||
const caps = getModelCapabilities("claudeAgent", claudeModel);
|
||||
const caps = getClaudeModelCapabilities(claudeModel);
|
||||
|
||||
// For prompt injection, we check if the raw effort is a prompt-injected level (e.g. "ultrathink").
|
||||
// resolveEffort strips prompt-injected values (returning the default instead), so we check the raw value directly.
|
||||
const trimmedEffort = trimOrNull(rawEffort);
|
||||
const promptEffort =
|
||||
requestedEffort === "ultrathink" && caps.reasoningEffortLevels.length > 0
|
||||
? "ultrathink"
|
||||
: requestedEffort && hasEffortLevel(caps, requestedEffort)
|
||||
? requestedEffort
|
||||
: null;
|
||||
trimmedEffort && caps.promptInjectedEffortLevels.includes(trimmedEffort) ? trimmedEffort : null;
|
||||
return applyClaudePromptEffortPrefix(input.input?.trim() ?? "", promptEffort);
|
||||
}
|
||||
|
||||
@@ -943,6 +931,7 @@ 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));
|
||||
@@ -2727,13 +2716,25 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
}),
|
||||
);
|
||||
|
||||
const providerOptions = input.providerOptions?.claudeAgent;
|
||||
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 modelSelection =
|
||||
input.modelSelection?.provider === "claudeAgent" ? input.modelSelection : undefined;
|
||||
const requestedEffort = trimOrNull(modelSelection?.options?.effort ?? null);
|
||||
const caps = getModelCapabilities("claudeAgent", modelSelection?.model);
|
||||
const effort =
|
||||
requestedEffort && hasEffortLevel(caps, requestedEffort) ? requestedEffort : null;
|
||||
const caps = getClaudeModelCapabilities(modelSelection?.model);
|
||||
const apiModelId = modelSelection ? resolveApiModelId(modelSelection) : undefined;
|
||||
const effort = (resolveEffort(caps, modelSelection?.options?.effort) ??
|
||||
null) as ClaudeCodeEffort | null;
|
||||
const fastMode = modelSelection?.options?.fastMode === true && caps.supportsFastMode;
|
||||
const thinking =
|
||||
typeof modelSelection?.options?.thinking === "boolean" && caps.supportsThinkingToggle
|
||||
@@ -2741,8 +2742,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
: undefined;
|
||||
const effectiveEffort = getEffectiveClaudeCodeEffort(effort);
|
||||
const permissionMode =
|
||||
toPermissionMode(providerOptions?.permissionMode) ??
|
||||
(input.runtimeMode === "full-access" ? "bypassPermissions" : undefined);
|
||||
input.runtimeMode === "full-access" ? "bypassPermissions" : undefined;
|
||||
const settings = {
|
||||
...(typeof thinking === "boolean" ? { alwaysThinkingEnabled: thinking } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
@@ -2750,17 +2750,14 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
|
||||
const queryOptions: ClaudeQueryOptions = {
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
pathToClaudeCodeExecutable: providerOptions?.binaryPath ?? "claude",
|
||||
...(apiModelId ? { model: apiModelId } : {}),
|
||||
pathToClaudeCodeExecutable: claudeBinaryPath,
|
||||
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 } : {}),
|
||||
@@ -2847,13 +2844,10 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
threadId,
|
||||
payload: {
|
||||
config: {
|
||||
...(modelSelection?.model ? { model: modelSelection.model } : {}),
|
||||
...(apiModelId ? { model: apiModelId } : {}),
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(providerOptions?.maxThinkingTokens !== undefined
|
||||
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
|
||||
: {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
@@ -2903,8 +2897,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
}
|
||||
|
||||
if (modelSelection?.model) {
|
||||
const apiModelId = resolveApiModelId(modelSelection);
|
||||
yield* Effect.tryPromise({
|
||||
try: () => context.query.setModel(modelSelection.model),
|
||||
try: () => context.query.setModel(apiModelId),
|
||||
catch: (cause) => toRequestError(input.threadId, "turn/setModel", cause),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,400 @@
|
||||
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 { resolveContextWindow, resolveEffort } 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,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
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,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeClaudeModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const caps = getClaudeModelCapabilities(model);
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly 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,6 +22,7 @@ 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";
|
||||
@@ -151,6 +152,7 @@ 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),
|
||||
),
|
||||
@@ -201,6 +203,7 @@ 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",
|
||||
@@ -216,6 +219,7 @@ 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),
|
||||
),
|
||||
@@ -284,6 +288,7 @@ 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),
|
||||
),
|
||||
|
||||
@@ -38,6 +38,7 @@ 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;
|
||||
@@ -1342,25 +1343,39 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
}
|
||||
}),
|
||||
);
|
||||
const serverSettingsService = yield* ServerSettingsService;
|
||||
|
||||
const startSession: CodexAdapterShape["startSession"] = (input) => {
|
||||
const startSession: CodexAdapterShape["startSession"] = Effect.fn(function* (input) {
|
||||
if (input.provider !== undefined && input.provider !== PROVIDER) {
|
||||
return Effect.fail(
|
||||
new ProviderAdapterValidationError({
|
||||
provider: PROVIDER,
|
||||
operation: "startSession",
|
||||
issue: `Expected provider '${PROVIDER}' but received '${input.provider}'.`,
|
||||
}),
|
||||
);
|
||||
return yield* 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 }
|
||||
: {}),
|
||||
@@ -1369,7 +1384,7 @@ const makeCodexAdapter = (options?: CodexAdapterLiveOptions) =>
|
||||
: {}),
|
||||
};
|
||||
|
||||
return Effect.tryPromise({
|
||||
return yield* Effect.tryPromise({
|
||||
try: () => manager.startSession(managerInput),
|
||||
catch: (cause) =>
|
||||
new ProviderAdapterProcessError({
|
||||
@@ -1378,8 +1393,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* () {
|
||||
|
||||
@@ -0,0 +1,537 @@
|
||||
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 { resolveEffort } 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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptions(
|
||||
model: string | null | undefined,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const caps = getCodexModelCapabilities(model);
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly 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,
|
||||
});
|
||||
}),
|
||||
);
|
||||
@@ -1,640 +0,0 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,603 +0,0 @@
|
||||
/**
|
||||
* 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;
|
||||
}),
|
||||
);
|
||||
@@ -0,0 +1,879 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* 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,8 +42,11 @@ 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);
|
||||
@@ -251,6 +254,7 @@ function makeProviderServiceLayer() {
|
||||
makeProviderServiceLive().pipe(
|
||||
Layer.provide(providerAdapterLayer),
|
||||
Layer.provide(directoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
),
|
||||
directoryLayer,
|
||||
@@ -267,6 +271,55 @@ 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* () {
|
||||
@@ -299,6 +352,7 @@ 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),
|
||||
);
|
||||
|
||||
@@ -358,6 +412,7 @@ it.effect(
|
||||
const firstProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, firstRegistry)),
|
||||
Layer.provide(firstDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
const updatedResumeCursor = {
|
||||
@@ -409,6 +464,7 @@ it.effect(
|
||||
const secondProviderLayer = makeProviderServiceLive().pipe(
|
||||
Layer.provide(Layer.succeed(ProviderAdapterRegistry, secondRegistry)),
|
||||
Layer.provide(secondDirectoryLayer),
|
||||
Layer.provide(defaultServerSettingsLayer),
|
||||
Layer.provide(AnalyticsService.layerTest),
|
||||
);
|
||||
|
||||
@@ -769,6 +825,7 @@ 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),
|
||||
);
|
||||
|
||||
@@ -801,6 +858,7 @@ 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,6 +33,7 @@ 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;
|
||||
@@ -91,7 +92,6 @@ function toRuntimePayloadFromSession(
|
||||
session: ProviderSession,
|
||||
extra?: {
|
||||
readonly modelSelection?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
@@ -102,7 +102,6 @@ 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 }
|
||||
@@ -120,17 +119,6 @@ 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 {
|
||||
@@ -146,6 +134,7 @@ 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
|
||||
@@ -173,7 +162,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
threadId: ThreadId,
|
||||
extra?: {
|
||||
readonly modelSelection?: unknown;
|
||||
readonly providerOptions?: unknown;
|
||||
readonly lastRuntimeEvent?: string;
|
||||
readonly lastRuntimeEventAt?: string;
|
||||
},
|
||||
@@ -239,14 +227,12 @@ 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",
|
||||
});
|
||||
@@ -308,6 +294,21 @@ 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 ??
|
||||
@@ -329,7 +330,6 @@ const makeProviderService = (options?: ProviderServiceLiveOptions) =>
|
||||
|
||||
yield* upsertSessionBinding(session, threadId, {
|
||||
modelSelection: input.modelSelection,
|
||||
providerOptions: input.providerOptions,
|
||||
});
|
||||
yield* analytics.record("provider.session.started", {
|
||||
provider: session.provider,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
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",
|
||||
) {}
|
||||
@@ -0,0 +1,9 @@
|
||||
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",
|
||||
) {}
|
||||
@@ -1,22 +0,0 @@
|
||||
/**
|
||||
* 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",
|
||||
) {}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* 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",
|
||||
) {}
|
||||
@@ -0,0 +1,8 @@
|
||||
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>;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
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;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
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,
|
||||
),
|
||||
);
|
||||
@@ -24,6 +24,7 @@ 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";
|
||||
@@ -54,7 +55,11 @@ const makeRuntimePtyAdapterLayer = () =>
|
||||
export function makeServerProviderLayer(): Layer.Layer<
|
||||
ProviderService,
|
||||
ProviderUnsupportedError,
|
||||
SqlClient.SqlClient | ServerConfig | FileSystem.FileSystem | AnalyticsService
|
||||
| SqlClient.SqlClient
|
||||
| ServerConfig
|
||||
| ServerSettingsService
|
||||
| FileSystem.FileSystem
|
||||
| AnalyticsService
|
||||
> {
|
||||
return Effect.gen(function* () {
|
||||
const { providerEventLogPath } = yield* ServerConfig;
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
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 { ServerConfig } from "./config";
|
||||
import { ServerSettingsLive, ServerSettingsService } from "./serverSettings";
|
||||
|
||||
const makeServerSettingsLayer = () =>
|
||||
ServerSettingsLive.pipe(
|
||||
Layer.provideMerge(
|
||||
Layer.fresh(
|
||||
ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3code-server-settings-test-",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
it.effect("decodes nested settings patches", () =>
|
||||
Effect.sync(() => {
|
||||
const decodePatch = Schema.decodeUnknownSync(ServerSettingsPatch);
|
||||
|
||||
assert.deepEqual(decodePatch({ providers: { codex: { binaryPath: "/tmp/codex" } } }), {
|
||||
providers: { codex: { binaryPath: "/tmp/codex" } },
|
||||
});
|
||||
|
||||
assert.deepEqual(
|
||||
decodePatch({
|
||||
textGenerationModelSelection: {
|
||||
options: {
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
}),
|
||||
{
|
||||
textGenerationModelSelection: {
|
||||
options: {
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("deep merges nested settings updates without dropping siblings", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: "/usr/local/bin/codex",
|
||||
homePath: "/Users/julius/.codex",
|
||||
},
|
||||
claudeAgent: {
|
||||
binaryPath: "/usr/local/bin/claude",
|
||||
customModels: ["claude-custom"],
|
||||
},
|
||||
},
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
providers: {
|
||||
codex: {
|
||||
binaryPath: "/opt/homebrew/bin/codex",
|
||||
},
|
||||
},
|
||||
textGenerationModelSelection: {
|
||||
options: {
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
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"],
|
||||
});
|
||||
assert.deepEqual(next.textGenerationModelSelection, {
|
||||
provider: "codex",
|
||||
model: DEFAULT_SERVER_SETTINGS.textGenerationModelSelection.model,
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
});
|
||||
}).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())),
|
||||
);
|
||||
});
|
||||
@@ -11,14 +11,17 @@
|
||||
* @module ServerSettings
|
||||
*/
|
||||
import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
type ProviderStartOptions,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
ServerSettings,
|
||||
type ServerSettingsPatch,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
Cache,
|
||||
Deferred,
|
||||
Duration,
|
||||
Effect,
|
||||
Exit,
|
||||
FileSystem,
|
||||
@@ -27,13 +30,15 @@ import {
|
||||
PubSub,
|
||||
Ref,
|
||||
Schema,
|
||||
SchemaGetter,
|
||||
SchemaIssue,
|
||||
Scope,
|
||||
ServiceMap,
|
||||
Stream,
|
||||
} from "effect";
|
||||
import * as Semaphore from "effect/Semaphore";
|
||||
import { ServerConfig } from "./config";
|
||||
import { type DeepPartial, deepMerge } from "@t3tools/shared/Struct";
|
||||
import { fromLenientJson } from "@t3tools/shared/schemaJson";
|
||||
|
||||
export class ServerSettingsError extends Schema.TaggedErrorClass<ServerSettingsError>()(
|
||||
"ServerSettingsError",
|
||||
@@ -71,54 +76,87 @@ export class ServerSettingsService extends ServiceMap.Service<
|
||||
ServerSettingsService,
|
||||
ServerSettingsShape
|
||||
>()("t3/serverSettings/ServerSettingsService") {
|
||||
static readonly layerTest = (overrides: Partial<ServerSettings> = {}) =>
|
||||
Layer.succeed(ServerSettingsService, {
|
||||
start: Effect.void,
|
||||
ready: Effect.void,
|
||||
getSettings: Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
|
||||
updateSettings: () => Effect.succeed({ ...DEFAULT_SERVER_SETTINGS, ...overrides }),
|
||||
streamChanges: Stream.empty,
|
||||
} satisfies ServerSettingsShape);
|
||||
static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
|
||||
Layer.effect(
|
||||
ServerSettingsService,
|
||||
Effect.gen(function* () {
|
||||
const currentSettingsRef = yield* Ref.make<ServerSettings>(
|
||||
deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
|
||||
);
|
||||
|
||||
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;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const ServerSettingsJson = fromLenientJson(ServerSettings);
|
||||
|
||||
const PROVIDER_ORDER: readonly ProviderKind[] = ["codex", "claudeAgent"];
|
||||
|
||||
/**
|
||||
* Derive `ProviderStartOptions` from server settings.
|
||||
* Replaces the client-side `getProviderStartOptions()` function.
|
||||
* 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.
|
||||
*/
|
||||
export function deriveProviderStartOptions(
|
||||
settings: ServerSettings,
|
||||
): ProviderStartOptions | undefined {
|
||||
const providerOptions: ProviderStartOptions = {
|
||||
...(settings.codex
|
||||
? {
|
||||
codex: {
|
||||
...(settings.codex.binaryPath ? { binaryPath: settings.codex.binaryPath } : {}),
|
||||
...(settings.codex.homePath ? { homePath: settings.codex.homePath } : {}),
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
...(settings.claude?.binaryPath
|
||||
? {
|
||||
claudeAgent: {
|
||||
binaryPath: settings.claude.binaryPath,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
|
||||
const selection = settings.textGenerationModelSelection;
|
||||
if (settings.providers[selection.provider].enabled) {
|
||||
return settings;
|
||||
}
|
||||
|
||||
return Object.keys(providerOptions).length > 0 ? providerOptions : undefined;
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
const ServerSettingsJson = Schema.fromJsonString(ServerSettings);
|
||||
const PrettyJsonString = SchemaGetter.parseJson<string>().compose(
|
||||
SchemaGetter.stringifyJson({ space: 2 }),
|
||||
);
|
||||
const ServerSettingsPrettyJson = ServerSettingsJson.pipe(
|
||||
Schema.encode({
|
||||
decode: PrettyJsonString,
|
||||
encode: PrettyJsonString,
|
||||
}),
|
||||
);
|
||||
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 makeServerSettings = Effect.gen(function* () {
|
||||
const { settingsPath } = yield* ServerConfig;
|
||||
@@ -182,12 +220,13 @@ 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 Schema.encodeEffect(ServerSettingsPrettyJson)(settings).pipe(
|
||||
Effect.map((encoded) => `${encoded}\n`),
|
||||
return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
|
||||
Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
|
||||
Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
|
||||
Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
|
||||
Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ServerSettingsError({
|
||||
@@ -225,25 +264,33 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
|
||||
const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
|
||||
|
||||
yield* Stream.runForEach(fs.watch(settingsDir), (event) => {
|
||||
const isTargetEvent =
|
||||
event.path === settingsFile ||
|
||||
event.path === settingsPath ||
|
||||
pathService.resolve(settingsDir, event.path) === settingsPathResolved;
|
||||
if (!isTargetEvent) {
|
||||
return Effect.void;
|
||||
}
|
||||
return revalidateAndEmitSafely;
|
||||
}).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid);
|
||||
// Debounce watch events so the file is fully written before we read it.
|
||||
// Editors emit multiple events per save (truncate, write, rename) and
|
||||
// `fs.watch` can fire before the content has been flushed to disk.
|
||||
const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
|
||||
Stream.filter((event) => {
|
||||
return (
|
||||
event.path === settingsFile ||
|
||||
event.path === settingsPath ||
|
||||
pathService.resolve(settingsDir, event.path) === settingsPathResolved
|
||||
);
|
||||
}),
|
||||
Stream.debounce(Duration.millis(100)),
|
||||
);
|
||||
|
||||
yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
|
||||
Effect.ignoreCause({ log: true }),
|
||||
Effect.forkIn(watcherScope),
|
||||
Effect.asVoid,
|
||||
);
|
||||
});
|
||||
|
||||
const start = Effect.gen(function* () {
|
||||
const alreadyStarted = yield* Ref.get(startedRef);
|
||||
if (alreadyStarted) {
|
||||
const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
|
||||
if (!shouldStart) {
|
||||
return yield* Deferred.await(startedDeferred);
|
||||
}
|
||||
|
||||
yield* Ref.set(startedRef, true);
|
||||
const startup = Effect.gen(function* () {
|
||||
yield* startWatcher;
|
||||
yield* Cache.invalidate(settingsCache, cacheKey);
|
||||
@@ -262,20 +309,29 @@ const makeServerSettings = Effect.gen(function* () {
|
||||
return {
|
||||
start,
|
||||
ready: Deferred.await(startedDeferred),
|
||||
getSettings: getSettingsFromCache,
|
||||
getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)),
|
||||
updateSettings: (patch) =>
|
||||
writeSemaphore.withPermits(1)(
|
||||
Effect.gen(function* () {
|
||||
const current = yield* getSettingsFromCache;
|
||||
const next: ServerSettings = { ...current, ...patch };
|
||||
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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
yield* writeSettingsAtomically(next);
|
||||
yield* Cache.set(settingsCache, cacheKey, next);
|
||||
yield* emitChange(next);
|
||||
return next;
|
||||
return resolveTextGenerationProvider(next);
|
||||
}),
|
||||
),
|
||||
get streamChanges() {
|
||||
return Stream.fromPubSub(changesPubSub);
|
||||
return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider));
|
||||
},
|
||||
} satisfies ServerSettingsShape;
|
||||
});
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Http from "node:http";
|
||||
import fs from "node:fs";
|
||||
import net from "node:net";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
@@ -13,18 +14,20 @@ import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serve
|
||||
|
||||
import {
|
||||
DEFAULT_TERMINAL_ID,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
EDITORS,
|
||||
EventId,
|
||||
ORCHESTRATION_WS_CHANNELS,
|
||||
ORCHESTRATION_WS_METHODS,
|
||||
ProviderItemId,
|
||||
type ServerSettings,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WebSocketResponse,
|
||||
type ProviderRuntimeEvent,
|
||||
type ServerProviderStatus,
|
||||
type ServerProvider,
|
||||
type KeybindingsConfig,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type WsPushChannel,
|
||||
@@ -45,7 +48,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 { ProviderHealth, type ProviderHealthShape } from "./provider/Services/ProviderHealth";
|
||||
import { ProviderRegistry, type ProviderRegistryShape } from "./provider/Services/ProviderRegistry";
|
||||
import { Open, type OpenShape } from "./open";
|
||||
import { GitManager, type GitManagerShape } from "./git/Services/GitManager.ts";
|
||||
import type { GitCoreShape } from "./git/Services/GitCore.ts";
|
||||
@@ -54,6 +57,7 @@ import { GitCommandError, GitManagerError } from "./git/Errors.ts";
|
||||
import { MigrationError } from "@effect/sql-sqlite-bun/SqliteMigrator";
|
||||
import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
|
||||
import { ServerSettingsService } from "./serverSettings.ts";
|
||||
import { BrowserAuth, BrowserAuthLive } from "./browserAuth.ts";
|
||||
|
||||
const asEventId = (value: string): EventId => EventId.makeUnsafe(value);
|
||||
const asProviderItemId = (value: string): ProviderItemId => ProviderItemId.makeUnsafe(value);
|
||||
@@ -65,20 +69,27 @@ const defaultOpenService: OpenShape = {
|
||||
openInEditor: () => Effect.void,
|
||||
};
|
||||
|
||||
const defaultProviderStatuses: ReadonlyArray<ServerProviderStatus> = [
|
||||
const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
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 defaultProviderHealthService: ProviderHealthShape = {
|
||||
getStatuses: Effect.succeed(defaultProviderStatuses),
|
||||
const defaultProviderRegistryService: ProviderRegistryShape = {
|
||||
getProviders: Effect.succeed(defaultProviderStatuses),
|
||||
refresh: () => Effect.succeed(defaultProviderStatuses),
|
||||
streamChanges: Stream.empty,
|
||||
};
|
||||
|
||||
const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
@@ -236,6 +247,8 @@ interface SocketChannels {
|
||||
}
|
||||
|
||||
const channelsBySocket = new WeakMap<WebSocket, SocketChannels>();
|
||||
let currentBootstrapToken: string | null = null;
|
||||
let currentBrowserCookie: string | null = null;
|
||||
|
||||
function enqueue<T>(channel: MessageChannel<T>, item: T) {
|
||||
const waiter = channel.waiters.shift();
|
||||
@@ -281,10 +294,46 @@ function asWebSocketResponse(message: unknown): WebSocketResponse | null {
|
||||
return message as WebSocketResponse;
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
interface ConnectWsOptions {
|
||||
readonly token?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
async function pairBrowserSession(
|
||||
port: number,
|
||||
origin = `http://127.0.0.1:${port}`,
|
||||
): Promise<string> {
|
||||
if (!currentBootstrapToken) {
|
||||
throw new Error("Browser bootstrap token not initialized");
|
||||
}
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: origin,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
if (response.statusCode !== 204) {
|
||||
throw new Error(`Browser bootstrap failed with status ${response.statusCode}`);
|
||||
}
|
||||
|
||||
const setCookie = response.headers["set-cookie"];
|
||||
const cookieHeader = Array.isArray(setCookie) ? setCookie[0] : setCookie;
|
||||
if (!cookieHeader) {
|
||||
throw new Error("Browser bootstrap missing auth cookie");
|
||||
}
|
||||
|
||||
return cookieHeader.split(";", 1)[0] ?? "";
|
||||
}
|
||||
|
||||
function connectWsOnce(port: number, options: ConnectWsOptions = {}): Promise<WebSocket> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const query = token ? `?token=${encodeURIComponent(token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`);
|
||||
const query = options.token ? `?token=${encodeURIComponent(options.token)}` : "";
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${port}/${query}`, {
|
||||
headers: options.headers,
|
||||
});
|
||||
const channels: SocketChannels = {
|
||||
push: { queue: [], waiters: [] },
|
||||
response: { queue: [], waiters: [] },
|
||||
@@ -308,12 +357,25 @@ function connectWsOnce(port: number, token?: string): Promise<WebSocket> {
|
||||
});
|
||||
}
|
||||
|
||||
async function connectWs(port: number, token?: string, attempts = 5): Promise<WebSocket> {
|
||||
async function connectWs(
|
||||
port: number,
|
||||
options: ConnectWsOptions = {},
|
||||
attempts = 5,
|
||||
): Promise<WebSocket> {
|
||||
const normalizedOptions =
|
||||
options.token || options.headers
|
||||
? options
|
||||
: {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: (currentBrowserCookie ??= await pairBrowserSession(port)),
|
||||
},
|
||||
};
|
||||
let lastError: unknown = new Error("WebSocket connection failed");
|
||||
|
||||
for (let attempt = 0; attempt < attempts; attempt += 1) {
|
||||
try {
|
||||
return await connectWsOnce(port, token);
|
||||
return await connectWsOnce(port, normalizedOptions);
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
if (attempt < attempts - 1) {
|
||||
@@ -328,9 +390,9 @@ async function connectWs(port: number, token?: string, attempts = 5): Promise<We
|
||||
/** Connect and wait for the server.welcome push. Returns [ws, welcomeData]. */
|
||||
async function connectAndAwaitWelcome(
|
||||
port: number,
|
||||
token?: string,
|
||||
options: ConnectWsOptions = {},
|
||||
): Promise<[WebSocket, WsPushMessage<typeof WS_CHANNELS.serverWelcome>]> {
|
||||
const ws = await connectWs(port, token);
|
||||
const ws = await connectWs(port, options);
|
||||
const welcome = await waitForPush(ws, WS_CHANNELS.serverWelcome);
|
||||
return [ws, welcome];
|
||||
}
|
||||
@@ -402,14 +464,20 @@ async function rewriteKeybindingsAndWaitForPush(
|
||||
async function requestPath(
|
||||
port: number,
|
||||
requestPath: string,
|
||||
): Promise<{ statusCode: number; body: string }> {
|
||||
options: {
|
||||
readonly method?: string;
|
||||
readonly headers?: Record<string, string>;
|
||||
readonly body?: string;
|
||||
} = {},
|
||||
): Promise<{ statusCode: number; body: string; headers: Http.IncomingHttpHeaders }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = Http.request(
|
||||
{
|
||||
hostname: "127.0.0.1",
|
||||
port,
|
||||
path: requestPath,
|
||||
method: "GET",
|
||||
method: options.method ?? "GET",
|
||||
headers: options.headers,
|
||||
},
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
@@ -420,11 +488,15 @@ async function requestPath(
|
||||
resolve({
|
||||
statusCode: res.statusCode ?? 0,
|
||||
body: Buffer.concat(chunks).toString("utf8"),
|
||||
headers: res.headers,
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
req.once("error", reject);
|
||||
if (options.body) {
|
||||
req.write(options.body);
|
||||
}
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
@@ -474,6 +546,24 @@ describe("WebSocket Server", () => {
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function reserveLoopbackPort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const server = net.createServer();
|
||||
server.once("error", reject);
|
||||
server.listen(0, "127.0.0.1", () => {
|
||||
const address = server.address();
|
||||
const port = typeof address === "object" && address !== null ? address.port : 0;
|
||||
server.close((error) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(port);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function createTestServer(
|
||||
options: {
|
||||
persistenceLayer?: Layer.Layer<
|
||||
@@ -488,11 +578,12 @@ describe("WebSocket Server", () => {
|
||||
baseDir?: string;
|
||||
staticDir?: string;
|
||||
providerLayer?: Layer.Layer<ProviderService, never>;
|
||||
providerHealth?: ProviderHealthShape;
|
||||
providerRegistry?: ProviderRegistryShape;
|
||||
open?: OpenShape;
|
||||
gitManager?: GitManagerShape;
|
||||
gitCore?: Pick<GitCoreShape, "listBranches" | "initRepo" | "pullCurrentBranch">;
|
||||
terminalManager?: TerminalManagerShape;
|
||||
serverSettings?: Partial<ServerSettings>;
|
||||
} = {},
|
||||
): Promise<Http.Server> {
|
||||
if (serverScope) {
|
||||
@@ -502,18 +593,19 @@ describe("WebSocket Server", () => {
|
||||
const baseDir = options.baseDir ?? makeTempDir("t3code-ws-base-");
|
||||
const devUrl = options.devUrl ? new URL(options.devUrl) : undefined;
|
||||
const derivedPaths = deriveServerPathsSync(baseDir, devUrl);
|
||||
const reservedPort = await reserveLoopbackPort();
|
||||
const scope = await Effect.runPromise(Scope.make("sequential"));
|
||||
const persistenceLayer = options.persistenceLayer ?? SqlitePersistenceMemory;
|
||||
const providerLayer = options.providerLayer ?? makeServerProviderLayer();
|
||||
const providerHealthLayer = Layer.succeed(
|
||||
ProviderHealth,
|
||||
options.providerHealth ?? defaultProviderHealthService,
|
||||
const providerRegistryLayer = Layer.succeed(
|
||||
ProviderRegistry,
|
||||
options.providerRegistry ?? defaultProviderRegistryService,
|
||||
);
|
||||
const openLayer = Layer.succeed(Open, options.open ?? defaultOpenService);
|
||||
const serverConfigLayer = Layer.succeed(ServerConfig, {
|
||||
mode: "web",
|
||||
port: 0,
|
||||
host: undefined,
|
||||
port: reservedPort,
|
||||
host: "127.0.0.1",
|
||||
cwd: options.cwd ?? "/test/project",
|
||||
baseDir,
|
||||
...derivedPaths,
|
||||
@@ -524,6 +616,7 @@ describe("WebSocket Server", () => {
|
||||
autoBootstrapProjectFromCwd: options.autoBootstrapProjectFromCwd ?? false,
|
||||
logWebSocketEvents: options.logWebSocketEvents ?? Boolean(options.devUrl),
|
||||
} satisfies ServerConfigShape);
|
||||
const browserAuthLayer = BrowserAuthLive.pipe(Layer.provide(serverConfigLayer));
|
||||
const infrastructureLayer = providerLayer.pipe(Layer.provideMerge(persistenceLayer));
|
||||
const runtimeOverrides = Layer.mergeAll(
|
||||
options.gitManager ? Layer.succeed(GitManager, options.gitManager) : Layer.empty,
|
||||
@@ -544,16 +637,26 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
const dependenciesLayer = Layer.empty.pipe(
|
||||
Layer.provideMerge(runtimeLayer),
|
||||
Layer.provideMerge(providerHealthLayer),
|
||||
Layer.provideMerge(providerRegistryLayer),
|
||||
Layer.provideMerge(openLayer),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest()),
|
||||
Layer.provideMerge(ServerSettingsService.layerTest(options.serverSettings)),
|
||||
Layer.provideMerge(serverConfigLayer),
|
||||
Layer.provideMerge(browserAuthLayer),
|
||||
Layer.provideMerge(AnalyticsService.layerTest),
|
||||
Layer.provideMerge(NodeServices.layer),
|
||||
);
|
||||
const runtimeServices = await Effect.runPromise(
|
||||
Layer.build(dependenciesLayer).pipe(Scope.provide(scope)),
|
||||
);
|
||||
currentBrowserCookie = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBootstrapToken = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const pairingUrl = yield* browserAuth.getPairingUrl("http://pair.test");
|
||||
return new URL(pairingUrl).hash.replace(/^#t3_bootstrap=/, "");
|
||||
}).pipe(Effect.provide(runtimeServices)),
|
||||
);
|
||||
|
||||
try {
|
||||
const runtime = await Effect.runPromise(
|
||||
@@ -581,6 +684,8 @@ describe("WebSocket Server", () => {
|
||||
connections.length = 0;
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
currentBootstrapToken = null;
|
||||
currentBrowserCookie = null;
|
||||
for (const dir of tempDirs.splice(0, tempDirs.length)) {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -860,6 +965,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
settings: defaultServerSettings,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -885,6 +991,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
settings: defaultServerSettings,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
|
||||
@@ -921,6 +1028,7 @@ describe("WebSocket Server", () => {
|
||||
],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
settings: defaultServerSettings,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
expect(fs.readFileSync(keybindingsPath, "utf8")).toBe("{ not-json");
|
||||
@@ -954,7 +1062,7 @@ describe("WebSocket Server", () => {
|
||||
keybindingsConfigPath: string;
|
||||
keybindings: ResolvedKeybindingsConfig;
|
||||
issues: Array<{ kind: string; index?: number; message: string }>;
|
||||
providers: ReadonlyArray<ServerProviderStatus>;
|
||||
providers: ReadonlyArray<ServerProvider>;
|
||||
availableEditors: unknown;
|
||||
};
|
||||
expect(result.cwd).toBe("/my/workspace");
|
||||
@@ -1002,7 +1110,6 @@ describe("WebSocket Server", () => {
|
||||
);
|
||||
expect(malformedPush.data).toEqual({
|
||||
issues: [{ kind: "keybindings.malformed-config", message: expect.any(String) }],
|
||||
providers: defaultProviderStatuses,
|
||||
});
|
||||
|
||||
const successPush = await rewriteKeybindingsAndWaitForPush(
|
||||
@@ -1011,7 +1118,7 @@ describe("WebSocket Server", () => {
|
||||
"[]",
|
||||
(push) => Array.isArray(push.data.issues) && push.data.issues.length === 0,
|
||||
);
|
||||
expect(successPush.data).toEqual({ issues: [], providers: defaultProviderStatuses });
|
||||
expect(successPush.data).toEqual({ issues: [] });
|
||||
});
|
||||
|
||||
it("routes shell.openInEditor through the injected open service", async () => {
|
||||
@@ -1071,6 +1178,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
settings: defaultServerSettings,
|
||||
});
|
||||
expectAvailableEditors((response.result as { availableEditors: unknown }).availableEditors);
|
||||
});
|
||||
@@ -1119,6 +1227,7 @@ describe("WebSocket Server", () => {
|
||||
issues: [],
|
||||
providers: defaultProviderStatuses,
|
||||
availableEditors: expect.any(Array),
|
||||
settings: defaultServerSettings,
|
||||
});
|
||||
expectAvailableEditors(
|
||||
(configResponse.result as { availableEditors: unknown }).availableEditors,
|
||||
@@ -1275,6 +1384,7 @@ describe("WebSocket Server", () => {
|
||||
server = await createTestServer({
|
||||
cwd: "/test",
|
||||
providerLayer,
|
||||
serverSettings: { enableAssistantStreaming: true },
|
||||
});
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
@@ -1325,7 +1435,6 @@ describe("WebSocket Server", () => {
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
},
|
||||
assistantDeliveryMode: "streaming",
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: "default",
|
||||
createdAt,
|
||||
@@ -1852,10 +1961,6 @@ describe("WebSocket Server", () => {
|
||||
actionId: "client-action-1",
|
||||
cwd: "/test",
|
||||
action: "commit_push",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
},
|
||||
expect.objectContaining({
|
||||
actionId: "client-action-1",
|
||||
@@ -1944,9 +2049,120 @@ describe("WebSocket Server", () => {
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
await expect(connectWs(port)).rejects.toThrow("WebSocket connection failed");
|
||||
await expect(
|
||||
connectWs(port, { headers: { Origin: `http://127.0.0.1:${port}` } }),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, "secret-token");
|
||||
const [authorizedWs] = await connectAndAwaitWelcome(port, { token: "secret-token" });
|
||||
connections.push(authorizedWs);
|
||||
});
|
||||
|
||||
it("issues an auth cookie from a valid bootstrap token", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(204);
|
||||
expect(String(response.headers["set-cookie"])).toContain("t3_auth=");
|
||||
});
|
||||
|
||||
it("rejects bootstrap requests from foreign origins", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const response = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(403);
|
||||
});
|
||||
|
||||
it("consumes bootstrap tokens exactly once", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const first = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
const second = await requestPath(port, "/api/auth/bootstrap", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ token: currentBootstrapToken }),
|
||||
});
|
||||
|
||||
expect(first.statusCode).toBe(204);
|
||||
expect(second.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("reports auth session state from the browser cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const unauthenticated = await requestPath(port, "/api/auth/session");
|
||||
expect(unauthenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(unauthenticated.body)).toEqual({ authenticated: false });
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
const authenticated = await requestPath(port, "/api/auth/session", {
|
||||
headers: {
|
||||
Origin: `http://127.0.0.1:${port}`,
|
||||
Cookie: cookie,
|
||||
},
|
||||
});
|
||||
|
||||
expect(authenticated.statusCode).toBe(200);
|
||||
expect(JSON.parse(authenticated.body)).toEqual({ authenticated: true });
|
||||
});
|
||||
|
||||
it("rejects websocket connections without a browser origin", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(connectWs(port, { headers: { Cookie: cookie } })).rejects.toThrow(
|
||||
"WebSocket connection failed",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects websocket connections from a foreign origin even with a valid cookie", async () => {
|
||||
server = await createTestServer({ cwd: "/test" });
|
||||
const addr = server.address();
|
||||
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
||||
|
||||
const cookie = await pairBrowserSession(port);
|
||||
await expect(
|
||||
connectWs(port, {
|
||||
headers: {
|
||||
Origin: "https://evil.example",
|
||||
Cookie: cookie,
|
||||
},
|
||||
}),
|
||||
).rejects.toThrow("WebSocket connection failed");
|
||||
});
|
||||
});
|
||||
+212
-26
@@ -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 { ProviderHealth } from "./provider/Services/ProviderHealth";
|
||||
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
|
||||
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
|
||||
import { clamp } from "effect/Number";
|
||||
import { Open, resolveAvailableEditors } from "./open";
|
||||
@@ -79,6 +79,7 @@ import { expandHomePath } from "./os-jank.ts";
|
||||
import { makeServerPushBus } from "./wsServer/pushBus.ts";
|
||||
import { makeServerReadiness } from "./wsServer/readiness.ts";
|
||||
import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
|
||||
import { BrowserAuth } from "./browserAuth";
|
||||
|
||||
/**
|
||||
* ServerShape - Service API for server lifecycle control.
|
||||
@@ -122,6 +123,27 @@ function rejectUpgrade(socket: Duplex, statusCode: number, message: string): voi
|
||||
);
|
||||
}
|
||||
|
||||
function readRequestBody(request: http.IncomingMessage): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const chunks: Buffer[] = [];
|
||||
request.on("data", (chunk: Buffer | string) => {
|
||||
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
||||
});
|
||||
request.once("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
||||
request.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function corsHeaders(origin: string): Record<string, string> {
|
||||
return {
|
||||
"Access-Control-Allow-Origin": origin,
|
||||
"Access-Control-Allow-Credentials": "true",
|
||||
"Access-Control-Allow-Methods": "GET,POST,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "Content-Type",
|
||||
Vary: "Origin",
|
||||
};
|
||||
}
|
||||
|
||||
function websocketRawToString(raw: unknown): string | null {
|
||||
if (typeof raw === "string") {
|
||||
return raw;
|
||||
@@ -209,7 +231,7 @@ export type ServerCoreRuntimeServices =
|
||||
| CheckpointDiffQuery
|
||||
| OrchestrationReactor
|
||||
| ProviderService
|
||||
| ProviderHealth;
|
||||
| ProviderRegistry;
|
||||
|
||||
export type ServerRuntimeServices =
|
||||
| ServerCoreRuntimeServices
|
||||
@@ -219,7 +241,8 @@ export type ServerRuntimeServices =
|
||||
| Keybindings
|
||||
| ServerSettingsService
|
||||
| Open
|
||||
| AnalyticsService;
|
||||
| AnalyticsService
|
||||
| BrowserAuth;
|
||||
|
||||
export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
|
||||
"ServerLifecycleError",
|
||||
@@ -256,7 +279,8 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const terminalManager = yield* TerminalManager;
|
||||
const keybindingsManager = yield* Keybindings;
|
||||
const serverSettingsManager = yield* ServerSettingsService;
|
||||
const providerHealth = yield* ProviderHealth;
|
||||
const browserAuth = yield* BrowserAuth;
|
||||
const providerRegistry = yield* ProviderRegistry;
|
||||
const git = yield* GitCore;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -271,7 +295,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
),
|
||||
);
|
||||
|
||||
const providerStatuses = yield* providerHealth.getStatuses;
|
||||
const providersRef = yield* Ref.make(yield* providerRegistry.getProviders);
|
||||
|
||||
const clients = yield* Ref.make(new Set<WebSocket>());
|
||||
const logger = createLogger("ws");
|
||||
@@ -422,7 +446,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
const httpServer = http.createServer((req, res) => {
|
||||
const respond = (
|
||||
statusCode: number,
|
||||
headers: Record<string, string>,
|
||||
headers: http.OutgoingHttpHeaders,
|
||||
body?: string | Uint8Array,
|
||||
) => {
|
||||
res.writeHead(statusCode, headers);
|
||||
@@ -436,6 +460,134 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
return;
|
||||
}
|
||||
|
||||
const requestOrigin = req.headers.origin;
|
||||
const authEndpointHeaders =
|
||||
typeof requestOrigin === "string" && (yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
? corsHeaders(requestOrigin)
|
||||
: {};
|
||||
|
||||
if (url.pathname === "/api/auth/bootstrap") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "POST") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const bodyText = yield* Effect.tryPromise({
|
||||
try: () => readRequestBody(req),
|
||||
catch: () =>
|
||||
new RouteRequestError({ message: "Failed to read auth bootstrap request body." }),
|
||||
});
|
||||
|
||||
let parsedBody: unknown;
|
||||
try {
|
||||
parsedBody = JSON.parse(bodyText);
|
||||
} catch {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid JSON body",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const token =
|
||||
typeof parsedBody === "object" &&
|
||||
parsedBody !== null &&
|
||||
"token" in parsedBody &&
|
||||
typeof (parsedBody as { token?: unknown }).token === "string"
|
||||
? (parsedBody as { token: string }).token
|
||||
: null;
|
||||
if (!token) {
|
||||
respond(
|
||||
400,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Missing bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const consumed = yield* browserAuth.consumeBootstrapToken(token);
|
||||
if (!consumed) {
|
||||
respond(
|
||||
401,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Invalid bootstrap token",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const cookieHeader = yield* browserAuth.createAuthCookie(url.protocol === "https:");
|
||||
respond(204, {
|
||||
...authEndpointHeaders,
|
||||
"Set-Cookie": cookieHeader,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/auth/session") {
|
||||
if (req.method === "OPTIONS") {
|
||||
if (typeof requestOrigin !== "string") {
|
||||
respond(204, {});
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
respond(403, { "Content-Type": "text/plain" }, "Forbidden origin");
|
||||
return;
|
||||
}
|
||||
respond(204, authEndpointHeaders);
|
||||
return;
|
||||
}
|
||||
|
||||
if (req.method !== "GET") {
|
||||
respond(405, { "Content-Type": "text/plain" }, "Method Not Allowed");
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof requestOrigin === "string" &&
|
||||
!(yield* browserAuth.isAllowedOrigin(requestOrigin))
|
||||
) {
|
||||
respond(
|
||||
403,
|
||||
{ "Content-Type": "text/plain", ...authEndpointHeaders },
|
||||
"Forbidden origin",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const authenticated = yield* browserAuth.isAuthenticatedRequest(req.headers);
|
||||
respond(
|
||||
200,
|
||||
{ "Content-Type": "application/json", ...authEndpointHeaders },
|
||||
JSON.stringify({ authenticated }),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
|
||||
const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
|
||||
const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
|
||||
@@ -622,18 +774,25 @@ 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;
|
||||
|
||||
@@ -897,17 +1056,24 @@ 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: providerStatuses,
|
||||
providers,
|
||||
availableEditors,
|
||||
settings,
|
||||
};
|
||||
}
|
||||
|
||||
case WS_METHODS.serverRefreshProviders: {
|
||||
const providers = yield* providerRegistry.refresh();
|
||||
yield* Ref.set(providersRef, providers);
|
||||
return { providers };
|
||||
}
|
||||
|
||||
case WS_METHODS.serverUpsertKeybinding: {
|
||||
const body = stripRequestTag(request.body);
|
||||
const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
|
||||
@@ -972,25 +1138,45 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
httpServer.on("upgrade", (request, socket, head) => {
|
||||
socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
|
||||
|
||||
if (authToken) {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
void runPromise(
|
||||
Effect.gen(function* () {
|
||||
let providedToken: string | null = null;
|
||||
try {
|
||||
const url = new URL(request.url ?? "/", `http://localhost:${port}`);
|
||||
providedToken = url.searchParams.get("token");
|
||||
} catch {
|
||||
rejectUpgrade(socket, 400, "Invalid WebSocket URL");
|
||||
return;
|
||||
}
|
||||
|
||||
if (providedToken !== authToken) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
}
|
||||
const requestOrigin = request.headers.origin;
|
||||
const hasLegacyToken = Boolean(authToken && providedToken === authToken);
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
if (hasLegacyToken && !requestOrigin) {
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof requestOrigin !== "string") {
|
||||
rejectUpgrade(socket, 401, "Missing WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAllowedOrigin(requestOrigin))) {
|
||||
rejectUpgrade(socket, 401, "Forbidden WebSocket origin");
|
||||
return;
|
||||
}
|
||||
if (!(yield* browserAuth.isAuthenticatedRequest(request.headers))) {
|
||||
rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
|
||||
return;
|
||||
}
|
||||
|
||||
wss.handleUpgrade(request, socket, head, (ws) => {
|
||||
wss.emit("connection", ws, request);
|
||||
});
|
||||
}).pipe(Effect.ignoreCause({ log: true })),
|
||||
);
|
||||
});
|
||||
|
||||
wss.on("connection", (ws) => {
|
||||
|
||||
@@ -53,7 +53,6 @@ describe("makeServerPushBus", () => {
|
||||
|
||||
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [{ kind: "keybindings.malformed-config", message: "queued-before-connect" }],
|
||||
providers: [],
|
||||
});
|
||||
|
||||
const delivered = yield* pushBus.publishClient(
|
||||
@@ -70,7 +69,6 @@ describe("makeServerPushBus", () => {
|
||||
|
||||
yield* pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
|
||||
issues: [],
|
||||
providers: [],
|
||||
});
|
||||
|
||||
yield* Effect.promise(() => client.waitForSentCount(2));
|
||||
@@ -95,7 +93,6 @@ describe("makeServerPushBus", () => {
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: {
|
||||
issues: [],
|
||||
providers: [],
|
||||
},
|
||||
});
|
||||
}),
|
||||
|
||||
@@ -1,266 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
} from "./appSettings";
|
||||
import {
|
||||
getAppModelOptions,
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
getCustomModelsForProvider,
|
||||
getDefaultCustomModelsForProvider,
|
||||
MODEL_PROVIDER_SETTINGS,
|
||||
normalizeCustomModelSlugs,
|
||||
patchCustomModels,
|
||||
resolveAppModelSelectionState,
|
||||
resolveAppModelSelection,
|
||||
} from "./modelSelection";
|
||||
|
||||
describe("normalizeCustomModelSlugs", () => {
|
||||
it("normalizes aliases, removes built-ins, and deduplicates values", () => {
|
||||
expect(
|
||||
normalizeCustomModelSlugs([
|
||||
" custom/internal-model ",
|
||||
"gpt-5.3-codex",
|
||||
"5.3",
|
||||
"custom/internal-model",
|
||||
"",
|
||||
null,
|
||||
]),
|
||||
).toEqual(["custom/internal-model"]);
|
||||
});
|
||||
|
||||
it("normalizes provider-specific aliases for claude", () => {
|
||||
expect(normalizeCustomModelSlugs(["sonnet"], "claudeAgent")).toEqual([]);
|
||||
expect(normalizeCustomModelSlugs(["claude/custom-sonnet"], "claudeAgent")).toEqual([
|
||||
"claude/custom-sonnet",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getAppModelOptions", () => {
|
||||
it("appends saved custom models after the built-in options", () => {
|
||||
const options = getAppModelOptions("codex", ["custom/internal-model"]);
|
||||
|
||||
expect(options.map((option) => option.slug)).toEqual([
|
||||
"gpt-5.4",
|
||||
"gpt-5.4-mini",
|
||||
"gpt-5.3-codex",
|
||||
"gpt-5.3-codex-spark",
|
||||
"gpt-5.2-codex",
|
||||
"gpt-5.2",
|
||||
"custom/internal-model",
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps the currently selected custom model available even if it is no longer saved", () => {
|
||||
const options = getAppModelOptions("codex", [], "custom/selected-model");
|
||||
|
||||
expect(options.at(-1)).toEqual({
|
||||
slug: "custom/selected-model",
|
||||
name: "custom/selected-model",
|
||||
isCustom: true,
|
||||
});
|
||||
});
|
||||
it("keeps a saved custom provider model available as an exact slug option", () => {
|
||||
const options = getAppModelOptions("claudeAgent", ["claude/custom-opus"], "claude/custom-opus");
|
||||
|
||||
expect(options.some((option) => option.slug === "claude/custom-opus" && option.isCustom)).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAppModelSelection", () => {
|
||||
it("preserves saved custom model slugs instead of falling back to the default", () => {
|
||||
expect(
|
||||
resolveAppModelSelection(
|
||||
"codex",
|
||||
{ codex: ["galapagos-alpha"], claudeAgent: [] },
|
||||
"galapagos-alpha",
|
||||
),
|
||||
).toBe("galapagos-alpha");
|
||||
});
|
||||
|
||||
it("falls back to the provider default when no model is selected", () => {
|
||||
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "")).toBe("gpt-5.4");
|
||||
});
|
||||
|
||||
it("resolves display names through the shared resolver", () => {
|
||||
expect(resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "GPT-5.3 Codex")).toBe(
|
||||
"gpt-5.3-codex",
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves aliases through the shared resolver", () => {
|
||||
expect(resolveAppModelSelection("claudeAgent", { codex: [], claudeAgent: [] }, "sonnet")).toBe(
|
||||
"claude-sonnet-4-6",
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves transient selected custom models included in app model options", () => {
|
||||
expect(
|
||||
resolveAppModelSelection("codex", { codex: [], claudeAgent: [] }, "custom/selected-model"),
|
||||
).toBe("custom/selected-model");
|
||||
});
|
||||
});
|
||||
|
||||
describe("timestamp format defaults", () => {
|
||||
it("defaults timestamp format to locale", () => {
|
||||
expect(DEFAULT_TIMESTAMP_FORMAT).toBe("locale");
|
||||
});
|
||||
});
|
||||
|
||||
describe("sidebar sort defaults", () => {
|
||||
it("defaults project sorting to updated_at", () => {
|
||||
expect(DEFAULT_SIDEBAR_PROJECT_SORT_ORDER).toBe("updated_at");
|
||||
});
|
||||
|
||||
it("defaults thread sorting to updated_at", () => {
|
||||
expect(DEFAULT_SIDEBAR_THREAD_SORT_ORDER).toBe("updated_at");
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider-specific custom models", () => {
|
||||
it("includes provider-specific custom slugs in non-codex model lists", () => {
|
||||
const claudeOptions = getAppModelOptions("claudeAgent", ["claude/custom-opus"]);
|
||||
|
||||
expect(claudeOptions.some((option) => option.slug === "claude/custom-opus")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("provider-indexed custom model settings", () => {
|
||||
const settings = {
|
||||
customCodexModels: ["custom/codex-model"],
|
||||
customClaudeModels: ["claude/custom-opus"],
|
||||
} as const;
|
||||
|
||||
it("exports one provider config per provider", () => {
|
||||
expect(MODEL_PROVIDER_SETTINGS.map((config) => config.provider)).toEqual([
|
||||
"codex",
|
||||
"claudeAgent",
|
||||
]);
|
||||
});
|
||||
|
||||
it("reads custom models for each provider", () => {
|
||||
expect(getCustomModelsForProvider(settings, "codex")).toEqual(["custom/codex-model"]);
|
||||
expect(getCustomModelsForProvider(settings, "claudeAgent")).toEqual(["claude/custom-opus"]);
|
||||
});
|
||||
|
||||
it("reads default custom models for each provider", () => {
|
||||
const defaults = {
|
||||
customCodexModels: ["default/codex-model"],
|
||||
customClaudeModels: ["claude/default-opus"],
|
||||
} as const;
|
||||
|
||||
expect(getDefaultCustomModelsForProvider(defaults, "codex")).toEqual(["default/codex-model"]);
|
||||
expect(getDefaultCustomModelsForProvider(defaults, "claudeAgent")).toEqual([
|
||||
"claude/default-opus",
|
||||
]);
|
||||
});
|
||||
|
||||
it("patches custom models for codex", () => {
|
||||
expect(patchCustomModels("codex", ["custom/codex-model"])).toEqual({
|
||||
customCodexModels: ["custom/codex-model"],
|
||||
});
|
||||
});
|
||||
|
||||
it("patches custom models for claude", () => {
|
||||
expect(patchCustomModels("claudeAgent", ["claude/custom-opus"])).toEqual({
|
||||
customClaudeModels: ["claude/custom-opus"],
|
||||
});
|
||||
});
|
||||
|
||||
it("builds a complete provider-indexed custom model record", () => {
|
||||
expect(getCustomModelsByProvider(settings)).toEqual({
|
||||
codex: ["custom/codex-model"],
|
||||
claudeAgent: ["claude/custom-opus"],
|
||||
});
|
||||
});
|
||||
|
||||
it("builds provider-indexed model options including custom models", () => {
|
||||
const modelOptionsByProvider = getCustomModelOptionsByProvider(settings);
|
||||
|
||||
expect(
|
||||
modelOptionsByProvider.codex.some((option) => option.slug === "custom/codex-model"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude/custom-opus"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("normalizes and deduplicates custom model options per provider", () => {
|
||||
const modelOptionsByProvider = getCustomModelOptionsByProvider({
|
||||
customCodexModels: [" custom/codex-model ", "gpt-5.4", "custom/codex-model"],
|
||||
customClaudeModels: [" sonnet ", "claude/custom-opus", "claude/custom-opus"],
|
||||
});
|
||||
|
||||
expect(
|
||||
modelOptionsByProvider.codex.filter((option) => option.slug === "custom/codex-model"),
|
||||
).toHaveLength(1);
|
||||
expect(modelOptionsByProvider.codex.some((option) => option.slug === "gpt-5.4")).toBe(true);
|
||||
expect(
|
||||
modelOptionsByProvider.claudeAgent.filter((option) => option.slug === "claude/custom-opus"),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
modelOptionsByProvider.claudeAgent.some((option) => option.slug === "claude-sonnet-4-6"),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveAppModelSelectionState", () => {
|
||||
it("falls back to the default git-writing codex selection", () => {
|
||||
expect(
|
||||
resolveAppModelSelectionState({
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
textGenerationModelSelection: undefined,
|
||||
}),
|
||||
).toEqual({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the selected provider and resolves saved custom models", () => {
|
||||
expect(
|
||||
resolveAppModelSelectionState({
|
||||
customCodexModels: [],
|
||||
customClaudeModels: ["claude/custom-haiku"],
|
||||
textGenerationModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude/custom-haiku",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: "claudeAgent",
|
||||
model: "claude/custom-haiku",
|
||||
});
|
||||
});
|
||||
|
||||
it("normalizes provider options against the resolved model capabilities", () => {
|
||||
expect(
|
||||
resolveAppModelSelectionState({
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
textGenerationModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
effort: "max",
|
||||
thinking: false,
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
options: {
|
||||
thinking: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* App Settings - Backward-compatible shim.
|
||||
*
|
||||
* Re-exports the unified settings hook (`useSettings` / `useUpdateSettings`)
|
||||
* as `useAppSettings()` so existing consumers continue to work without
|
||||
* modification. New code should import from `~/hooks/useSettings` directly.
|
||||
*
|
||||
* Also re-exports type aliases and schema constants consumed by components
|
||||
* that only need the type (e.g. `TimestampFormat`).
|
||||
*/
|
||||
import { DEFAULT_SERVER_SETTINGS, type ServerSettings } from "@t3tools/contracts";
|
||||
import { useSettings, useUpdateSettings, type UnifiedSettings } from "./hooks/useSettings";
|
||||
import {
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
type ClientSettings,
|
||||
type TimestampFormat,
|
||||
type SidebarProjectSortOrder,
|
||||
type SidebarThreadSortOrder,
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
} from "./clientSettings";
|
||||
|
||||
// ── Re-exports for downstream type consumers ─────────────────────────
|
||||
|
||||
export type { TimestampFormat, SidebarProjectSortOrder, SidebarThreadSortOrder };
|
||||
export {
|
||||
DEFAULT_TIMESTAMP_FORMAT,
|
||||
DEFAULT_SIDEBAR_PROJECT_SORT_ORDER,
|
||||
DEFAULT_SIDEBAR_THREAD_SORT_ORDER,
|
||||
};
|
||||
export type { UnifiedSettings };
|
||||
|
||||
// ── Backward-compat type alias ───────────────────────────────────────
|
||||
|
||||
export type AppSettings = UnifiedSettings;
|
||||
|
||||
// ── Backward-compat hook ─────────────────────────────────────────────
|
||||
|
||||
export function useAppSettings() {
|
||||
const settings = useSettings();
|
||||
const { updateSettings, resetSettings, defaults } = useUpdateSettings();
|
||||
|
||||
return {
|
||||
settings,
|
||||
updateSettings: (patch: Partial<AppSettings>) => updateSettings(patch),
|
||||
resetSettings,
|
||||
defaults,
|
||||
} as const;
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
clearBootstrapTokenFromUrl,
|
||||
consumeBootstrapTokenFromHash,
|
||||
ensureBrowserPairing,
|
||||
resolveServerHttpOrigin,
|
||||
} from "./browserAuth";
|
||||
|
||||
describe("browserAuth", () => {
|
||||
const fetchMock = vi.fn<typeof fetch>();
|
||||
const setTestWindow = (href: string) => {
|
||||
let currentUrl = new URL(href);
|
||||
const location = {
|
||||
get hash() {
|
||||
return currentUrl.hash;
|
||||
},
|
||||
get host() {
|
||||
return currentUrl.host;
|
||||
},
|
||||
get hostname() {
|
||||
return currentUrl.hostname;
|
||||
},
|
||||
get href() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
get origin() {
|
||||
return currentUrl.origin;
|
||||
},
|
||||
get pathname() {
|
||||
return currentUrl.pathname;
|
||||
},
|
||||
get port() {
|
||||
return currentUrl.port;
|
||||
},
|
||||
get protocol() {
|
||||
return currentUrl.protocol;
|
||||
},
|
||||
get search() {
|
||||
return currentUrl.search;
|
||||
},
|
||||
toString() {
|
||||
return currentUrl.toString();
|
||||
},
|
||||
};
|
||||
const history = {
|
||||
state: {} as unknown,
|
||||
replaceState: (state: unknown, _unused: string, nextUrl?: string | URL | null) => {
|
||||
history.state = state;
|
||||
if (!nextUrl) return;
|
||||
currentUrl = new URL(String(nextUrl));
|
||||
},
|
||||
};
|
||||
vi.stubGlobal("window", {
|
||||
location,
|
||||
history,
|
||||
nativeApi: undefined,
|
||||
desktopBridge: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
setTestWindow("http://localhost:3773/");
|
||||
fetchMock.mockReset();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("reads and clears bootstrap tokens from the url hash", () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
|
||||
expect(consumeBootstrapTokenFromHash()).toBe("pair-me");
|
||||
|
||||
clearBootstrapTokenFromUrl();
|
||||
|
||||
expect(window.location.hash).toBe("");
|
||||
expect(consumeBootstrapTokenFromHash()).toBeNull();
|
||||
});
|
||||
|
||||
it("resolves the server http origin from the current location when no ws override exists", () => {
|
||||
setTestWindow("http://localhost:4123/chat");
|
||||
|
||||
expect(resolveServerHttpOrigin()).toBe("http://localhost:4123");
|
||||
});
|
||||
|
||||
it("exchanges a bootstrap token before checking the auth session", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
"http://localhost:3773/api/auth/bootstrap",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("polls auth session after a successful bootstrap until the cookie is visible", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(null, {
|
||||
status: 204,
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: true }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(4);
|
||||
expect(window.location.hash).toBe("");
|
||||
});
|
||||
|
||||
it("returns false when bootstrap exchange fails", async () => {
|
||||
setTestWindow("http://localhost:3773/#t3_bootstrap=pair-me");
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response("nope", {
|
||||
status: 401,
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(window.location.hash).toBe("#t3_bootstrap=pair-me");
|
||||
});
|
||||
|
||||
it("checks the existing auth session when no bootstrap token is present", async () => {
|
||||
fetchMock.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ authenticated: false }), {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(false);
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost:3773/api/auth/session",
|
||||
expect.objectContaining({
|
||||
credentials: "include",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("bypasses browser pairing when the electron desktop bridge is available", async () => {
|
||||
vi.stubGlobal("window", {
|
||||
location: {
|
||||
href: "file:///app/index.html",
|
||||
origin: "file://",
|
||||
hash: "",
|
||||
},
|
||||
history: {
|
||||
state: undefined,
|
||||
replaceState: vi.fn(),
|
||||
},
|
||||
nativeApi: undefined,
|
||||
desktopBridge: {
|
||||
getWsUrl: () => "ws://127.0.0.1:3773",
|
||||
},
|
||||
});
|
||||
|
||||
await expect(ensureBrowserPairing()).resolves.toBe(true);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
const BOOTSTRAP_HASH_KEY = "t3_bootstrap";
|
||||
const AUTH_SESSION_POLL_ATTEMPTS = 50;
|
||||
const AUTH_SESSION_POLL_INTERVAL_MS = 100;
|
||||
|
||||
interface AuthSessionResponse {
|
||||
readonly authenticated: boolean;
|
||||
}
|
||||
|
||||
function normalizeServerHttpOrigin(rawUrl: string): string {
|
||||
const wsUrl = new URL(rawUrl);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
}
|
||||
|
||||
export function resolveServerHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
|
||||
if (!wsCandidate) {
|
||||
return window.location.origin;
|
||||
}
|
||||
|
||||
try {
|
||||
return normalizeServerHttpOrigin(wsCandidate);
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
export function consumeBootstrapTokenFromHash(
|
||||
locationLike: Location = window.location,
|
||||
): string | null {
|
||||
const hash = locationLike.hash.startsWith("#") ? locationLike.hash.slice(1) : locationLike.hash;
|
||||
const params = new URLSearchParams(hash);
|
||||
const token = params.get(BOOTSTRAP_HASH_KEY);
|
||||
return token && token.length > 0 ? token : null;
|
||||
}
|
||||
|
||||
export function clearBootstrapTokenFromUrl(locationLike: Location = window.location): void {
|
||||
const currentUrl = new URL(locationLike.href);
|
||||
currentUrl.hash = "";
|
||||
window.history.replaceState(window.history.state, "", currentUrl.toString());
|
||||
}
|
||||
|
||||
async function exchangeBootstrapToken(serverOrigin: string, token: string): Promise<void> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/bootstrap`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
credentials: "include",
|
||||
body: JSON.stringify({ token }),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Browser pairing failed with status ${response.status}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSession(serverOrigin: string): Promise<boolean> {
|
||||
const response = await fetch(`${serverOrigin}/api/auth/session`, {
|
||||
credentials: "include",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Auth session check failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const parsed = (await response.json()) as Partial<AuthSessionResponse>;
|
||||
return parsed.authenticated === true;
|
||||
}
|
||||
|
||||
async function waitForAuthenticatedSession(serverOrigin: string): Promise<boolean> {
|
||||
for (let attempt = 0; attempt < AUTH_SESSION_POLL_ATTEMPTS; attempt += 1) {
|
||||
if (await fetchSession(serverOrigin)) {
|
||||
return true;
|
||||
}
|
||||
if (attempt < AUTH_SESSION_POLL_ATTEMPTS - 1) {
|
||||
await new Promise((resolve) => setTimeout(resolve, AUTH_SESSION_POLL_INTERVAL_MS));
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function ensureBrowserPairing(): Promise<boolean> {
|
||||
if (typeof window === "undefined") return false;
|
||||
if (window.nativeApi || window.desktopBridge) return true;
|
||||
|
||||
const serverOrigin = resolveServerHttpOrigin();
|
||||
const bootstrapToken = consumeBootstrapTokenFromHash();
|
||||
|
||||
if (bootstrapToken) {
|
||||
try {
|
||||
await exchangeBootstrapToken(serverOrigin, bootstrapToken);
|
||||
clearBootstrapTokenFromUrl();
|
||||
return waitForAuthenticatedSession(serverOrigin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return fetchSession(serverOrigin);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
/**
|
||||
* 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({});
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
resolveBranchSelectionTarget,
|
||||
resolveDraftEnvModeAfterBranchChange,
|
||||
resolveBranchToolbarValue,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
|
||||
describe("resolveDraftEnvModeAfterBranchChange", () => {
|
||||
@@ -267,3 +268,38 @@ describe("resolveBranchSelectionTarget", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldIncludeBranchPickerItem", () => {
|
||||
it("keeps the synthetic checkout PR item visible for gh pr checkout input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__checkout_pull_request__:1359",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps the synthetic create-branch item visible for arbitrary branch input", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "__create_new_branch__:feature/demo",
|
||||
normalizedQuery: "feature/demo",
|
||||
createBranchItemValue: "__create_new_branch__:feature/demo",
|
||||
checkoutPullRequestItemValue: null,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("still filters ordinary branch items by query text", () => {
|
||||
expect(
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue: "main",
|
||||
normalizedQuery: "gh pr checkout 1359",
|
||||
createBranchItemValue: "__create_new_branch__:gh pr checkout 1359",
|
||||
checkoutPullRequestItemValue: "__checkout_pull_request__:1359",
|
||||
}),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -123,3 +123,26 @@ export function resolveBranchSelectionTarget(input: {
|
||||
reuseExistingWorktree: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function shouldIncludeBranchPickerItem(input: {
|
||||
itemValue: string;
|
||||
normalizedQuery: string;
|
||||
createBranchItemValue: string | null;
|
||||
checkoutPullRequestItemValue: string | null;
|
||||
}): boolean {
|
||||
const { itemValue, normalizedQuery, createBranchItemValue, checkoutPullRequestItemValue } = input;
|
||||
|
||||
if (normalizedQuery.length === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (checkoutPullRequestItemValue && itemValue === checkoutPullRequestItemValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return itemValue.toLowerCase().includes(normalizedQuery);
|
||||
}
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
EnvMode,
|
||||
resolveBranchSelectionTarget,
|
||||
resolveBranchToolbarValue,
|
||||
shouldIncludeBranchPickerItem,
|
||||
} from "./BranchToolbar.logic";
|
||||
import { Button } from "./ui/button";
|
||||
import {
|
||||
@@ -134,11 +135,20 @@ export function BranchToolbarBranchSelector({
|
||||
() =>
|
||||
normalizedDeferredBranchQuery.length === 0
|
||||
? branchPickerItems
|
||||
: branchPickerItems.filter((itemValue) => {
|
||||
if (createBranchItemValue && itemValue === createBranchItemValue) return true;
|
||||
return itemValue.toLowerCase().includes(normalizedDeferredBranchQuery);
|
||||
}),
|
||||
[branchPickerItems, createBranchItemValue, normalizedDeferredBranchQuery],
|
||||
: branchPickerItems.filter((itemValue) =>
|
||||
shouldIncludeBranchPickerItem({
|
||||
itemValue,
|
||||
normalizedQuery: normalizedDeferredBranchQuery,
|
||||
createBranchItemValue,
|
||||
checkoutPullRequestItemValue,
|
||||
}),
|
||||
),
|
||||
[
|
||||
branchPickerItems,
|
||||
checkoutPullRequestItemValue,
|
||||
createBranchItemValue,
|
||||
normalizedDeferredBranchQuery,
|
||||
],
|
||||
);
|
||||
const [resolvedActiveBranch, setOptimisticBranch] = useOptimistic(
|
||||
canonicalActiveBranch,
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
OrchestrationSessionStatus,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
} from "@t3tools/contracts";
|
||||
import { RouterProvider, createMemoryHistory } from "@tanstack/react-router";
|
||||
import { HttpResponse, http, ws } from "msw";
|
||||
@@ -30,6 +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";
|
||||
|
||||
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}$/;
|
||||
@@ -54,6 +56,7 @@ interface TestFixture {
|
||||
|
||||
let fixture: TestFixture;
|
||||
const wsRequests: WsRequestEnvelope["body"][] = [];
|
||||
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
|
||||
const wsLink = ws.link(/ws(s)?:\/\/.*/);
|
||||
|
||||
interface ViewportSpec {
|
||||
@@ -110,21 +113,19 @@ 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: [],
|
||||
settings: {
|
||||
claude: { binaryPath: "" },
|
||||
codex: { binaryPath: "", homePath: "" },
|
||||
enableAssistantStreaming: false,
|
||||
defaultThreadEnvMode: "local" as const,
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -356,6 +357,25 @@ function withProjectScripts(
|
||||
};
|
||||
}
|
||||
|
||||
function setDraftThreadWithoutWorktree(): void {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
const snapshot = createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-plan-target" as MessageId,
|
||||
@@ -414,6 +434,10 @@ function createSnapshotWithLongProposedPlan(): OrchestrationReadModel {
|
||||
}
|
||||
|
||||
function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
|
||||
const customResult = customWsRpcResolver?.(body);
|
||||
if (customResult !== undefined) {
|
||||
return customResult;
|
||||
}
|
||||
const tag = body._tag;
|
||||
if (tag === ORCHESTRATION_WS_METHODS.getSnapshot) {
|
||||
return fixture.snapshot;
|
||||
@@ -748,9 +772,11 @@ async function mountChatView(options: {
|
||||
viewport: ViewportSpec;
|
||||
snapshot: OrchestrationReadModel;
|
||||
configureFixture?: (fixture: TestFixture) => void;
|
||||
resolveRpc?: (body: WsRequestEnvelope["body"]) => unknown | undefined;
|
||||
}): Promise<MountedChatView> {
|
||||
fixture = buildFixture(options.snapshot);
|
||||
options.configureFixture?.(fixture);
|
||||
customWsRpcResolver = options.resolveRpc ?? null;
|
||||
await setViewport(options.viewport);
|
||||
await waitForProductionStyles();
|
||||
|
||||
@@ -776,6 +802,7 @@ async function mountChatView(options: {
|
||||
await waitForLayout();
|
||||
|
||||
const cleanup = async () => {
|
||||
customWsRpcResolver = null;
|
||||
await screen.unmount();
|
||||
host.remove();
|
||||
};
|
||||
@@ -835,6 +862,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
localStorage.clear();
|
||||
document.body.innerHTML = "";
|
||||
wsRequests.length = 0;
|
||||
customWsRpcResolver = null;
|
||||
useComposerDraftStore.setState({
|
||||
draftsByThreadId: {},
|
||||
draftThreadsByThreadId: {},
|
||||
@@ -850,6 +878,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
customWsRpcResolver = null;
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
@@ -1011,22 +1040,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
);
|
||||
|
||||
it("opens the project cwd for draft threads without a worktree path", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
@@ -1067,6 +1081,153 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the project cwd with VS Code Insiders when it is the only available editor", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Open",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscode-insiders",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("filters the open picker menu and opens VSCodium from the menu", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders", "vscodium"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const menuButton = await waitForElement(
|
||||
() => document.querySelector('button[aria-label="Copy options"]'),
|
||||
"Unable to find Open picker button.",
|
||||
);
|
||||
(menuButton as HTMLButtonElement).click();
|
||||
|
||||
await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) =>
|
||||
item.textContent?.includes("VS Code Insiders"),
|
||||
) ?? null,
|
||||
"Unable to find VS Code Insiders menu item.",
|
||||
);
|
||||
|
||||
expect(
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).some((item) =>
|
||||
item.textContent?.includes("Zed"),
|
||||
),
|
||||
).toBe(false);
|
||||
|
||||
const vscodiumItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find((item) =>
|
||||
item.textContent?.includes("VSCodium"),
|
||||
) ?? null,
|
||||
"Unable to find VSCodium menu item.",
|
||||
);
|
||||
(vscodiumItem as HTMLElement).click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscodium",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to the first installed editor when the stored favorite is unavailable", async () => {
|
||||
localStorage.setItem("t3code:last-editor", "vscodium");
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
configureFixture: (nextFixture) => {
|
||||
nextFixture.serverConfig = {
|
||||
...nextFixture.serverConfig,
|
||||
availableEditors: ["vscode-insiders"],
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const openButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Open",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Open button.",
|
||||
);
|
||||
openButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.shellOpenInEditor,
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.shellOpenInEditor,
|
||||
cwd: "/repo/project",
|
||||
editor: "vscode-insiders",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("runs project scripts from local draft threads at the project cwd", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
@@ -1206,6 +1367,154 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("runs setup scripts after preparing a pull request worktree thread", async () => {
|
||||
useComposerDraftStore.setState({
|
||||
draftThreadsByThreadId: {
|
||||
[THREAD_ID]: {
|
||||
projectId: PROJECT_ID,
|
||||
createdAt: NOW_ISO,
|
||||
runtimeMode: "full-access",
|
||||
interactionMode: "default",
|
||||
branch: null,
|
||||
worktreePath: null,
|
||||
envMode: "local",
|
||||
},
|
||||
},
|
||||
projectDraftThreadIdByProjectId: {
|
||||
[PROJECT_ID]: THREAD_ID,
|
||||
},
|
||||
});
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: withProjectScripts(createDraftOnlySnapshot(), [
|
||||
{
|
||||
id: "setup",
|
||||
name: "Setup",
|
||||
command: "bun install",
|
||||
icon: "configure",
|
||||
runOnWorktreeCreate: true,
|
||||
},
|
||||
]),
|
||||
resolveRpc: (body) => {
|
||||
if (body._tag === WS_METHODS.gitResolvePullRequest) {
|
||||
return {
|
||||
pullRequest: {
|
||||
number: 1359,
|
||||
title: "Add thread archiving and settings navigation",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1359",
|
||||
baseBranch: "main",
|
||||
headBranch: "archive-settings-overhaul",
|
||||
state: "open",
|
||||
},
|
||||
};
|
||||
}
|
||||
if (body._tag === WS_METHODS.gitPreparePullRequestThread) {
|
||||
return {
|
||||
pullRequest: {
|
||||
number: 1359,
|
||||
title: "Add thread archiving and settings navigation",
|
||||
url: "https://github.com/pingdotgg/t3code/pull/1359",
|
||||
baseBranch: "main",
|
||||
headBranch: "archive-settings-overhaul",
|
||||
state: "open",
|
||||
},
|
||||
branch: "archive-settings-overhaul",
|
||||
worktreePath: "/repo/worktrees/pr-1359",
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
const branchButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "main",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find branch selector button.",
|
||||
);
|
||||
branchButton.click();
|
||||
|
||||
const branchInput = await waitForElement(
|
||||
() => document.querySelector<HTMLInputElement>('input[placeholder="Search branches..."]'),
|
||||
"Unable to find branch search input.",
|
||||
);
|
||||
branchInput.focus();
|
||||
await page.getByPlaceholder("Search branches...").fill("1359");
|
||||
|
||||
const checkoutItem = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("span")).find(
|
||||
(element) => element.textContent?.trim() === "Checkout Pull Request",
|
||||
) as HTMLSpanElement | null,
|
||||
"Unable to find checkout pull request option.",
|
||||
);
|
||||
checkoutItem.click();
|
||||
|
||||
const worktreeButton = await waitForElement(
|
||||
() =>
|
||||
Array.from(document.querySelectorAll("button")).find(
|
||||
(button) => button.textContent?.trim() === "Worktree",
|
||||
) as HTMLButtonElement | null,
|
||||
"Unable to find Worktree button.",
|
||||
);
|
||||
worktreeButton.click();
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const prepareRequest = wsRequests.find(
|
||||
(request) => request._tag === WS_METHODS.gitPreparePullRequestThread,
|
||||
);
|
||||
expect(prepareRequest).toMatchObject({
|
||||
_tag: WS_METHODS.gitPreparePullRequestThread,
|
||||
cwd: "/repo/project",
|
||||
reference: "1359",
|
||||
mode: "worktree",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const openRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === WS_METHODS.terminalOpen && request.cwd === "/repo/worktrees/pr-1359",
|
||||
);
|
||||
expect(openRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalOpen,
|
||||
threadId: expect.any(String),
|
||||
cwd: "/repo/worktrees/pr-1359",
|
||||
env: {
|
||||
T3CODE_PROJECT_ROOT: "/repo/project",
|
||||
T3CODE_WORKTREE_PATH: "/repo/worktrees/pr-1359",
|
||||
},
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
const writeRequest = wsRequests.find(
|
||||
(request) =>
|
||||
request._tag === WS_METHODS.terminalWrite && request.data === "bun install\r",
|
||||
);
|
||||
expect(writeRequest).toMatchObject({
|
||||
_tag: WS_METHODS.terminalWrite,
|
||||
threadId: expect.any(String),
|
||||
data: "bun install\r",
|
||||
});
|
||||
},
|
||||
{ timeout: 8_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("toggles plan mode with Shift+Tab only while the composer is focused", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
type MessageId,
|
||||
type ModelSelection,
|
||||
type ProjectScript,
|
||||
type ModelSlug,
|
||||
type ProviderKind,
|
||||
type ProjectEntry,
|
||||
type ProjectId,
|
||||
@@ -13,7 +12,7 @@ import {
|
||||
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
|
||||
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
|
||||
type ResolvedKeybindingsConfig,
|
||||
type ServerProviderStatus,
|
||||
type ServerProvider,
|
||||
type ThreadId,
|
||||
type TurnId,
|
||||
type EditorId,
|
||||
@@ -22,11 +21,7 @@ import {
|
||||
ProviderInteractionMode,
|
||||
RuntimeMode,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelCapabilities,
|
||||
normalizeModelSlug,
|
||||
} from "@t3tools/shared/model";
|
||||
import { applyClaudePromptEffortPrefix, 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";
|
||||
@@ -120,12 +115,13 @@ import {
|
||||
import { SidebarTrigger } from "./ui/sidebar";
|
||||
import { newCommandId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { readNativeApi } from "~/nativeApi";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import {
|
||||
getCustomModelOptionsByProvider,
|
||||
getCustomModelsByProvider,
|
||||
resolveAppModelSelection,
|
||||
} from "../modelSelection";
|
||||
getProviderModelCapabilities,
|
||||
getProviderModels,
|
||||
resolveSelectableProvider,
|
||||
} from "../providerModels";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { resolveAppModelSelection } from "../modelSelection";
|
||||
import { isTerminalFocused } from "../lib/terminalFocus";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
@@ -164,7 +160,7 @@ import {
|
||||
renderProviderTraitsMenuContent,
|
||||
renderProviderTraitsPicker,
|
||||
} from "./chat/composerProviderRegistry";
|
||||
import { ProviderHealthBanner } from "./chat/ProviderHealthBanner";
|
||||
import { ProviderStatusBanner } from "./chat/ProviderStatusBanner";
|
||||
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
|
||||
import {
|
||||
buildExpiredTerminalContextToastCopy,
|
||||
@@ -191,16 +187,17 @@ const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const EMPTY_PROJECT_ENTRIES: ProjectEntry[] = [];
|
||||
const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
|
||||
const EMPTY_PROVIDER_STATUSES: ServerProviderStatus[] = [];
|
||||
const EMPTY_PROVIDERS: ServerProvider[] = [];
|
||||
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 = getModelCapabilities(params.provider, params.model);
|
||||
const caps = getProviderModelCapabilities(params.models, params.model, params.provider);
|
||||
if (params.effort && caps.promptInjectedEffortLevels.includes(params.effort)) {
|
||||
return applyClaudePromptEffortPrefix(params.text, params.effort as ClaudeCodeEffort | null);
|
||||
}
|
||||
@@ -242,6 +239,12 @@ interface ChatViewProps {
|
||||
threadId: ThreadId;
|
||||
}
|
||||
|
||||
interface PendingPullRequestSetupRequest {
|
||||
threadId: ThreadId;
|
||||
worktreePath: string;
|
||||
scriptId: string;
|
||||
}
|
||||
|
||||
export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
@@ -249,7 +252,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
const { settings } = useAppSettings();
|
||||
const settings = useSettings();
|
||||
const setStickyComposerModelSelection = useComposerDraftStore(
|
||||
(store) => store.setStickyModelSelection,
|
||||
);
|
||||
@@ -353,6 +356,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
|
||||
const [pullRequestDialogState, setPullRequestDialogState] =
|
||||
useState<PullRequestDialogState | null>(null);
|
||||
const [pendingPullRequestSetupRequest, setPendingPullRequestSetupRequest] =
|
||||
useState<PendingPullRequestSetupRequest | null>(null);
|
||||
const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<
|
||||
Record<string, string[]>
|
||||
>({});
|
||||
@@ -530,14 +535,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
params: { threadId: storedDraftThread.threadId },
|
||||
});
|
||||
}
|
||||
return;
|
||||
return storedDraftThread.threadId;
|
||||
}
|
||||
|
||||
const activeDraftThread = getDraftThread(threadId);
|
||||
if (!isServerThread && activeDraftThread?.projectId === activeProject.id) {
|
||||
setDraftThreadContext(threadId, input);
|
||||
setProjectDraftThreadId(activeProject.id, threadId, input);
|
||||
return;
|
||||
return threadId;
|
||||
}
|
||||
|
||||
clearProjectDraftThreadId(activeProject.id);
|
||||
@@ -552,6 +557,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
to: "/$threadId",
|
||||
params: { threadId: nextThreadId },
|
||||
});
|
||||
return nextThreadId;
|
||||
},
|
||||
[
|
||||
activeProject,
|
||||
@@ -568,13 +574,24 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
|
||||
const handlePreparedPullRequestThread = useCallback(
|
||||
async (input: { branch: string; worktreePath: string | null }) => {
|
||||
await openOrReuseProjectDraftThread({
|
||||
const targetThreadId = await openOrReuseProjectDraftThread({
|
||||
branch: input.branch,
|
||||
worktreePath: input.worktreePath,
|
||||
envMode: input.worktreePath ? "worktree" : "local",
|
||||
});
|
||||
const setupScript =
|
||||
input.worktreePath && activeProject ? setupProjectScript(activeProject.scripts) : null;
|
||||
if (targetThreadId && input.worktreePath && setupScript) {
|
||||
setPendingPullRequestSetupRequest({
|
||||
threadId: targetThreadId,
|
||||
worktreePath: input.worktreePath,
|
||||
scriptId: setupScript.id,
|
||||
});
|
||||
} else {
|
||||
setPendingPullRequestSetupRequest(null);
|
||||
}
|
||||
},
|
||||
[openOrReuseProjectDraftThread],
|
||||
[activeProject, openOrReuseProjectDraftThread],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -608,25 +625,32 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const lockedProvider: ProviderKind | null = hasThreadStarted
|
||||
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
|
||||
: null;
|
||||
const selectedProvider: ProviderKind =
|
||||
lockedProvider ?? selectedProviderByThreadId ?? threadProvider ?? "codex";
|
||||
const customModelsByProvider = useMemo(() => getCustomModelsByProvider(settings), [settings]);
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
const providerStatuses = serverConfigQuery.data?.providers ?? EMPTY_PROVIDERS;
|
||||
const unlockedSelectedProvider = resolveSelectableProvider(
|
||||
providerStatuses,
|
||||
selectedProviderByThreadId ?? threadProvider ?? "codex",
|
||||
);
|
||||
const selectedProvider: ProviderKind = lockedProvider ?? unlockedSelectedProvider;
|
||||
const { modelOptions: composerModelOptions, selectedModel } = useEffectiveComposerModelState({
|
||||
threadId,
|
||||
providers: providerStatuses,
|
||||
selectedProvider,
|
||||
threadModelSelection: activeThread?.modelSelection,
|
||||
projectModelSelection: activeProject?.defaultModelSelection,
|
||||
customModelsByProvider,
|
||||
settings,
|
||||
});
|
||||
const selectedProviderModels = getProviderModels(providerStatuses, selectedProvider);
|
||||
const composerProviderState = useMemo(
|
||||
() =>
|
||||
getComposerProviderState({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
prompt,
|
||||
modelOptions: composerModelOptions,
|
||||
}),
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider],
|
||||
[composerModelOptions, prompt, selectedModel, selectedProvider, selectedProviderModels],
|
||||
);
|
||||
const selectedPromptEffort = composerProviderState.promptEffort;
|
||||
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
|
||||
@@ -639,33 +663,6 @@ 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";
|
||||
@@ -1028,7 +1025,39 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const effectivePathQuery = pathTriggerQuery.length > 0 ? debouncedPathQuery : "";
|
||||
const branchesQuery = useQuery(gitBranchesQueryOptions(gitCwd));
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
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 workspaceEntriesQuery = useQuery(
|
||||
projectSearchEntriesQueryOptions({
|
||||
cwd: gitCwd,
|
||||
@@ -1116,9 +1145,6 @@ 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],
|
||||
@@ -1412,6 +1438,45 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
terminalState.terminalIds,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!pendingPullRequestSetupRequest || !activeProject || !activeThreadId || !activeThread) {
|
||||
return;
|
||||
}
|
||||
if (pendingPullRequestSetupRequest.threadId !== activeThreadId) {
|
||||
return;
|
||||
}
|
||||
if (activeThread.worktreePath !== pendingPullRequestSetupRequest.worktreePath) {
|
||||
return;
|
||||
}
|
||||
|
||||
const setupScript =
|
||||
activeProject.scripts.find(
|
||||
(script) => script.id === pendingPullRequestSetupRequest.scriptId,
|
||||
) ?? null;
|
||||
setPendingPullRequestSetupRequest(null);
|
||||
if (!setupScript) {
|
||||
return;
|
||||
}
|
||||
|
||||
void runProjectScript(setupScript, {
|
||||
cwd: pendingPullRequestSetupRequest.worktreePath,
|
||||
worktreePath: pendingPullRequestSetupRequest.worktreePath,
|
||||
rememberAsLastInvoked: false,
|
||||
}).catch((error) => {
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Failed to run setup script.",
|
||||
description: error instanceof Error ? error.message : "An error occurred.",
|
||||
});
|
||||
});
|
||||
}, [
|
||||
activeProject,
|
||||
activeThread,
|
||||
activeThreadId,
|
||||
pendingPullRequestSetupRequest,
|
||||
runProjectScript,
|
||||
]);
|
||||
const persistProjectScripts = useCallback(
|
||||
async (input: {
|
||||
projectId: ProjectId;
|
||||
@@ -2459,6 +2524,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
effort: selectedPromptEffort,
|
||||
text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,
|
||||
});
|
||||
@@ -2880,6 +2946,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const outgoingMessageText = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
effort: selectedPromptEffort,
|
||||
text: trimmed,
|
||||
});
|
||||
@@ -2970,9 +3037,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
selectedProvider,
|
||||
selectedProviderModels,
|
||||
setComposerDraftInteractionMode,
|
||||
setThreadError,
|
||||
settings.enableAssistantStreaming,
|
||||
selectedModel,
|
||||
],
|
||||
);
|
||||
@@ -2999,6 +3066,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const outgoingImplementationPrompt = formatOutgoingPrompt({
|
||||
provider: selectedProvider,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
effort: selectedPromptEffort,
|
||||
text: implementationPrompt,
|
||||
});
|
||||
@@ -3089,20 +3157,27 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
selectedProvider,
|
||||
selectedProviderModels,
|
||||
syncServerReadModel,
|
||||
selectedModel,
|
||||
]);
|
||||
|
||||
const onProviderModelSelect = useCallback(
|
||||
(provider: ProviderKind, model: ModelSlug) => {
|
||||
(provider: ProviderKind, model: string) => {
|
||||
if (!activeThread) return;
|
||||
if (lockedProvider !== null && provider !== lockedProvider) {
|
||||
scheduleComposerFocus();
|
||||
return;
|
||||
}
|
||||
const resolvedModel = resolveAppModelSelection(provider, customModelsByProvider, model);
|
||||
const resolvedProvider = resolveSelectableProvider(providerStatuses, provider);
|
||||
const resolvedModel = resolveAppModelSelection(
|
||||
resolvedProvider,
|
||||
settings,
|
||||
providerStatuses,
|
||||
model,
|
||||
);
|
||||
const nextModelSelection: ModelSelection = {
|
||||
provider,
|
||||
provider: resolvedProvider,
|
||||
model: resolvedModel,
|
||||
};
|
||||
setComposerDraftModelSelection(activeThread.id, nextModelSelection);
|
||||
@@ -3115,7 +3190,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
scheduleComposerFocus,
|
||||
setComposerDraftModelSelection,
|
||||
setStickyComposerModelSelection,
|
||||
customModelsByProvider,
|
||||
providerStatuses,
|
||||
settings,
|
||||
],
|
||||
);
|
||||
const setPromptFromTraits = useCallback(
|
||||
@@ -3138,6 +3214,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
@@ -3146,6 +3223,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
provider: selectedProvider,
|
||||
threadId,
|
||||
model: selectedModel,
|
||||
models: selectedProviderModels,
|
||||
modelOptions: composerModelOptions?.[selectedProvider],
|
||||
prompt,
|
||||
onPromptChange: setPromptFromTraits,
|
||||
@@ -3509,7 +3587,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</header>
|
||||
|
||||
{/* Error banner */}
|
||||
<ProviderHealthBanner status={activeProviderStatus} />
|
||||
<ProviderStatusBanner status={activeProviderStatus} />
|
||||
<ThreadErrorBanner
|
||||
error={activeThread.error}
|
||||
onDismiss={() => setThreadError(activeThread.id, null)}
|
||||
@@ -3596,7 +3674,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 focus-within:border-ring/45",
|
||||
"rounded-[20px] border bg-card transition-colors duration-200 has-focus-visible:border-ring/45",
|
||||
isDragOverComposer ? "border-primary/70 bg-accent/30" : "border-border",
|
||||
composerProviderState.composerSurfaceClassName,
|
||||
)}
|
||||
@@ -3786,6 +3864,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
provider={selectedProvider}
|
||||
model={selectedModelForPickerWithCustomFallback}
|
||||
lockedProvider={lockedProvider}
|
||||
providers={providerStatuses}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
{...(composerProviderState.modelPickerIconClassName
|
||||
? {
|
||||
@@ -4013,7 +4092,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
) : (
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-9 w-9 items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
className="flex h-9 w-9 enabled:cursor-pointer items-center justify-center rounded-full bg-primary/90 text-primary-foreground transition-all duration-150 hover:bg-primary hover:scale-105 disabled:pointer-events-none disabled:opacity-30 disabled:hover:scale-100 sm:h-8 sm:w-8"
|
||||
disabled={
|
||||
isSendBusy || isConnecting || !composerSendState.hasSendableContent
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import { useStore } from "../store";
|
||||
import { useAppSettings } from "../appSettings";
|
||||
import { useSettings } from "../hooks/useSettings";
|
||||
import { formatShortTimestamp } from "../timestampFormat";
|
||||
import { DiffPanelLoadingState, DiffPanelShell, type DiffPanelMode } from "./DiffPanelShell";
|
||||
import { ToggleGroup, Toggle } from "./ui/toggle-group";
|
||||
@@ -166,7 +166,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const { settings } = useAppSettings();
|
||||
const settings = useSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
const patchViewportRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
resolveQuickAction,
|
||||
summarizeGitResult,
|
||||
} from "./GitActionsControl.logic";
|
||||
import { useAppSettings } from "~/appSettings";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Checkbox } from "~/components/ui/checkbox";
|
||||
import {
|
||||
@@ -205,7 +204,6 @@ function GitQuickActionIcon({ quickAction }: { quickAction: GitQuickAction }) {
|
||||
}
|
||||
|
||||
export default function GitActionsControl({ gitCwd, activeThreadId }: GitActionsControlProps) {
|
||||
const { settings } = useAppSettings();
|
||||
const threadToastData = useMemo(
|
||||
() => (activeThreadId ? { threadId: activeThreadId } : undefined),
|
||||
[activeThreadId],
|
||||
@@ -261,7 +259,6 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
gitRunStackedActionMutationOptions({
|
||||
cwd: gitCwd,
|
||||
queryClient,
|
||||
modelSelection: settings.textGenerationModelSelection,
|
||||
}),
|
||||
);
|
||||
const pullMutation = useMutation(gitPullMutationOptions({ cwd: gitCwd, queryClient }));
|
||||
@@ -753,7 +750,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
{initMutation.isPending ? "Initializing..." : "Initialize Git"}
|
||||
</Button>
|
||||
) : (
|
||||
<Group aria-label="Git actions">
|
||||
<Group aria-label="Git actions" className="shrink-0">
|
||||
{quickActionDisabledReason ? (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
@@ -768,7 +765,7 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
</PopoverTrigger>
|
||||
@@ -784,12 +781,12 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
|
||||
onClick={runQuickAction}
|
||||
>
|
||||
<GitQuickActionIcon quickAction={quickAction} />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{quickAction.label}
|
||||
</span>
|
||||
</Button>
|
||||
)}
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu
|
||||
onOpenChange={(open) => {
|
||||
if (open) void invalidateGitQueries(queryClient);
|
||||
|
||||
@@ -46,21 +46,24 @@ 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: [],
|
||||
settings: {
|
||||
claude: { binaryPath: "" },
|
||||
codex: { binaryPath: "", homePath: "" },
|
||||
enableAssistantStreaming: false,
|
||||
defaultThreadEnvMode: "local" as const,
|
||||
customCodexModels: [],
|
||||
customClaudeModels: [],
|
||||
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
|
||||
providers: {
|
||||
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
|
||||
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { memo, useState, useCallback } from "react";
|
||||
import { type TimestampFormat } from "../appSettings";
|
||||
import { type TimestampFormat } from "@t3tools/contracts/settings";
|
||||
import { Badge } from "./ui/badge";
|
||||
import { Button } from "./ui/button";
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
|
||||
@@ -277,11 +277,11 @@ export default function ProjectScriptsControl({
|
||||
title={`Run ${primaryScript.name}`}
|
||||
>
|
||||
<ScriptIcon icon={primaryScript.icon} />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
{primaryScript.name}
|
||||
</span>
|
||||
</Button>
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu highlightItemOnHover={false}>
|
||||
<MenuTrigger
|
||||
render={<Button size="icon-xs" variant="outline" aria-label="Script actions" />}
|
||||
@@ -342,7 +342,7 @@ export default function ProjectScriptsControl({
|
||||
) : (
|
||||
<Button size="xs" variant="outline" onClick={openAddDialog} title="Add action">
|
||||
<PlusIcon className="size-3.5" />
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
Add action
|
||||
</span>
|
||||
</Button>
|
||||
|
||||
@@ -153,9 +153,9 @@ export function PullRequestThreadDialog({
|
||||
const validationMessage = !referenceDirty
|
||||
? null
|
||||
: reference.trim().length === 0
|
||||
? "Paste a GitHub pull request URL or enter 123 / #123."
|
||||
? "Paste a GitHub pull request URL, `gh pr checkout 123`, or enter 123 / #123."
|
||||
: parsedReference === null
|
||||
? "Use a GitHub pull request URL, 123, or #123."
|
||||
? "Use a GitHub pull request URL, `gh pr checkout 123`, 123, or #123."
|
||||
: null;
|
||||
const errorMessage =
|
||||
validationMessage ??
|
||||
@@ -191,7 +191,7 @@ export function PullRequestThreadDialog({
|
||||
<span className="text-xs font-medium text-foreground">Pull request</span>
|
||||
<Input
|
||||
ref={referenceInputRef}
|
||||
placeholder="https://github.com/owner/repo/pull/42 or #42"
|
||||
placeholder="https://github.com/owner/repo/pull/42, gh pr checkout 42, or #42"
|
||||
value={reference}
|
||||
onChange={(event) => {
|
||||
setReferenceDirty(true);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "../appSettings";
|
||||
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import type { Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
import {
|
||||
|
||||
@@ -41,8 +41,7 @@ import { useLocation, useNavigate, useParams } from "@tanstack/react-router";
|
||||
import {
|
||||
type SidebarProjectSortOrder,
|
||||
type SidebarThreadSortOrder,
|
||||
useAppSettings,
|
||||
} from "../appSettings";
|
||||
} from "@t3tools/contracts/settings";
|
||||
import { isElectron } from "../env";
|
||||
import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
|
||||
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
|
||||
@@ -102,6 +101,7 @@ import {
|
||||
sortThreadsForSidebar,
|
||||
} from "./Sidebar.logic";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
const THREAD_PREVIEW_LIMIT = 6;
|
||||
@@ -381,7 +381,8 @@ export default function Sidebar() {
|
||||
);
|
||||
const navigate = useNavigate();
|
||||
const isOnSettings = useLocation({ select: (loc) => loc.pathname === "/settings" });
|
||||
const { settings: appSettings, updateSettings } = useAppSettings();
|
||||
const appSettings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const { handleNewThread } = useHandleNewThread();
|
||||
const routeThreadId = useParams({
|
||||
strict: false,
|
||||
|
||||
@@ -62,7 +62,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
onToggleDiff,
|
||||
}: ChatHeaderProps) {
|
||||
return (
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center gap-2">
|
||||
<div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden sm:gap-3">
|
||||
<SidebarTrigger className="size-7 shrink-0 md:hidden" />
|
||||
<h2
|
||||
@@ -72,8 +72,8 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
{activeThreadTitle}
|
||||
</h2>
|
||||
{activeProjectName && (
|
||||
<Badge variant="outline" className="min-w-0 shrink truncate">
|
||||
{activeProjectName}
|
||||
<Badge variant="outline" className="min-w-0 shrink overflow-hidden">
|
||||
<span className="min-w-0 truncate">{activeProjectName}</span>
|
||||
</Badge>
|
||||
)}
|
||||
{activeProjectName && !isGitRepo && (
|
||||
@@ -82,7 +82,7 @@ export const ChatHeader = memo(function ChatHeader({
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="@container/header-actions flex min-w-0 flex-1 items-center justify-end gap-2 @sm/header-actions:gap-3">
|
||||
<div className="flex shrink-0 items-center justify-end gap-2 @3xl/header-actions:gap-3">
|
||||
{activeProjectScripts && (
|
||||
<ProjectScriptsControl
|
||||
scripts={activeProjectScripts}
|
||||
|
||||
@@ -43,6 +43,74 @@ 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,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
];
|
||||
const screen = await render(
|
||||
<CompactComposerControlsMenu
|
||||
activePlan={false}
|
||||
@@ -52,6 +120,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
|
||||
traitsMenuContent={
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
models={models}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
prompt={props?.prompt ?? ""}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type ProjectEntry, type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { BotIcon } from "lucide-react";
|
||||
@@ -27,7 +27,7 @@ export type ComposerCommandItem =
|
||||
id: string;
|
||||
type: "model";
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
label: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
@@ -48,7 +48,7 @@ import {
|
||||
type ParsedTerminalContextEntry,
|
||||
} from "~/lib/terminalContext";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { type TimestampFormat } from "../../appSettings";
|
||||
import { type TimestampFormat } from "@t3tools/contracts/settings";
|
||||
import { formatTimestamp } from "../../timestampFormat";
|
||||
import {
|
||||
buildInlineTerminalContextText,
|
||||
|
||||
@@ -22,6 +22,16 @@ const resolveOptions = (platform: string, availableEditors: ReadonlyArray<Editor
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode",
|
||||
},
|
||||
{
|
||||
label: "VS Code Insiders",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscode-insiders",
|
||||
},
|
||||
{
|
||||
label: "VSCodium",
|
||||
Icon: VisualStudioCode,
|
||||
value: "vscodium",
|
||||
},
|
||||
{
|
||||
label: "Zed",
|
||||
Icon: Zed,
|
||||
@@ -101,11 +111,11 @@ export const OpenInPicker = memo(function OpenInPicker({
|
||||
onClick={() => openInEditor(preferredEditor)}
|
||||
>
|
||||
{primaryOption?.Icon && <primaryOption.Icon aria-hidden="true" className="size-3.5" />}
|
||||
<span className="sr-only @sm/header-actions:not-sr-only @sm/header-actions:ml-0.5">
|
||||
<span className="sr-only @3xl/header-actions:not-sr-only @3xl/header-actions:ml-0.5">
|
||||
Open
|
||||
</span>
|
||||
</Button>
|
||||
<GroupSeparator className="hidden @sm/header-actions:block" />
|
||||
<GroupSeparator className="hidden @3xl/header-actions:block" />
|
||||
<Menu>
|
||||
<MenuTrigger render={<Button aria-label="Copy options" size="icon-xs" variant="outline" />}>
|
||||
<ChevronDownIcon aria-hidden="true" className="size-4" />
|
||||
|
||||
@@ -1,37 +1,139 @@
|
||||
import { type ModelSlug, type ProviderKind } from "@t3tools/contracts";
|
||||
import { type ProviderKind, type ServerProvider } 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";
|
||||
|
||||
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 }>>;
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
async function mountPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
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}
|
||||
modelOptionsByProvider={MODEL_OPTIONS_BY_PROVIDER}
|
||||
providers={providers}
|
||||
modelOptionsByProvider={modelOptionsByProvider}
|
||||
triggerVariant={props.triggerVariant}
|
||||
onProviderModelChange={onProviderModelChange}
|
||||
/>,
|
||||
@@ -159,6 +261,40 @@ 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 } from "@t3tools/contracts";
|
||||
import { type ProviderKind, type ServerProvider } from "@t3tools/contracts";
|
||||
import { resolveSelectableModel } from "@t3tools/shared/model";
|
||||
import { memo, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
@@ -20,6 +20,7 @@ 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;
|
||||
@@ -51,15 +52,16 @@ function providerIconClassName(
|
||||
|
||||
export const ProviderModelPicker = memo(function ProviderModelPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
lockedProvider: ProviderKind | null;
|
||||
providers?: ReadonlyArray<ServerProvider>;
|
||||
modelOptionsByProvider: Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>>;
|
||||
activeProviderIconClassName?: string;
|
||||
compact?: boolean;
|
||||
disabled?: boolean;
|
||||
triggerVariant?: VariantProps<typeof buttonVariants>["variant"];
|
||||
triggerClassName?: string;
|
||||
onProviderModelChange: (provider: ProviderKind, model: ModelSlug) => void;
|
||||
onProviderModelChange: (provider: ProviderKind, model: string) => void;
|
||||
}) {
|
||||
const [isMenuOpen, setIsMenuOpen] = useState(false);
|
||||
const activeProvider = props.lockedProvider ?? props.provider;
|
||||
@@ -145,6 +147,31 @@ 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>
|
||||
|
||||
+4
-4
@@ -1,14 +1,14 @@
|
||||
import { PROVIDER_DISPLAY_NAMES, type ServerProviderStatus } from "@t3tools/contracts";
|
||||
import { PROVIDER_DISPLAY_NAMES, type ServerProvider } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
|
||||
import { CircleAlertIcon } from "lucide-react";
|
||||
|
||||
export const ProviderHealthBanner = memo(function ProviderHealthBanner({
|
||||
export const ProviderStatusBanner = memo(function ProviderStatusBanner({
|
||||
status,
|
||||
}: {
|
||||
status: ServerProviderStatus | null;
|
||||
status: ServerProvider | null;
|
||||
}) {
|
||||
if (!status || status.status === "ready") {
|
||||
if (!status || status.status === "ready" || status.status === "disabled") {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@ import {
|
||||
ClaudeModelOptions,
|
||||
CodexModelOptions,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_SERVER_SETTINGS,
|
||||
ProjectId,
|
||||
type ServerProvider,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import { page } from "vitest/browser";
|
||||
@@ -21,10 +23,97 @@ import {
|
||||
useComposerThreadDraft,
|
||||
useEffectiveComposerModelState,
|
||||
} from "../../composerDraftStore";
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
|
||||
|
||||
// ── 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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
function ClaudeTraitsPickerHarness(props: {
|
||||
model: string;
|
||||
@@ -35,10 +124,14 @@ 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,
|
||||
customModelsByProvider: { codex: [], claudeAgent: [] },
|
||||
settings: {
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
},
|
||||
});
|
||||
const handlePromptChange = useCallback(
|
||||
(nextPrompt: string) => {
|
||||
@@ -50,6 +143,7 @@ function ClaudeTraitsPickerHarness(props: {
|
||||
return (
|
||||
<TraitsPicker
|
||||
provider="claudeAgent"
|
||||
models={TEST_PROVIDERS[1]!.models}
|
||||
threadId={CLAUDE_THREAD_ID}
|
||||
model={selectedModel ?? props.model}
|
||||
prompt={prompt}
|
||||
@@ -109,7 +203,7 @@ async function mountClaudePicker(props?: {
|
||||
? ({
|
||||
provider: "claudeAgent",
|
||||
model,
|
||||
options: props.fallbackModelOptions ?? undefined,
|
||||
...(props.fallbackModelOptions ? { options: props.fallbackModelOptions } : {}),
|
||||
} satisfies ModelSelection)
|
||||
: null;
|
||||
const screen = await render(
|
||||
@@ -293,6 +387,7 @@ 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=""
|
||||
@@ -359,10 +454,10 @@ describe("TraitsPicker (Codex)", () => {
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("Low");
|
||||
expect(text).toContain("Medium");
|
||||
expect(text).toContain("High");
|
||||
expect(text).toContain("Extra High");
|
||||
expect(text).toContain("High");
|
||||
expect(text).not.toContain("Low");
|
||||
expect(text).not.toContain("Medium");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -3,15 +3,17 @@ import {
|
||||
type CodexModelOptions,
|
||||
type ProviderKind,
|
||||
type ProviderModelOptions,
|
||||
type ServerProviderModel,
|
||||
type ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
applyClaudePromptEffortPrefix,
|
||||
getModelCapabilities,
|
||||
isClaudeUltrathinkPrompt,
|
||||
trimOrNull,
|
||||
getDefaultEffort,
|
||||
hasEffortLevel,
|
||||
getDefaultContextWindow,
|
||||
hasContextWindowOption,
|
||||
resolveEffort,
|
||||
} from "@t3tools/shared/model";
|
||||
import { memo, useCallback, useState } from "react";
|
||||
import type { VariantProps } from "class-variance-authority";
|
||||
@@ -27,6 +29,7 @@ import {
|
||||
MenuTrigger,
|
||||
} from "../ui/menu";
|
||||
import { useComposerDraftStore } from "../../composerDraftStore";
|
||||
import { getProviderModelCapabilities } from "../../providerModels";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
type ProviderOptions = ProviderModelOptions[ProviderKind];
|
||||
@@ -52,6 +55,16 @@ function getRawEffort(
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.effort);
|
||||
}
|
||||
|
||||
function getRawContextWindow(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
): string | null {
|
||||
if (provider === "claudeAgent") {
|
||||
return trimOrNull((modelOptions as ClaudeModelOptions | undefined)?.contextWindow);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function buildNextOptions(
|
||||
provider: ProviderKind,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
@@ -65,32 +78,22 @@ function buildNextOptions(
|
||||
|
||||
function getSelectedTraits(
|
||||
provider: ProviderKind,
|
||||
models: ReadonlyArray<ServerProviderModel>,
|
||||
model: string | null | undefined,
|
||||
prompt: string,
|
||||
modelOptions: ProviderOptions | null | undefined,
|
||||
allowPromptInjectedEffort: boolean,
|
||||
) {
|
||||
const caps = getModelCapabilities(provider, model);
|
||||
const caps = getProviderModelCapabilities(models, model, provider);
|
||||
const effortLevels = allowPromptInjectedEffort
|
||||
? caps.reasoningEffortLevels
|
||||
: caps.reasoningEffortLevels.filter(
|
||||
(option) => !caps.promptInjectedEffortLevels.includes(option.value),
|
||||
);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
// Resolve effort from options (provider-specific key)
|
||||
const resolvedEffort = getRawEffort(provider, modelOptions);
|
||||
|
||||
// Filter out prompt-injected efforts from the "current effort" display
|
||||
const isPromptInjected = resolvedEffort
|
||||
? caps.promptInjectedEffortLevels.includes(resolvedEffort)
|
||||
: false;
|
||||
const effort =
|
||||
resolvedEffort && !isPromptInjected && hasEffortLevel(caps, resolvedEffort)
|
||||
? resolvedEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const rawEffort = getRawEffort(provider, modelOptions);
|
||||
const effort = resolveEffort(caps, rawEffort) ?? null;
|
||||
|
||||
// Thinking toggle (only for models that support it)
|
||||
const thinkingEnabled = caps.supportsThinkingToggle
|
||||
@@ -102,6 +105,15 @@ function getSelectedTraits(
|
||||
caps.supportsFastMode &&
|
||||
(modelOptions as { fastMode?: boolean } | undefined)?.fastMode === true;
|
||||
|
||||
// Context window
|
||||
const contextWindowOptions = caps.contextWindowOptions;
|
||||
const rawContextWindow = getRawContextWindow(provider, modelOptions);
|
||||
const defaultContextWindow = getDefaultContextWindow(caps);
|
||||
const contextWindow =
|
||||
rawContextWindow && hasContextWindowOption(caps, rawContextWindow)
|
||||
? rawContextWindow
|
||||
: defaultContextWindow;
|
||||
|
||||
// Prompt-controlled effort (e.g. ultrathink in prompt text)
|
||||
const ultrathinkPromptControlled =
|
||||
allowPromptInjectedEffort &&
|
||||
@@ -114,12 +126,16 @@ function getSelectedTraits(
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
};
|
||||
}
|
||||
|
||||
export interface TraitsMenuContentProps {
|
||||
provider: ProviderKind;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
model: string | null | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
@@ -131,6 +147,7 @@ export interface TraitsMenuContentProps {
|
||||
|
||||
export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
provider,
|
||||
models,
|
||||
model,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
@@ -155,8 +172,11 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
|
||||
const handleEffortChange = useCallback(
|
||||
@@ -190,7 +210,7 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
],
|
||||
);
|
||||
|
||||
if (effort === null && thinkingEnabled === null) {
|
||||
if (effort === null && thinkingEnabled === null && contextWindowOptions.length <= 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -254,12 +274,40 @@ export const TraitsMenuContent = memo(function TraitsMenuContentImpl({
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
{contextWindowOptions.length > 1 ? (
|
||||
<>
|
||||
<MenuDivider />
|
||||
<MenuGroup>
|
||||
<div className="px-2 py-1.5 font-medium text-muted-foreground text-xs">
|
||||
Context Window
|
||||
</div>
|
||||
<MenuRadioGroup
|
||||
value={contextWindow ?? defaultContextWindow ?? ""}
|
||||
onValueChange={(value) => {
|
||||
updateModelOptions(
|
||||
buildNextOptions(provider, modelOptions, {
|
||||
contextWindow: value,
|
||||
}),
|
||||
);
|
||||
}}
|
||||
>
|
||||
{contextWindowOptions.map((option) => (
|
||||
<MenuRadioItem key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
{option.value === defaultContextWindow ? " (default)" : ""}
|
||||
</MenuRadioItem>
|
||||
))}
|
||||
</MenuRadioGroup>
|
||||
</MenuGroup>
|
||||
</>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
});
|
||||
|
||||
export const TraitsPicker = memo(function TraitsPicker({
|
||||
provider,
|
||||
models,
|
||||
model,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
@@ -276,12 +324,19 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
effortLevels,
|
||||
thinkingEnabled,
|
||||
fastModeEnabled,
|
||||
contextWindowOptions,
|
||||
contextWindow,
|
||||
defaultContextWindow,
|
||||
ultrathinkPromptControlled,
|
||||
} = getSelectedTraits(provider, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
} = getSelectedTraits(provider, models, model, prompt, modelOptions, allowPromptInjectedEffort);
|
||||
|
||||
const effortLabel = effort
|
||||
? (effortLevels.find((l) => l.value === effort)?.label ?? effort)
|
||||
: null;
|
||||
const contextWindowLabel =
|
||||
contextWindowOptions.length > 1 && contextWindow !== defaultContextWindow
|
||||
? (contextWindowOptions.find((o) => o.value === contextWindow)?.label ?? null)
|
||||
: null;
|
||||
const triggerLabel = [
|
||||
ultrathinkPromptControlled
|
||||
? "Ultrathink"
|
||||
@@ -291,6 +346,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
? null
|
||||
: `Thinking ${thinkingEnabled ? "On" : "Off"}`,
|
||||
...(caps.supportsFastMode && fastModeEnabled ? ["Fast"] : []),
|
||||
...(contextWindowLabel ? [contextWindowLabel] : []),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" · ");
|
||||
@@ -333,6 +389,7 @@ export const TraitsPicker = memo(function TraitsPicker({
|
||||
<MenuPopup align="start">
|
||||
<TraitsMenuContent
|
||||
provider={provider}
|
||||
models={models}
|
||||
model={model}
|
||||
prompt={prompt}
|
||||
onPromptChange={onPromptChange}
|
||||
|
||||
@@ -1,11 +1,82 @@
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "claude-haiku-4-5",
|
||||
name: "Claude Haiku 4.5",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
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,
|
||||
});
|
||||
@@ -13,7 +84,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,6 +94,7 @@ describe("getComposerProviderState", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
models: CODEX_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
@@ -44,6 +118,7 @@ describe("getComposerProviderState", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
models: CODEX_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
@@ -56,15 +131,17 @@ describe("getComposerProviderState", () => {
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit codex default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
it("preserves codex default effort explicitly in dispatch options", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
models: CODEX_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
codex: {
|
||||
@@ -77,7 +154,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "codex",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -85,6 +164,7 @@ describe("getComposerProviderState", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: undefined,
|
||||
});
|
||||
@@ -92,7 +172,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -100,6 +182,7 @@ describe("getComposerProviderState", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "Ultrathink:\nInvestigate this failure",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
@@ -124,6 +207,7 @@ describe("getComposerProviderState", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
@@ -146,6 +230,7 @@ describe("getComposerProviderState", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
@@ -158,15 +243,17 @@ describe("getComposerProviderState", () => {
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("drops explicit Claude default/off overrides from dispatch while keeping the selected effort label", () => {
|
||||
it("preserves Claude default effort explicitly in dispatch options", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
@@ -179,7 +266,9 @@ describe("getComposerProviderState", () => {
|
||||
expect(state).toEqual({
|
||||
provider: "claudeAgent",
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: undefined,
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,24 +1,22 @@
|
||||
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 { isClaudeUltrathinkPrompt, resolveEffort } 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;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
prompt: string;
|
||||
modelOptions: ProviderModelOptions | null | undefined;
|
||||
};
|
||||
@@ -36,14 +34,16 @@ type ProviderRegistryEntry = {
|
||||
getState: (input: ComposerProviderStateInput) => ComposerProviderState;
|
||||
renderTraitsMenuContent: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
}) => ReactNode;
|
||||
renderTraitsPicker: (input: {
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
@@ -53,8 +53,8 @@ type ProviderRegistryEntry = {
|
||||
function getProviderStateFromCapabilities(
|
||||
input: ComposerProviderStateInput,
|
||||
): ComposerProviderState {
|
||||
const { provider, model, prompt, modelOptions } = input;
|
||||
const caps = getModelCapabilities(provider, model);
|
||||
const { provider, model, models, prompt, modelOptions } = input;
|
||||
const caps = getProviderModelCapabilities(models, model, provider);
|
||||
const providerOptions = modelOptions?.[provider];
|
||||
|
||||
// Resolve effort
|
||||
@@ -66,23 +66,13 @@ function getProviderStateFromCapabilities(
|
||||
: null
|
||||
: null;
|
||||
|
||||
const draftEffort = trimOrNull(rawEffort);
|
||||
const defaultEffort = getDefaultEffort(caps);
|
||||
const isPromptInjected = draftEffort
|
||||
? caps.promptInjectedEffortLevels.includes(draftEffort)
|
||||
: false;
|
||||
const promptEffort =
|
||||
draftEffort && !isPromptInjected && hasEffortLevel(caps, draftEffort)
|
||||
? draftEffort
|
||||
: defaultEffort && hasEffortLevel(caps, defaultEffort)
|
||||
? defaultEffort
|
||||
: null;
|
||||
const promptEffort = resolveEffort(caps, rawEffort) ?? null;
|
||||
|
||||
// Normalize options for dispatch
|
||||
const normalizedOptions =
|
||||
provider === "codex"
|
||||
? normalizeCodexModelOptions(model, providerOptions)
|
||||
: normalizeClaudeModelOptions(model, providerOptions);
|
||||
? normalizeCodexModelOptionsWithCapabilities(caps, providerOptions)
|
||||
: normalizeClaudeModelOptionsWithCapabilities(caps, providerOptions);
|
||||
|
||||
// Ultrathink styling (driven by capabilities data, not provider identity)
|
||||
const ultrathinkActive =
|
||||
@@ -103,9 +93,17 @@ function getProviderStateFromCapabilities(
|
||||
const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
codex: {
|
||||
getState: (input) => getProviderStateFromCapabilities(input),
|
||||
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
renderTraitsMenuContent: ({
|
||||
threadId,
|
||||
model,
|
||||
models,
|
||||
modelOptions,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
}) => (
|
||||
<TraitsMenuContent
|
||||
provider="codex"
|
||||
models={models}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
@@ -113,9 +111,10 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
renderTraitsPicker: ({ threadId, model, models, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsPicker
|
||||
provider="codex"
|
||||
models={models}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
@@ -126,9 +125,17 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
},
|
||||
claudeAgent: {
|
||||
getState: (input) => getProviderStateFromCapabilities(input),
|
||||
renderTraitsMenuContent: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
renderTraitsMenuContent: ({
|
||||
threadId,
|
||||
model,
|
||||
models,
|
||||
modelOptions,
|
||||
prompt,
|
||||
onPromptChange,
|
||||
}) => (
|
||||
<TraitsMenuContent
|
||||
provider="claudeAgent"
|
||||
models={models}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
@@ -136,9 +143,10 @@ const composerProviderRegistry: Record<ProviderKind, ProviderRegistryEntry> = {
|
||||
onPromptChange={onPromptChange}
|
||||
/>
|
||||
),
|
||||
renderTraitsPicker: ({ threadId, model, modelOptions, prompt, onPromptChange }) => (
|
||||
renderTraitsPicker: ({ threadId, model, models, modelOptions, prompt, onPromptChange }) => (
|
||||
<TraitsPicker
|
||||
provider="claudeAgent"
|
||||
models={models}
|
||||
threadId={threadId}
|
||||
model={model}
|
||||
modelOptions={modelOptions}
|
||||
@@ -156,7 +164,8 @@ export function getComposerProviderState(input: ComposerProviderStateInput): Com
|
||||
export function renderProviderTraitsMenuContent(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
@@ -164,6 +173,7 @@ 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,
|
||||
@@ -173,7 +183,8 @@ export function renderProviderTraitsMenuContent(input: {
|
||||
export function renderProviderTraitsPicker(input: {
|
||||
provider: ProviderKind;
|
||||
threadId: ThreadId;
|
||||
model: ModelSlug;
|
||||
model: string;
|
||||
models: ReadonlyArray<ServerProviderModel>;
|
||||
modelOptions: ProviderModelOptions[ProviderKind] | undefined;
|
||||
prompt: string;
|
||||
onPromptChange: (prompt: string) => void;
|
||||
@@ -181,6 +192,7 @@ 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,
|
||||
|
||||
@@ -5,8 +5,10 @@ import { useEffect, type CSSProperties } from "react";
|
||||
import { useParams } from "@tanstack/react-router";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
CheckIcon,
|
||||
CircleAlertIcon,
|
||||
CircleCheckIcon,
|
||||
CopyIcon,
|
||||
InfoIcon,
|
||||
LoaderCircleIcon,
|
||||
TriangleAlertIcon,
|
||||
@@ -14,6 +16,7 @@ import {
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
import { buildVisibleToastLayout, shouldHideCollapsedToastContent } from "./toast.logic";
|
||||
|
||||
type ThreadToastData = {
|
||||
@@ -35,6 +38,25 @@ const TOAST_ICONS = {
|
||||
warning: TriangleAlertIcon,
|
||||
} as const;
|
||||
|
||||
function CopyErrorButton({ text }: { text: string }) {
|
||||
const { copyToClipboard, isCopied } = useCopyToClipboard();
|
||||
|
||||
return (
|
||||
<button
|
||||
className="shrink-0 cursor-pointer rounded-md p-1 text-muted-foreground opacity-60 transition-opacity hover:opacity-100"
|
||||
onClick={() => copyToClipboard(text)}
|
||||
title="Copy error"
|
||||
type="button"
|
||||
>
|
||||
{isCopied ? (
|
||||
<CheckIcon className="size-3.5 text-success" />
|
||||
) : (
|
||||
<CopyIcon className="size-3.5" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
type ToastPosition =
|
||||
| "top-left"
|
||||
| "top-center"
|
||||
@@ -284,12 +306,17 @@ function Toasts({ position = "top-right" }: { position: ToastPosition }) {
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<div className="flex items-center justify-between gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
@@ -373,12 +400,17 @@ function AnchoredToasts() {
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
<div className="flex items-center gap-1">
|
||||
<Toast.Title
|
||||
className="min-w-0 break-words font-medium"
|
||||
data-slot="toast-title"
|
||||
/>
|
||||
{toast.type === "error" && typeof toast.description === "string" && (
|
||||
<CopyErrorButton text={toast.description} />
|
||||
)}
|
||||
</div>
|
||||
<Toast.Description
|
||||
className="min-w-0 break-words text-muted-foreground"
|
||||
className="min-w-0 select-text break-words text-muted-foreground"
|
||||
data-slot="toast-description"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -2,23 +2,20 @@ import {
|
||||
CODEX_REASONING_EFFORT_OPTIONS,
|
||||
type ClaudeCodeEffort,
|
||||
type CodexReasoningEffort,
|
||||
type ModelSlug,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
ModelSelection,
|
||||
ProjectId,
|
||||
ProviderInteractionMode,
|
||||
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,
|
||||
resolveModelSlugForProvider,
|
||||
} from "@t3tools/shared/model";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
import { useMemo } from "react";
|
||||
import { getLocalStorageItem } from "./hooks/useLocalStorage";
|
||||
import { resolveAppModelSelection } from "./modelSelection";
|
||||
@@ -31,6 +28,8 @@ 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";
|
||||
|
||||
export const COMPOSER_DRAFT_STORAGE_KEY = "t3code:composer-drafts:v1";
|
||||
const COMPOSER_DRAFT_STORAGE_VERSION = 3;
|
||||
@@ -264,7 +263,7 @@ interface ComposerDraftStoreState {
|
||||
}
|
||||
|
||||
export interface EffectiveComposerModelState {
|
||||
selectedModel: ModelSlug;
|
||||
selectedModel: string;
|
||||
modelOptions: ProviderModelOptions | null;
|
||||
}
|
||||
|
||||
@@ -476,12 +475,20 @@ function normalizeProviderModelOptions(
|
||||
: claudeCandidate?.fastMode === false
|
||||
? false
|
||||
: undefined;
|
||||
const claudeContextWindow =
|
||||
typeof claudeCandidate?.contextWindow === "string" && claudeCandidate.contextWindow.length > 0
|
||||
? claudeCandidate.contextWindow
|
||||
: undefined;
|
||||
const claude =
|
||||
claudeThinking !== undefined || claudeEffort !== undefined || claudeFastMode !== undefined
|
||||
claudeThinking !== undefined ||
|
||||
claudeEffort !== undefined ||
|
||||
claudeFastMode !== undefined ||
|
||||
claudeContextWindow !== undefined
|
||||
? {
|
||||
...(claudeThinking !== undefined ? { thinking: claudeThinking } : {}),
|
||||
...(claudeEffort !== undefined ? { effort: claudeEffort } : {}),
|
||||
...(claudeFastMode !== undefined ? { fastMode: claudeFastMode } : {}),
|
||||
...(claudeContextWindow !== undefined ? { contextWindow: claudeContextWindow } : {}),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
@@ -595,7 +602,7 @@ function legacyToModelSelectionByProvider(
|
||||
model:
|
||||
modelSelection?.provider === provider
|
||||
? modelSelection.model
|
||||
: getDefaultModel(provider),
|
||||
: DEFAULT_MODEL_BY_PROVIDER[provider],
|
||||
options,
|
||||
};
|
||||
}
|
||||
@@ -613,22 +620,23 @@ export function deriveEffectiveComposerModelState(input: {
|
||||
| Pick<ComposerThreadDraftState, "modelSelectionByProvider" | "activeProvider">
|
||||
| null
|
||||
| undefined;
|
||||
providers: ReadonlyArray<ServerProvider>;
|
||||
selectedProvider: ProviderKind;
|
||||
threadModelSelection: ModelSelection | null | undefined;
|
||||
projectModelSelection: ModelSelection | null | undefined;
|
||||
customModelsByProvider: Record<ProviderKind, readonly string[]>;
|
||||
settings: UnifiedSettings;
|
||||
}): EffectiveComposerModelState {
|
||||
const baseModel = resolveModelSlugForProvider(
|
||||
input.selectedProvider,
|
||||
input.threadModelSelection?.model ??
|
||||
input.projectModelSelection?.model ??
|
||||
getDefaultModel(input.selectedProvider),
|
||||
);
|
||||
const baseModel =
|
||||
normalizeModelSlug(
|
||||
input.threadModelSelection?.model ?? input.projectModelSelection?.model,
|
||||
input.selectedProvider,
|
||||
) ?? getDefaultServerModel(input.providers, input.selectedProvider);
|
||||
const activeSelection = input.draft?.modelSelectionByProvider?.[input.selectedProvider];
|
||||
const selectedModel = activeSelection?.model
|
||||
? resolveAppModelSelection(
|
||||
input.selectedProvider,
|
||||
input.customModelsByProvider,
|
||||
input.settings,
|
||||
input.providers,
|
||||
activeSelection.model,
|
||||
)
|
||||
: baseModel;
|
||||
@@ -1676,7 +1684,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (opts) {
|
||||
nextMap[provider] = {
|
||||
provider,
|
||||
model: current?.model ?? getDefaultModel(provider),
|
||||
model: current?.model ?? DEFAULT_MODEL_BY_PROVIDER[provider],
|
||||
options: opts,
|
||||
};
|
||||
} else if (current?.options) {
|
||||
@@ -1726,7 +1734,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
if (providerOpts) {
|
||||
nextMap[normalizedProvider] = {
|
||||
provider: normalizedProvider,
|
||||
model: currentForProvider?.model ?? getDefaultModel(normalizedProvider),
|
||||
model: currentForProvider?.model ?? DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
options: providerOpts,
|
||||
};
|
||||
} else if (currentForProvider?.options) {
|
||||
@@ -1744,7 +1752,7 @@ export const useComposerDraftStore = create<ComposerDraftStoreState>()(
|
||||
base.modelSelectionByProvider[normalizedProvider] ??
|
||||
({
|
||||
provider: normalizedProvider,
|
||||
model: getDefaultModel(normalizedProvider),
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[normalizedProvider],
|
||||
} as ModelSelection);
|
||||
if (providerOpts) {
|
||||
nextStickyMap[normalizedProvider] = {
|
||||
@@ -2157,10 +2165,11 @@ 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;
|
||||
customModelsByProvider: Record<ProviderKind, readonly string[]>;
|
||||
settings: UnifiedSettings;
|
||||
}): EffectiveComposerModelState {
|
||||
const draft = useComposerThreadDraft(input.threadId);
|
||||
|
||||
@@ -2168,14 +2177,16 @@ export function useEffectiveComposerModelState(input: {
|
||||
() =>
|
||||
deriveEffectiveComposerModelState({
|
||||
draft,
|
||||
providers: input.providers,
|
||||
selectedProvider: input.selectedProvider,
|
||||
threadModelSelection: input.threadModelSelection,
|
||||
projectModelSelection: input.projectModelSelection,
|
||||
customModelsByProvider: input.customModelsByProvider,
|
||||
settings: input.settings,
|
||||
}),
|
||||
[
|
||||
draft,
|
||||
input.customModelsByProvider,
|
||||
input.providers,
|
||||
input.settings,
|
||||
input.projectModelSelection,
|
||||
input.selectedProvider,
|
||||
input.threadModelSelection,
|
||||
|
||||
@@ -11,22 +11,34 @@
|
||||
*/
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { ServerSettings, ServerSettingsPatch, ServerConfig } from "@t3tools/contracts";
|
||||
import {
|
||||
ServerSettings,
|
||||
ServerSettingsPatch,
|
||||
ServerConfig,
|
||||
ModelSelection,
|
||||
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 {
|
||||
ClientSettingsSchema,
|
||||
type ClientSettings,
|
||||
DEFAULT_CLIENT_SETTINGS,
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
} from "~/clientSettings";
|
||||
import { Struct } from "effect";
|
||||
import { normalizeCustomModelSlugs } from "~/modelSelection";
|
||||
import { Predicate, Schema, Struct } from "effect";
|
||||
import { DeepMutable } from "effect/Types";
|
||||
import { deepMerge } from "@t3tools/shared/Struct";
|
||||
|
||||
// ── Unified type ─────────────────────────────────────────────────────
|
||||
|
||||
export type UnifiedSettings = ServerSettings & ClientSettings;
|
||||
const CLIENT_SETTINGS_STORAGE_KEY = "t3code:client-settings:v1";
|
||||
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
|
||||
|
||||
// ── Key sets for routing patches ─────────────────────────────────────
|
||||
|
||||
@@ -103,7 +115,7 @@ export function useUpdateSettings() {
|
||||
if (!old) return old;
|
||||
return {
|
||||
...old,
|
||||
settings: { ...old.settings, ...serverPatch },
|
||||
settings: deepMerge(old.settings, serverPatch),
|
||||
};
|
||||
});
|
||||
// Fire-and-forget RPC — push will reconcile on success
|
||||
@@ -118,85 +130,137 @@ export function useUpdateSettings() {
|
||||
);
|
||||
|
||||
const resetSettings = useCallback(() => {
|
||||
updateSettings({
|
||||
...DEFAULT_SERVER_SETTINGS,
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
});
|
||||
updateSettings(DEFAULT_UNIFIED_SETTINGS);
|
||||
}, [updateSettings]);
|
||||
|
||||
return {
|
||||
updateSettings,
|
||||
resetSettings,
|
||||
defaults: { ...DEFAULT_SERVER_SETTINGS, ...DEFAULT_CLIENT_SETTINGS } as UnifiedSettings,
|
||||
};
|
||||
}
|
||||
|
||||
// ── One-time migration from localStorage ─────────────────────────────
|
||||
|
||||
const MIGRATION_FLAG_KEY = "t3code:settings-migrated:v1";
|
||||
const OLD_SETTINGS_KEY = "t3code:app-settings:v1";
|
||||
export function buildLegacyServerSettingsMigrationPatch(legacySettings: Record<string, unknown>) {
|
||||
const patch: DeepMutable<ServerSettingsPatch> = {};
|
||||
|
||||
if (Predicate.isBoolean(legacySettings.enableAssistantStreaming)) {
|
||||
patch.enableAssistantStreaming = legacySettings.enableAssistantStreaming;
|
||||
}
|
||||
|
||||
if (Schema.is(ThreadEnvMode)(legacySettings.defaultThreadEnvMode)) {
|
||||
patch.defaultThreadEnvMode = legacySettings.defaultThreadEnvMode;
|
||||
}
|
||||
|
||||
if (Schema.is(ModelSelection)(legacySettings.textGenerationModelSelection)) {
|
||||
patch.textGenerationModelSelection = legacySettings.textGenerationModelSelection;
|
||||
}
|
||||
|
||||
if (typeof legacySettings.codexBinaryPath === "string") {
|
||||
patch.providers ??= {};
|
||||
patch.providers.codex ??= {};
|
||||
patch.providers.codex.binaryPath = legacySettings.codexBinaryPath;
|
||||
}
|
||||
|
||||
if (typeof legacySettings.codexHomePath === "string") {
|
||||
patch.providers ??= {};
|
||||
patch.providers.codex ??= {};
|
||||
patch.providers.codex.homePath = legacySettings.codexHomePath;
|
||||
}
|
||||
|
||||
if (Array.isArray(legacySettings.customCodexModels)) {
|
||||
patch.providers ??= {};
|
||||
patch.providers.codex ??= {};
|
||||
patch.providers.codex.customModels = normalizeCustomModelSlugs(
|
||||
legacySettings.customCodexModels,
|
||||
new Set<string>(),
|
||||
"codex",
|
||||
);
|
||||
}
|
||||
|
||||
if (Predicate.isString(legacySettings.claudeBinaryPath)) {
|
||||
patch.providers ??= {};
|
||||
patch.providers.claudeAgent ??= {};
|
||||
patch.providers.claudeAgent.binaryPath = legacySettings.claudeBinaryPath;
|
||||
}
|
||||
|
||||
if (Array.isArray(legacySettings.customClaudeModels)) {
|
||||
patch.providers ??= {};
|
||||
patch.providers.claudeAgent ??= {};
|
||||
patch.providers.claudeAgent.customModels = normalizeCustomModelSlugs(
|
||||
legacySettings.customClaudeModels,
|
||||
new Set<string>(),
|
||||
"claudeAgent",
|
||||
);
|
||||
}
|
||||
|
||||
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. Migrates server-relevant settings from the
|
||||
* old localStorage key to the server. Idempotent.
|
||||
* 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.
|
||||
*/
|
||||
export function migrateLocalSettingsToServer(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
if (localStorage.getItem(MIGRATION_FLAG_KEY)) return;
|
||||
|
||||
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
|
||||
if (!raw) {
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
return;
|
||||
}
|
||||
if (!raw) return;
|
||||
|
||||
try {
|
||||
const old = JSON.parse(raw) as Record<string, unknown>;
|
||||
const serverPatch: Record<string, unknown> = {};
|
||||
for (const key of SERVER_SETTINGS_KEYS) {
|
||||
if (key in old && old[key] !== undefined) {
|
||||
serverPatch[key] = old[key];
|
||||
}
|
||||
}
|
||||
|
||||
// Migrate old flat binary-path keys into their new nested shape
|
||||
const codexBinaryPath = old["codexBinaryPath"];
|
||||
const codexHomePath = old["codexHomePath"];
|
||||
const claudeBinaryPath = old["claudeBinaryPath"];
|
||||
|
||||
if (
|
||||
(typeof codexBinaryPath === "string" && codexBinaryPath) ||
|
||||
(typeof codexHomePath === "string" && codexHomePath)
|
||||
) {
|
||||
const existing = (serverPatch["codex"] as Record<string, unknown> | undefined) ?? {};
|
||||
serverPatch["codex"] = {
|
||||
...existing,
|
||||
...(typeof codexBinaryPath === "string" && codexBinaryPath
|
||||
? { binaryPath: codexBinaryPath }
|
||||
: {}),
|
||||
...(typeof codexHomePath === "string" && codexHomePath ? { homePath: codexHomePath } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (typeof claudeBinaryPath === "string" && claudeBinaryPath) {
|
||||
const existing = (serverPatch["claude"] as Record<string, unknown> | undefined) ?? {};
|
||||
serverPatch["claude"] = {
|
||||
...existing,
|
||||
binaryPath: claudeBinaryPath,
|
||||
};
|
||||
}
|
||||
const old = JSON.parse(raw);
|
||||
if (!Predicate.isObject(old)) return;
|
||||
|
||||
// Migrate server-relevant keys via RPC
|
||||
const serverPatch = buildLegacyServerSettingsMigrationPatch(old);
|
||||
if (Object.keys(serverPatch).length > 0) {
|
||||
void ensureNativeApi()
|
||||
.server.updateSettings(serverPatch as ServerSettingsPatch)
|
||||
.then(() => {
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
});
|
||||
} else {
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
const api = ensureNativeApi();
|
||||
void api.server.updateSettings(serverPatch);
|
||||
}
|
||||
} catch {
|
||||
// If parsing fails, mark as migrated to avoid retrying
|
||||
localStorage.setItem(MIGRATION_FLAG_KEY, "true");
|
||||
|
||||
// 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 }),
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[MIGRATION] Error migrating local settings:", error);
|
||||
} finally {
|
||||
// Remove the legacy key regardless to keep migration one-shot behavior.
|
||||
localStorage.removeItem(OLD_SETTINGS_KEY);
|
||||
}
|
||||
}
|
||||
@@ -32,10 +32,6 @@ describe("git mutation options", () => {
|
||||
const options = gitRunStackedActionMutationOptions({
|
||||
cwd: "/repo/a",
|
||||
queryClient,
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
},
|
||||
});
|
||||
expect(options.mutationKey).toEqual(gitMutationKeys.runStackedAction("/repo/a"));
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type GitStackedAction, type ModelSelection } from "@t3tools/contracts";
|
||||
import { type GitStackedAction } from "@t3tools/contracts";
|
||||
import { mutationOptions, queryOptions, type QueryClient } from "@tanstack/react-query";
|
||||
import { ensureNativeApi } from "../nativeApi";
|
||||
|
||||
@@ -112,7 +112,6 @@ export function gitCheckoutMutationOptions(input: {
|
||||
export function gitRunStackedActionMutationOptions(input: {
|
||||
cwd: string | null;
|
||||
queryClient: QueryClient;
|
||||
modelSelection: ModelSelection;
|
||||
}) {
|
||||
return mutationOptions({
|
||||
mutationKey: gitMutationKeys.runStackedAction(input.cwd),
|
||||
@@ -134,7 +133,6 @@ export function gitRunStackedActionMutationOptions(input: {
|
||||
return api.git.runStackedAction({
|
||||
actionId,
|
||||
cwd: input.cwd,
|
||||
modelSelection: input.modelSelection,
|
||||
action,
|
||||
...(commitMessage ? { commitMessage } : {}),
|
||||
...(featureBranch ? { featureBranch } : {}),
|
||||
|
||||
@@ -6,6 +6,13 @@ export const serverQueryKeys = {
|
||||
config: () => ["server", "config"] as const,
|
||||
};
|
||||
|
||||
/**
|
||||
* Server config query options.
|
||||
*
|
||||
* `staleTime` is kept short so that push-driven `invalidateQueries` calls in
|
||||
* the EventRouter always trigger a refetch, and so the query re-fetches when
|
||||
* the component re-mounts (e.g. navigating away from settings and back).
|
||||
*/
|
||||
export function serverConfigQueryOptions() {
|
||||
return queryOptions({
|
||||
queryKey: serverQueryKeys.config(),
|
||||
@@ -13,6 +20,5 @@ export function serverConfigQueryOptions() {
|
||||
const api = ensureNativeApi();
|
||||
return api.server.getConfig();
|
||||
},
|
||||
staleTime: Infinity,
|
||||
});
|
||||
}
|
||||
+114
-1
@@ -9,6 +9,8 @@ import "./index.css";
|
||||
import { isElectron } from "./env";
|
||||
import { getRouter } from "./router";
|
||||
import { APP_DISPLAY_NAME } from "./branding";
|
||||
import { ensureBrowserPairing } from "./browserAuth";
|
||||
import { initializeNativeApi } from "./nativeApi";
|
||||
|
||||
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
|
||||
const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
@@ -16,9 +18,120 @@ const history = isElectron ? createHashHistory() : createBrowserHistory();
|
||||
const router = getRouter(history);
|
||||
|
||||
document.title = APP_DISPLAY_NAME;
|
||||
const UNPAIRED_RETRY_INTERVAL_MS = 1_000;
|
||||
|
||||
function PairingRequiredScreen() {
|
||||
return (
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">
|
||||
<div className="pointer-events-none absolute inset-0 opacity-80">
|
||||
<div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(42rem_16rem_at_top,color-mix(in_srgb,var(--color-amber-500)_16%,transparent),transparent)]" />
|
||||
<div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_92%,var(--color-black))_0%,var(--background)_56%)]" />
|
||||
</div>
|
||||
|
||||
<section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">
|
||||
<p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">
|
||||
{APP_DISPLAY_NAME}
|
||||
</p>
|
||||
<h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">
|
||||
Browser pairing required
|
||||
</h1>
|
||||
<p className="mt-2 text-sm leading-relaxed text-muted-foreground">
|
||||
This browser is not paired with the local T3 session.
|
||||
</p>
|
||||
<p className="mt-3 text-sm leading-relaxed text-muted-foreground">
|
||||
Restart <code>t3</code> to open a paired browser, or open the pairing URL printed in the
|
||||
CLI.
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BootstrappedApp() {
|
||||
const [state, setState] = React.useState<"loading" | "ready" | "unpaired">("loading");
|
||||
|
||||
React.useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
void ensureBrowserPairing()
|
||||
.then((authenticated) => {
|
||||
if (!active) return;
|
||||
if (!authenticated) {
|
||||
setState("unpaired");
|
||||
return;
|
||||
}
|
||||
initializeNativeApi();
|
||||
setState("ready");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
setState("unpaired");
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, []);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (state !== "unpaired") {
|
||||
return;
|
||||
}
|
||||
|
||||
let active = true;
|
||||
let retryTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const retry = () => {
|
||||
void ensureBrowserPairing()
|
||||
.then((authenticated) => {
|
||||
if (!active || !authenticated) {
|
||||
if (active) {
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
}
|
||||
return;
|
||||
}
|
||||
initializeNativeApi();
|
||||
setState("ready");
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) {
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
retryTimeout = setTimeout(retry, UNPAIRED_RETRY_INTERVAL_MS);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
if (retryTimeout !== null) {
|
||||
clearTimeout(retryTimeout);
|
||||
}
|
||||
};
|
||||
}, [state]);
|
||||
|
||||
if (state === "loading") {
|
||||
return (
|
||||
<div className="flex h-screen flex-col bg-background text-foreground">
|
||||
<div className="flex flex-1 items-center justify-center">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Connecting to {APP_DISPLAY_NAME} server...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (state === "unpaired") {
|
||||
return <PairingRequiredScreen />;
|
||||
}
|
||||
|
||||
return <RouterProvider router={router} />;
|
||||
}
|
||||
|
||||
ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
|
||||
<React.StrictMode>
|
||||
<RouterProvider router={router} />
|
||||
<BootstrappedApp />
|
||||
</React.StrictMode>,
|
||||
);
|
||||
@@ -2,27 +2,22 @@ import {
|
||||
DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import {
|
||||
getDefaultModel,
|
||||
getModelOptions,
|
||||
normalizeModelSlug,
|
||||
resolveSelectableModel,
|
||||
} from "@t3tools/shared/model";
|
||||
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";
|
||||
|
||||
const MAX_CUSTOM_MODEL_COUNT = 32;
|
||||
export const MAX_CUSTOM_MODEL_LENGTH = 256;
|
||||
|
||||
export type CustomModelSettings = {
|
||||
customCodexModels: readonly string[];
|
||||
customClaudeModels: readonly string[];
|
||||
};
|
||||
|
||||
export type ProviderCustomModelConfig = {
|
||||
provider: ProviderKind;
|
||||
settingsKey: keyof CustomModelSettings;
|
||||
defaultSettingsKey: keyof CustomModelSettings;
|
||||
title: string;
|
||||
description: string;
|
||||
placeholder: string;
|
||||
@@ -38,8 +33,6 @@ export interface AppModelOption {
|
||||
const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConfig> = {
|
||||
codex: {
|
||||
provider: "codex",
|
||||
settingsKey: "customCodexModels",
|
||||
defaultSettingsKey: "customCodexModels",
|
||||
title: "Codex",
|
||||
description: "Save additional Codex model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-codex-model-slug",
|
||||
@@ -47,8 +40,6 @@ const PROVIDER_CUSTOM_MODEL_CONFIG: Record<ProviderKind, ProviderCustomModelConf
|
||||
},
|
||||
claudeAgent: {
|
||||
provider: "claudeAgent",
|
||||
settingsKey: "customClaudeModels",
|
||||
defaultSettingsKey: "customClaudeModels",
|
||||
title: "Claude",
|
||||
description: "Save additional Claude model slugs for the picker and `/model` command.",
|
||||
placeholder: "your-claude-model-slug",
|
||||
@@ -56,20 +47,15 @@ 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);
|
||||
@@ -92,52 +78,29 @@ export function normalizeCustomModelSlugs(
|
||||
return normalizedModels;
|
||||
}
|
||||
|
||||
export function getCustomModelsForProvider(
|
||||
settings: CustomModelSettings,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return settings[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey];
|
||||
}
|
||||
|
||||
export function getDefaultCustomModelsForProvider(
|
||||
defaults: CustomModelSettings,
|
||||
provider: ProviderKind,
|
||||
): readonly string[] {
|
||||
return defaults[PROVIDER_CUSTOM_MODEL_CONFIG[provider].defaultSettingsKey];
|
||||
}
|
||||
|
||||
export function patchCustomModels(
|
||||
provider: ProviderKind,
|
||||
models: string[],
|
||||
): Partial<CustomModelSettings> {
|
||||
return {
|
||||
[PROVIDER_CUSTOM_MODEL_CONFIG[provider].settingsKey]: models,
|
||||
};
|
||||
}
|
||||
|
||||
export function getCustomModelsByProvider(
|
||||
settings: CustomModelSettings,
|
||||
): Record<ProviderKind, readonly string[]> {
|
||||
return {
|
||||
codex: getCustomModelsForProvider(settings, "codex"),
|
||||
claudeAgent: getCustomModelsForProvider(settings, "claudeAgent"),
|
||||
};
|
||||
}
|
||||
|
||||
export function getAppModelOptions(
|
||||
settings: UnifiedSettings,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
provider: ProviderKind,
|
||||
customModels: readonly string[],
|
||||
selectedModel?: string | null,
|
||||
): AppModelOption[] {
|
||||
const options: AppModelOption[] = getModelOptions(provider).map(({ slug, name }) => ({
|
||||
slug,
|
||||
name,
|
||||
isCustom: false,
|
||||
}));
|
||||
const options: AppModelOption[] = getProviderModels(providers, provider).map(
|
||||
({ slug, name, isCustom }) => ({
|
||||
slug,
|
||||
name,
|
||||
isCustom,
|
||||
}),
|
||||
);
|
||||
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),
|
||||
);
|
||||
|
||||
for (const slug of normalizeCustomModelSlugs(customModels, provider)) {
|
||||
const customModels = settings.providers[provider].customModels;
|
||||
for (const slug of normalizeCustomModelSlugs(customModels, builtInModelSlugs, provider)) {
|
||||
if (seen.has(slug)) {
|
||||
continue;
|
||||
}
|
||||
@@ -171,52 +134,61 @@ export function getAppModelOptions(
|
||||
|
||||
export function resolveAppModelSelection(
|
||||
provider: ProviderKind,
|
||||
customModels: Record<ProviderKind, readonly string[]>,
|
||||
settings: UnifiedSettings,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
selectedModel: string | null | undefined,
|
||||
): string {
|
||||
const customModelsForProvider = customModels[provider];
|
||||
const options = getAppModelOptions(provider, customModelsForProvider, selectedModel);
|
||||
return resolveSelectableModel(provider, selectedModel, options) ?? getDefaultModel(provider);
|
||||
const resolvedProvider = resolveSelectableProvider(providers, provider);
|
||||
const options = getAppModelOptions(settings, providers, resolvedProvider, selectedModel);
|
||||
return (
|
||||
resolveSelectableModel(resolvedProvider, selectedModel, options) ??
|
||||
getDefaultServerModel(providers, resolvedProvider)
|
||||
);
|
||||
}
|
||||
|
||||
export function getCustomModelOptionsByProvider(
|
||||
settings: CustomModelSettings,
|
||||
settings: UnifiedSettings,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
selectedProvider?: ProviderKind | null,
|
||||
selectedModel?: string | null,
|
||||
): Record<ProviderKind, ReadonlyArray<{ slug: string; name: string }>> {
|
||||
const customModelsByProvider = getCustomModelsByProvider(settings);
|
||||
return {
|
||||
codex: getAppModelOptions(
|
||||
settings,
|
||||
providers,
|
||||
"codex",
|
||||
customModelsByProvider.codex,
|
||||
selectedProvider === "codex" ? selectedModel : undefined,
|
||||
),
|
||||
claudeAgent: getAppModelOptions(
|
||||
settings,
|
||||
providers,
|
||||
"claudeAgent",
|
||||
customModelsByProvider.claudeAgent,
|
||||
selectedProvider === "claudeAgent" ? selectedModel : undefined,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveAppModelSelectionState(
|
||||
settings: CustomModelSettings & {
|
||||
textGenerationModelSelection: ModelSelection | undefined;
|
||||
},
|
||||
settings: UnifiedSettings,
|
||||
providers: ReadonlyArray<ServerProvider>,
|
||||
): ModelSelection {
|
||||
const selection = settings.textGenerationModelSelection ?? {
|
||||
provider: "codex" as const,
|
||||
model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER.codex,
|
||||
};
|
||||
const provider = selection.provider;
|
||||
const customModelsByProvider = getCustomModelsByProvider(settings);
|
||||
const model = resolveAppModelSelection(provider, customModelsByProvider, selection.model);
|
||||
const 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 { modelOptionsForDispatch } = getComposerProviderState({
|
||||
provider,
|
||||
model,
|
||||
models: getProviderModels(providers, provider),
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
[provider]: selection.options,
|
||||
[provider]: provider === selection.provider ? selection.options : undefined,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,21 @@ import { createWsNativeApi } from "./wsNativeApi";
|
||||
|
||||
let cachedApi: NativeApi | undefined;
|
||||
|
||||
export function initializeNativeApi(): NativeApi {
|
||||
if (typeof window === "undefined") {
|
||||
throw new Error("Native API not available outside the browser");
|
||||
}
|
||||
if (cachedApi) return cachedApi;
|
||||
|
||||
if (window.nativeApi) {
|
||||
cachedApi = window.nativeApi;
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
cachedApi = createWsNativeApi();
|
||||
return cachedApi;
|
||||
}
|
||||
|
||||
export function readNativeApi(): NativeApi | undefined {
|
||||
if (typeof window === "undefined") return undefined;
|
||||
if (cachedApi) return cachedApi;
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type ModelCapabilities,
|
||||
type ProviderKind,
|
||||
type ServerProvider,
|
||||
type ServerProviderModel,
|
||||
} from "@t3tools/contracts";
|
||||
import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
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 reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastModeEnabled = modelOptions?.fastMode === true;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastModeEnabled ? { fastMode: true } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function normalizeClaudeModelOptionsWithCapabilities(
|
||||
caps: ModelCapabilities,
|
||||
modelOptions: ClaudeModelOptions | null | undefined,
|
||||
): ClaudeModelOptions | undefined {
|
||||
const effort = resolveEffort(caps, modelOptions?.effort);
|
||||
const thinking =
|
||||
caps.supportsThinkingToggle && modelOptions?.thinking === false ? false : undefined;
|
||||
const fastMode = caps.supportsFastMode && modelOptions?.fastMode === true ? true : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking === false ? { thinking: false } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
...(contextWindow ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
@@ -17,6 +17,20 @@ describe("parsePullRequestReference", () => {
|
||||
expect(parsePullRequestReference("#42")).toBe("#42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with raw numbers", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout 42")).toBe("42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with #number references", () => {
|
||||
expect(parsePullRequestReference("gh pr checkout #42")).toBe("#42");
|
||||
});
|
||||
|
||||
it("accepts gh pr checkout commands with GitHub pull request URLs", () => {
|
||||
expect(
|
||||
parsePullRequestReference("gh pr checkout https://github.com/pingdotgg/t3code/pull/42"),
|
||||
).toBe("https://github.com/pingdotgg/t3code/pull/42");
|
||||
});
|
||||
|
||||
it("rejects non-pull-request input", () => {
|
||||
expect(parsePullRequestReference("feature/my-branch")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
const GITHUB_PULL_REQUEST_URL_PATTERN =
|
||||
/^https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/(\d+)(?:[/?#].*)?$/i;
|
||||
const PULL_REQUEST_NUMBER_PATTERN = /^#?(\d+)$/;
|
||||
const GITHUB_CLI_PR_CHECKOUT_PATTERN = /^gh\s+pr\s+checkout\s+(.+)$/i;
|
||||
|
||||
export function parsePullRequestReference(input: string): string | null {
|
||||
const trimmed = input.trim();
|
||||
@@ -8,14 +9,20 @@ export function parsePullRequestReference(input: string): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(trimmed);
|
||||
if (urlMatch?.[1]) {
|
||||
return trimmed;
|
||||
const ghCliCheckoutMatch = GITHUB_CLI_PR_CHECKOUT_PATTERN.exec(trimmed);
|
||||
const normalizedInput = ghCliCheckoutMatch?.[1]?.trim() ?? trimmed;
|
||||
if (normalizedInput.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(trimmed);
|
||||
const urlMatch = GITHUB_PULL_REQUEST_URL_PATTERN.exec(normalizedInput);
|
||||
if (urlMatch?.[1]) {
|
||||
return normalizedInput;
|
||||
}
|
||||
|
||||
const numberMatch = PULL_REQUEST_NUMBER_PATTERN.exec(normalizedInput);
|
||||
if (numberMatch?.[1]) {
|
||||
return trimmed.startsWith("#") ? trimmed : numberMatch[1];
|
||||
return normalizedInput.startsWith("#") ? normalizedInput : numberMatch[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
|
||||
@@ -20,7 +20,7 @@ import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDra
|
||||
import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||
@@ -263,8 +263,14 @@ function EventRouter() {
|
||||
// don't produce duplicate toasts.
|
||||
let subscribed = false;
|
||||
const unsubServerConfigUpdated = onServerConfigUpdated((payload) => {
|
||||
// Invalidate the config query so active observers refetch fresh data.
|
||||
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
|
||||
|
||||
if (!subscribed) return;
|
||||
|
||||
// Only show keybindings toasts for keybindings changes (no settings in payload)
|
||||
if (payload.settings) return;
|
||||
|
||||
const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings."));
|
||||
if (!issue) {
|
||||
toastManager.add({
|
||||
@@ -303,6 +309,9 @@ function EventRouter() {
|
||||
},
|
||||
});
|
||||
});
|
||||
const unsubProvidersUpdated = onServerProvidersUpdated(() => {
|
||||
void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() });
|
||||
});
|
||||
subscribed = true;
|
||||
return () => {
|
||||
disposed = true;
|
||||
@@ -312,6 +321,7 @@ function EventRouter() {
|
||||
unsubTerminalEvent();
|
||||
unsubWelcome();
|
||||
unsubServerConfigUpdated();
|
||||
unsubProvidersUpdated();
|
||||
};
|
||||
}, [
|
||||
navigate,
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,7 +11,7 @@ import { resolveShortcutCommand } from "../keybindings";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { useThreadSelectionStore } from "../threadSelectionStore";
|
||||
import { resolveSidebarNewThreadEnvMode } from "~/components/Sidebar.logic";
|
||||
import { useAppSettings } from "~/appSettings";
|
||||
import { useSettings } from "~/hooks/useSettings";
|
||||
import { Sidebar, SidebarProvider, SidebarRail } from "~/components/ui/sidebar";
|
||||
|
||||
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
|
||||
@@ -31,7 +31,7 @@ function ChatRouteGlobalShortcuts() {
|
||||
? selectThreadTerminalState(state.terminalStateByThreadId, routeThreadId).terminalOpen
|
||||
: false,
|
||||
);
|
||||
const { settings: appSettings } = useAppSettings();
|
||||
const appSettings = useSettings();
|
||||
|
||||
useEffect(() => {
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
|
||||
+2
-22
@@ -9,6 +9,7 @@ import { resolveModelSlugForProvider } from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import { type ChatMessage, type Project, type Thread } from "./types";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
import { resolveServerHttpOrigin } from "./browserAuth";
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -199,30 +200,9 @@ function toLegacyProvider(providerName: string | null): ProviderKind {
|
||||
return "codex";
|
||||
}
|
||||
|
||||
function resolveWsHttpOrigin(): string {
|
||||
if (typeof window === "undefined") return "";
|
||||
const bridgeWsUrl = window.desktopBridge?.getWsUrl?.();
|
||||
const envWsUrl = import.meta.env.VITE_WS_URL as string | undefined;
|
||||
const wsCandidate =
|
||||
typeof bridgeWsUrl === "string" && bridgeWsUrl.length > 0
|
||||
? bridgeWsUrl
|
||||
: typeof envWsUrl === "string" && envWsUrl.length > 0
|
||||
? envWsUrl
|
||||
: null;
|
||||
if (!wsCandidate) return window.location.origin;
|
||||
try {
|
||||
const wsUrl = new URL(wsCandidate);
|
||||
const protocol =
|
||||
wsUrl.protocol === "wss:" ? "https:" : wsUrl.protocol === "ws:" ? "http:" : wsUrl.protocol;
|
||||
return `${protocol}//${wsUrl.host}`;
|
||||
} catch {
|
||||
return window.location.origin;
|
||||
}
|
||||
}
|
||||
|
||||
function toAttachmentPreviewUrl(rawUrl: string): string {
|
||||
if (rawUrl.startsWith("/")) {
|
||||
return `${resolveWsHttpOrigin()}${rawUrl}`;
|
||||
return `${resolveServerHttpOrigin()}${rawUrl}`;
|
||||
}
|
||||
return rawUrl;
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { type TimestampFormat } from "./appSettings";
|
||||
import { type TimestampFormat } from "@t3tools/contracts/settings";
|
||||
|
||||
export function getTimestampFormatOptions(
|
||||
timestampFormat: TimestampFormat,
|
||||
@@ -47,3 +47,22 @@ export function formatTimestamp(isoDate: string, timestampFormat: TimestampForma
|
||||
export function formatShortTimestamp(isoDate: string, timestampFormat: TimestampFormat): string {
|
||||
return getTimestampFormatter(timestampFormat, false).format(new Date(isoDate));
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a relative time string from an ISO date.
|
||||
* Returns `{ value: "20s", suffix: "ago" }` or `{ value: "just now", suffix: null }`
|
||||
* so callers can style the numeric portion independently.
|
||||
*/
|
||||
export function formatRelativeTime(isoDate: string): { value: string; suffix: string | null } {
|
||||
const diffMs = Date.now() - new Date(isoDate).getTime();
|
||||
if (diffMs < 0) return { value: "just now", suffix: null };
|
||||
const seconds = Math.floor(diffMs / 1000);
|
||||
if (seconds < 5) return { value: "just now", suffix: null };
|
||||
if (seconds < 60) return { value: `${seconds}s`, suffix: "ago" };
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return { value: `${hours}h`, suffix: "ago" };
|
||||
const days = Math.floor(hours / 24);
|
||||
return { value: `${days}d`, suffix: "ago" };
|
||||
}
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WsPush,
|
||||
type ServerProviderStatus,
|
||||
type ServerProvider,
|
||||
} from "@t3tools/contracts";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
@@ -92,13 +92,16 @@ function getWindowForTest(): Window & typeof globalThis & { desktopBridge?: unkn
|
||||
return testGlobal.window;
|
||||
}
|
||||
|
||||
const defaultProviders: ReadonlyArray<ServerProviderStatus> = [
|
||||
const defaultProviders: ReadonlyArray<ServerProvider> = [
|
||||
{
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
available: true,
|
||||
authStatus: "authenticated",
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -197,7 +200,6 @@ describe("wsNativeApi", () => {
|
||||
message: "Entry at index 1 is invalid.",
|
||||
},
|
||||
],
|
||||
providers: defaultProviders,
|
||||
} as const;
|
||||
emitPush(WS_CHANNELS.serverConfigUpdated, payload);
|
||||
|
||||
@@ -219,20 +221,38 @@ 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: [],
|
||||
providers: defaultProviders,
|
||||
});
|
||||
});
|
||||
|
||||
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 () => {
|
||||
const { createWsNativeApi } = await import("./wsNativeApi");
|
||||
|
||||
@@ -357,10 +377,6 @@ describe("wsNativeApi", () => {
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
});
|
||||
|
||||
expect(requestMock).toHaveBeenCalledWith(
|
||||
@@ -369,10 +385,6 @@ describe("wsNativeApi", () => {
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit",
|
||||
modelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4-mini",
|
||||
},
|
||||
},
|
||||
{ timeoutMs: null },
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
type ContextMenuItem,
|
||||
type NativeApi,
|
||||
ServerConfigUpdatedPayload,
|
||||
ServerProviderUpdatedPayload,
|
||||
WS_CHANNELS,
|
||||
WS_METHODS,
|
||||
type WsWelcomePayload,
|
||||
@@ -16,6 +17,7 @@ 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>();
|
||||
|
||||
/**
|
||||
@@ -64,6 +66,26 @@ 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;
|
||||
|
||||
@@ -89,6 +111,16 @@ 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) {
|
||||
@@ -178,6 +210,7 @@ export function createWsNativeApi(): NativeApi {
|
||||
},
|
||||
server: {
|
||||
getConfig: () => transport.request(WS_METHODS.serverGetConfig),
|
||||
refreshProviders: () => transport.request(WS_METHODS.serverRefreshProviders),
|
||||
upsertKeybinding: (input) => transport.request(WS_METHODS.serverUpsertKeybinding, input),
|
||||
getSettings: () => transport.request(WS_METHODS.serverGetSettings),
|
||||
updateSettings: (patch) => transport.request(WS_METHODS.serverUpdateSettings, { patch }),
|
||||
|
||||
@@ -98,7 +98,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 1,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [] },
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -107,7 +107,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 1,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [] },
|
||||
});
|
||||
|
||||
transport.dispose();
|
||||
@@ -160,7 +160,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [] },
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -169,7 +169,7 @@ describe("WsTransport", () => {
|
||||
type: "push",
|
||||
sequence: 3,
|
||||
channel: WS_CHANNELS.serverConfigUpdated,
|
||||
data: { issues: [], providers: [] },
|
||||
data: { issues: [] },
|
||||
});
|
||||
expect(warnSpy).toHaveBeenCalledTimes(2);
|
||||
expect(warnSpy).toHaveBeenNthCalledWith(
|
||||
|
||||
@@ -10,6 +10,11 @@
|
||||
"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",
|
||||
|
||||
@@ -2,11 +2,18 @@ import { Schema } from "effect";
|
||||
import { TrimmedNonEmptyString } from "./baseSchemas";
|
||||
|
||||
export const EDITORS = [
|
||||
{ id: "cursor", label: "Cursor", command: "cursor" },
|
||||
{ id: "vscode", label: "VS Code", command: "code" },
|
||||
{ id: "zed", label: "Zed", command: "zed" },
|
||||
{ id: "antigravity", label: "Antigravity", command: "agy" },
|
||||
{ id: "file-manager", label: "File Manager", command: null },
|
||||
{ id: "cursor", label: "Cursor", command: "cursor", supportsGoto: true },
|
||||
{ id: "vscode", label: "VS Code", command: "code", supportsGoto: true },
|
||||
{
|
||||
id: "vscode-insiders",
|
||||
label: "VS Code Insiders",
|
||||
command: "code-insiders",
|
||||
supportsGoto: true,
|
||||
},
|
||||
{ id: "vscodium", label: "VSCodium", command: "codium", supportsGoto: true },
|
||||
{ id: "zed", label: "Zed", command: "zed", supportsGoto: false },
|
||||
{ id: "antigravity", label: "Antigravity", command: "agy", supportsGoto: false },
|
||||
{ id: "file-manager", label: "File Manager", command: null, supportsGoto: false },
|
||||
] as const;
|
||||
|
||||
export const EditorId = Schema.Literals(EDITORS.map((e) => e.id));
|
||||
|
||||
@@ -74,19 +74,4 @@ describe("GitRunStackedActionInput", () => {
|
||||
expect(parsed.actionId).toBe("action-1");
|
||||
expect(parsed.action).toBe("commit");
|
||||
});
|
||||
|
||||
it("accepts git text generation as a modelSelection", () => {
|
||||
const parsed = decodeRunStackedActionInput({
|
||||
actionId: "action-1",
|
||||
cwd: "/repo",
|
||||
action: "commit_push_pr",
|
||||
modelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.modelSelection?.provider).toBe("claudeAgent");
|
||||
expect(parsed.modelSelection?.model).toBe("claude-haiku-4-5");
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Schema } from "effect";
|
||||
import { NonNegativeInt, PositiveInt, TrimmedNonEmptyString } from "./baseSchemas";
|
||||
import { ModelSelection } from "./orchestration";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
|
||||
@@ -80,7 +79,6 @@ export const GitRunStackedActionInput = Schema.Struct({
|
||||
filePaths: Schema.optional(
|
||||
Schema.Array(TrimmedNonEmptyStringSchema).check(Schema.isMinLength(1)),
|
||||
),
|
||||
modelSelection: ModelSelection,
|
||||
});
|
||||
export type GitRunStackedActionInput = typeof GitRunStackedActionInput.Type;
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ export * from "./model";
|
||||
export * from "./ws";
|
||||
export * from "./keybindings";
|
||||
export * from "./server";
|
||||
export * from "./settings";
|
||||
export * from "./git";
|
||||
export * from "./orchestration";
|
||||
export * from "./editor";
|
||||
|
||||
@@ -25,7 +25,11 @@ import type {
|
||||
ProjectWriteFileInput,
|
||||
ProjectWriteFileResult,
|
||||
} from "./project";
|
||||
import type { ServerConfig, ServerSettings, ServerSettingsPatch } from "./server";
|
||||
import type {
|
||||
ServerConfig,
|
||||
ServerProviderUpdatedPayload,
|
||||
ServerUpsertKeybindingResult,
|
||||
} from "./server";
|
||||
import type {
|
||||
TerminalClearInput,
|
||||
TerminalCloseInput,
|
||||
@@ -36,7 +40,7 @@ import type {
|
||||
TerminalSessionSnapshot,
|
||||
TerminalWriteInput,
|
||||
} from "./terminal";
|
||||
import type { ServerUpsertKeybindingInput, ServerUpsertKeybindingResult } from "./server";
|
||||
import type { ServerUpsertKeybindingInput } from "./server";
|
||||
import type {
|
||||
ClientOrchestrationCommand,
|
||||
OrchestrationGetFullThreadDiffInput,
|
||||
@@ -47,6 +51,7 @@ import type {
|
||||
OrchestrationReadModel,
|
||||
} from "./orchestration";
|
||||
import { EditorId } from "./editor";
|
||||
import { ServerSettings, ServerSettingsPatch } from "./settings";
|
||||
|
||||
export interface ContextMenuItem<T extends string = string> {
|
||||
id: T;
|
||||
@@ -160,6 +165,7 @@ export interface NativeApi {
|
||||
};
|
||||
server: {
|
||||
getConfig: () => Promise<ServerConfig>;
|
||||
refreshProviders: () => Promise<ServerProviderUpdatedPayload>;
|
||||
upsertKeybinding: (input: ServerUpsertKeybindingInput) => Promise<ServerUpsertKeybindingResult>;
|
||||
getSettings: () => Promise<ServerSettings>;
|
||||
updateSettings: (patch: ServerSettingsPatch) => Promise<ServerSettings>;
|
||||
|
||||
+24
-175
@@ -1,4 +1,5 @@
|
||||
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;
|
||||
@@ -17,6 +18,7 @@ export const ClaudeModelOptions = Schema.Struct({
|
||||
thinking: Schema.optional(Schema.Boolean),
|
||||
effort: Schema.optional(Schema.Literals(CLAUDE_CODE_EFFORT_OPTIONS)),
|
||||
fastMode: Schema.optional(Schema.Boolean),
|
||||
contextWindow: Schema.optional(Schema.String),
|
||||
});
|
||||
export type ClaudeModelOptions = typeof ClaudeModelOptions.Type;
|
||||
|
||||
@@ -26,178 +28,34 @@ export const ProviderModelOptions = Schema.Struct({
|
||||
});
|
||||
export type ProviderModelOptions = typeof ProviderModelOptions.Type;
|
||||
|
||||
export type EffortOption = {
|
||||
readonly value: string;
|
||||
readonly label: string;
|
||||
readonly isDefault?: true;
|
||||
};
|
||||
export const EffortOption = Schema.Struct({
|
||||
value: TrimmedNonEmptyString,
|
||||
label: TrimmedNonEmptyString,
|
||||
isDefault: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type EffortOption = typeof EffortOption.Type;
|
||||
|
||||
export type ModelCapabilities = {
|
||||
readonly reasoningEffortLevels: readonly EffortOption[];
|
||||
readonly supportsFastMode: boolean;
|
||||
readonly supportsThinkingToggle: boolean;
|
||||
readonly promptInjectedEffortLevels: readonly string[];
|
||||
};
|
||||
export const ContextWindowOption = Schema.Struct({
|
||||
value: TrimmedNonEmptyString,
|
||||
label: TrimmedNonEmptyString,
|
||||
isDefault: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ContextWindowOption = typeof ContextWindowOption.Type;
|
||||
|
||||
type ModelDefinition = {
|
||||
readonly slug: string;
|
||||
readonly name: string;
|
||||
readonly capabilities: ModelCapabilities;
|
||||
};
|
||||
export const ModelCapabilities = Schema.Struct({
|
||||
reasoningEffortLevels: Schema.Array(EffortOption),
|
||||
supportsFastMode: Schema.Boolean,
|
||||
supportsThinkingToggle: Schema.Boolean,
|
||||
contextWindowOptions: Schema.Array(ContextWindowOption),
|
||||
promptInjectedEffortLevels: Schema.Array(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ModelCapabilities = typeof ModelCapabilities.Type;
|
||||
|
||||
/**
|
||||
* 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> = {
|
||||
export const DEFAULT_MODEL_BY_PROVIDER: Record<ProviderKind, string> = {
|
||||
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. */
|
||||
@@ -206,7 +64,7 @@ export const DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER: Record<ProviderKind,
|
||||
claudeAgent: "claude-haiku-4-5",
|
||||
};
|
||||
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, ModelSlug>> = {
|
||||
export const MODEL_SLUG_ALIASES_BY_PROVIDER: Record<ProviderKind, Record<string, string>> = {
|
||||
codex: {
|
||||
"5.4": "gpt-5.4",
|
||||
"5.3": "gpt-5.3-codex",
|
||||
@@ -230,15 +88,6 @@ 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> = {
|
||||
|
||||
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user