Compare commits
24
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a94819851d | ||
|
|
a2c1172551 | ||
|
|
761e7359f9 | ||
|
|
4c72c5f671 | ||
|
|
4790ea0129 | ||
|
|
f65ebd618e | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
6d51620f8b | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
909fd5a571 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 | ||
|
|
922f9b66e5 | ||
|
|
8332eb21d5 | ||
|
|
c91e8b23e8 | ||
|
|
9a9be39751 |
No files matched your search
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
|
||||
const options = {
|
||||
type: "question" as const,
|
||||
buttons: ["No", "Yes"],
|
||||
defaultId: CONFIRM_BUTTON_INDEX,
|
||||
defaultId: 0,
|
||||
cancelId: 0,
|
||||
noLink: true,
|
||||
message: normalizedMessage,
|
||||
|
||||
@@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps spark enabled for api key accounts", () => {
|
||||
it("disables spark for api key accounts", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "apiKey",
|
||||
@@ -318,7 +318,20 @@ describe("readCodexAccountSnapshot", () => {
|
||||
).toEqual({
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
sparkEnabled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("disables spark for unknown chatgpt plans", () => {
|
||||
expect(
|
||||
readCodexAccountSnapshot({
|
||||
type: "chatgpt",
|
||||
email: "[email protected]",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "chatgpt",
|
||||
planType: "unknown",
|
||||
sparkEnabled: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -343,6 +356,16 @@ describe("resolveCodexModelForAccount", () => {
|
||||
}),
|
||||
).toBe("gpt-5.3-codex-spark");
|
||||
});
|
||||
|
||||
it("falls back from spark to default for api key auth", () => {
|
||||
expect(
|
||||
resolveCodexModelForAccount("gpt-5.3-codex-spark", {
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
).toBe("gpt-5.3-codex");
|
||||
});
|
||||
});
|
||||
|
||||
describe("startSession", () => {
|
||||
|
||||
@@ -26,6 +26,15 @@ import {
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "./provider/codexCliVersion";
|
||||
import {
|
||||
readCodexAccountSnapshot,
|
||||
resolveCodexModelForAccount,
|
||||
type CodexAccountSnapshot,
|
||||
} from "./provider/codexAccount";
|
||||
import { buildCodexInitializeParams, killCodexChildProcess } from "./provider/codexAppServer";
|
||||
|
||||
export { buildCodexInitializeParams } from "./provider/codexAppServer";
|
||||
export { readCodexAccountSnapshot, resolveCodexModelForAccount } from "./provider/codexAccount";
|
||||
|
||||
type PendingRequestKey = string;
|
||||
|
||||
@@ -96,23 +105,6 @@ interface JsonRpcNotification {
|
||||
params?: unknown;
|
||||
}
|
||||
|
||||
type CodexPlanType =
|
||||
| "free"
|
||||
| "go"
|
||||
| "plus"
|
||||
| "pro"
|
||||
| "team"
|
||||
| "business"
|
||||
| "enterprise"
|
||||
| "edu"
|
||||
| "unknown";
|
||||
|
||||
interface CodexAccountSnapshot {
|
||||
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||
readonly planType: CodexPlanType | null;
|
||||
readonly sparkEnabled: boolean;
|
||||
}
|
||||
|
||||
export interface CodexAppServerSendTurnInput {
|
||||
readonly threadId: ThreadId;
|
||||
readonly input?: string;
|
||||
@@ -162,50 +154,6 @@ const RECOVERABLE_THREAD_RESUME_ERROR_SNIPPETS = [
|
||||
"unknown thread",
|
||||
"does not exist",
|
||||
];
|
||||
const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||
const CODEX_SPARK_DISABLED_PLAN_TYPES = new Set<CodexPlanType>(["free", "go", "plus"]);
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
|
||||
const record = asObject(response);
|
||||
const account = asObject(record?.account) ?? record;
|
||||
const accountType = asString(account?.type);
|
||||
|
||||
if (accountType === "apiKey") {
|
||||
return {
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (accountType === "chatgpt") {
|
||||
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
||||
return {
|
||||
type: "chatgpt",
|
||||
planType,
|
||||
sparkEnabled: !CODEX_SPARK_DISABLED_PLAN_TYPES.has(planType),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: true,
|
||||
};
|
||||
}
|
||||
|
||||
export const CODEX_PLAN_MODE_DEVELOPER_INSTRUCTIONS = `<collaboration_mode># Plan Mode (Conversational)
|
||||
|
||||
You work in 3 phases, and you should *chat your way* to a great plan before finalizing it. A great plan is very detailed-intent- and implementation-wise-so that it can be handed to another engineer or agent to be implemented right away. It must be **decision complete**, where the implementer does not need to make any decisions.
|
||||
@@ -358,32 +306,13 @@ function mapCodexRuntimeMode(runtimeMode: RuntimeMode): {
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveCodexModelForAccount(
|
||||
model: string | undefined,
|
||||
account: CodexAccountSnapshot,
|
||||
): string | undefined {
|
||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return CODEX_DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
/**
|
||||
* On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
|
||||
* wrapper, leaving the actual command running. Use `taskkill /T` to kill the
|
||||
* entire process tree instead.
|
||||
*/
|
||||
function killChildTree(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// fallback to direct kill
|
||||
}
|
||||
}
|
||||
child.kill();
|
||||
killCodexChildProcess(child);
|
||||
}
|
||||
|
||||
export function normalizeCodexModelSlug(
|
||||
@@ -402,19 +331,6 @@ export function normalizeCodexModelSlug(
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
function buildCodexCollaborationMode(input: {
|
||||
readonly interactionMode?: "default" | "plan";
|
||||
readonly model?: string;
|
||||
|
||||
@@ -29,8 +29,9 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
|
||||
|
||||
const CLAUDE_TIMEOUT_MS = 180_000;
|
||||
|
||||
@@ -84,8 +85,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
|
||||
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
|
||||
Effect.gen(function* () {
|
||||
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
|
||||
const normalizedOptions = normalizeClaudeModelOptions(
|
||||
modelSelection.model,
|
||||
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
|
||||
getClaudeModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const settings = {
|
||||
|
||||
@@ -28,8 +28,9 @@ import {
|
||||
sanitizeThreadTitle,
|
||||
toJsonSchemaObject,
|
||||
} from "../Utils.ts";
|
||||
import { normalizeCodexModelOptions } from "../../provider/Layers/CodexProvider.ts";
|
||||
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
|
||||
import { ServerSettingsService } from "../../serverSettings.ts";
|
||||
import { normalizeCodexModelOptionsWithCapabilities } from "@t3tools/shared/model";
|
||||
|
||||
const CODEX_GIT_TEXT_GENERATION_REASONING_EFFORT = "low";
|
||||
const CODEX_TIMEOUT_MS = 180_000;
|
||||
@@ -156,8 +157,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
|
||||
).pipe(Effect.catch(() => Effect.undefined));
|
||||
|
||||
const runCodexCommand = Effect.gen(function* () {
|
||||
const normalizedOptions = normalizeCodexModelOptions(
|
||||
modelSelection.model,
|
||||
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
|
||||
getCodexModelCapabilities(modelSelection.model),
|
||||
modelSelection.options,
|
||||
);
|
||||
const reasoningEffort =
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import type {
|
||||
ClaudeSettings,
|
||||
ClaudeModelOptions,
|
||||
ModelCapabilities,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderAuth,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
|
||||
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
|
||||
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
|
||||
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
|
||||
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
|
||||
|
||||
import {
|
||||
buildServerProvider,
|
||||
@@ -43,8 +43,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
@@ -63,8 +63,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
supportsFastMode: false,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k" },
|
||||
{ value: "1m", label: "1M", isDefault: true },
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
promptInjectedEffortLevels: ["ultrathink"],
|
||||
} satisfies ModelCapabilities,
|
||||
@@ -96,28 +96,9 @@ export function getClaudeModelCapabilities(model: string | null | undefined): Mo
|
||||
);
|
||||
}
|
||||
|
||||
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 auth: Pick<ServerProviderAuth, "status">;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
@@ -129,7 +110,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
};
|
||||
@@ -144,7 +125,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
@@ -165,37 +146,286 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
"Could not verify Claude authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Could not verify Claude authentication status. ${detail}`
|
||||
: "Could not verify Claude authentication status.",
|
||||
};
|
||||
}
|
||||
|
||||
// ── Subscription type detection ─────────────────────────────────────
|
||||
//
|
||||
// The SDK probe returns typed `AccountInfo.subscriptionType` directly.
|
||||
// This walker is a best-effort fallback for the `claude auth status`
|
||||
// JSON output whose shape is not guaranteed.
|
||||
|
||||
/** Keys that directly hold a subscription/plan identifier. */
|
||||
const SUBSCRIPTION_TYPE_KEYS = [
|
||||
"subscriptionType",
|
||||
"subscription_type",
|
||||
"plan",
|
||||
"tier",
|
||||
"planType",
|
||||
"plan_type",
|
||||
] as const;
|
||||
|
||||
/** Keys whose value may be a nested object containing subscription info. */
|
||||
const SUBSCRIPTION_CONTAINER_KEYS = ["account", "subscription", "user", "billing"] as const;
|
||||
const AUTH_METHOD_KEYS = ["authMethod", "auth_method"] as const;
|
||||
const AUTH_METHOD_CONTAINER_KEYS = ["auth", "account", "session"] as const;
|
||||
|
||||
/** Lift an unknown value into `Option<string>` if it is a non-empty string. */
|
||||
const asNonEmptyString = (v: unknown): Option.Option<string> =>
|
||||
typeof v === "string" && v.length > 0 ? Option.some(v) : Option.none();
|
||||
|
||||
/** Lift an unknown value into `Option<Record>` if it is a plain object. */
|
||||
const asRecord = (v: unknown): Option.Option<Record<string, unknown>> =>
|
||||
typeof v === "object" && v !== null && !globalThis.Array.isArray(v)
|
||||
? Option.some(v as Record<string, unknown>)
|
||||
: Option.none();
|
||||
|
||||
/**
|
||||
* Walk an unknown parsed JSON value looking for a subscription/plan
|
||||
* identifier, returning the first match as an `Option`.
|
||||
*/
|
||||
function findSubscriptionType(value: unknown): Option.Option<string> {
|
||||
if (globalThis.Array.isArray(value)) {
|
||||
return Option.firstSomeOf(value.map(findSubscriptionType));
|
||||
}
|
||||
|
||||
return asRecord(value).pipe(
|
||||
Option.flatMap((record) => {
|
||||
const direct = Option.firstSomeOf(
|
||||
SUBSCRIPTION_TYPE_KEYS.map((key) => asNonEmptyString(record[key])),
|
||||
);
|
||||
if (Option.isSome(direct)) return direct;
|
||||
|
||||
return Option.firstSomeOf(
|
||||
SUBSCRIPTION_CONTAINER_KEYS.map((key) =>
|
||||
asRecord(record[key]).pipe(Option.flatMap(findSubscriptionType)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function findAuthMethod(value: unknown): Option.Option<string> {
|
||||
if (globalThis.Array.isArray(value)) {
|
||||
return Option.firstSomeOf(value.map(findAuthMethod));
|
||||
}
|
||||
|
||||
return asRecord(value).pipe(
|
||||
Option.flatMap((record) => {
|
||||
const direct = Option.firstSomeOf(
|
||||
AUTH_METHOD_KEYS.map((key) => asNonEmptyString(record[key])),
|
||||
);
|
||||
if (Option.isSome(direct)) return direct;
|
||||
|
||||
return Option.firstSomeOf(
|
||||
AUTH_METHOD_CONTAINER_KEYS.map((key) =>
|
||||
asRecord(record[key]).pipe(Option.flatMap(findAuthMethod)),
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to extract a subscription type from the `claude auth status` JSON
|
||||
* output. This is a zero-cost operation on data we already have.
|
||||
*/
|
||||
const decodeUnknownJson = decodeJsonResult(Schema.Unknown);
|
||||
|
||||
function extractSubscriptionTypeFromOutput(result: CommandResult): string | undefined {
|
||||
const parsed = decodeUnknownJson(result.stdout.trim());
|
||||
if (Result.isFailure(parsed)) return undefined;
|
||||
return Option.getOrUndefined(findSubscriptionType(parsed.success));
|
||||
}
|
||||
|
||||
function extractClaudeAuthMethodFromOutput(result: CommandResult): string | undefined {
|
||||
const parsed = decodeUnknownJson(result.stdout.trim());
|
||||
if (Result.isFailure(parsed)) return undefined;
|
||||
return Option.getOrUndefined(findAuthMethod(parsed.success));
|
||||
}
|
||||
|
||||
// ── Dynamic model capability adjustment ─────────────────────────────
|
||||
|
||||
/** Subscription types where the 1M context window is included in the plan. */
|
||||
const PREMIUM_SUBSCRIPTION_TYPES = new Set([
|
||||
"max",
|
||||
"maxplan",
|
||||
"max5",
|
||||
"max20",
|
||||
"enterprise",
|
||||
"team",
|
||||
]);
|
||||
|
||||
function toTitleCaseWords(value: string): string {
|
||||
return value
|
||||
.split(/[\s_-]+/g)
|
||||
.filter(Boolean)
|
||||
.map((part) => part[0]!.toUpperCase() + part.slice(1).toLowerCase())
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function claudeSubscriptionLabel(subscriptionType: string | undefined): string | undefined {
|
||||
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized) return undefined;
|
||||
|
||||
switch (normalized) {
|
||||
case "max":
|
||||
case "maxplan":
|
||||
case "max5":
|
||||
case "max20":
|
||||
return "Max";
|
||||
case "enterprise":
|
||||
return "Enterprise";
|
||||
case "team":
|
||||
return "Team";
|
||||
case "pro":
|
||||
return "Pro";
|
||||
case "free":
|
||||
return "Free";
|
||||
default:
|
||||
return toTitleCaseWords(subscriptionType!);
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeClaudeAuthMethod(authMethod: string | undefined): string | undefined {
|
||||
const normalized = authMethod?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized) return undefined;
|
||||
if (normalized === "apikey") return "apiKey";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function claudeAuthMetadata(input: {
|
||||
readonly subscriptionType: string | undefined;
|
||||
readonly authMethod: string | undefined;
|
||||
}): { readonly type: string; readonly label: string } | undefined {
|
||||
if (normalizeClaudeAuthMethod(input.authMethod) === "apiKey") {
|
||||
return {
|
||||
type: "apiKey",
|
||||
label: "Claude API Key",
|
||||
};
|
||||
}
|
||||
|
||||
if (input.subscriptionType) {
|
||||
const subscriptionLabel = claudeSubscriptionLabel(input.subscriptionType);
|
||||
return {
|
||||
type: input.subscriptionType,
|
||||
label: `Claude ${subscriptionLabel ?? toTitleCaseWords(input.subscriptionType)} Subscription`,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adjust the built-in model list based on the user's detected subscription.
|
||||
*
|
||||
* - Premium tiers (Max, Enterprise, Team): 1M context becomes the default.
|
||||
* - Other tiers (Pro, free, unknown): 200k context stays the default;
|
||||
* 1M remains available as a manual option so users can still enable it.
|
||||
*/
|
||||
export function adjustModelsForSubscription(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
subscriptionType: string | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
const normalized = subscriptionType?.toLowerCase().replace(/[\s_-]+/g, "");
|
||||
if (!normalized || !PREMIUM_SUBSCRIPTION_TYPES.has(normalized)) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
// Flip 1M to be the default for premium users
|
||||
return baseModels.map((model) => {
|
||||
const caps = model.capabilities;
|
||||
if (!caps || caps.contextWindowOptions.length === 0) return model;
|
||||
|
||||
return {
|
||||
...model,
|
||||
capabilities: {
|
||||
...caps,
|
||||
contextWindowOptions: caps.contextWindowOptions.map((opt) =>
|
||||
opt.value === "1m"
|
||||
? { value: opt.value, label: opt.label, isDefault: true as const }
|
||||
: { value: opt.value, label: opt.label },
|
||||
),
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ── SDK capability probe ────────────────────────────────────────────
|
||||
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
|
||||
/**
|
||||
* Probe account information by spawning a lightweight Claude Agent SDK
|
||||
* session and reading the initialization result.
|
||||
*
|
||||
* The prompt is never sent to the Anthropic API — we abort immediately
|
||||
* after the local initialization phase completes. This gives us the
|
||||
* user's subscription type without incurring any token cost.
|
||||
*
|
||||
* This is used as a fallback when `claude auth status` does not include
|
||||
* subscription type information.
|
||||
*/
|
||||
const probeClaudeCapabilities = (binaryPath: string) => {
|
||||
const abort = new AbortController();
|
||||
return Effect.tryPromise(async () => {
|
||||
const q = claudeQuery({
|
||||
prompt: ".",
|
||||
options: {
|
||||
persistSession: false,
|
||||
pathToClaudeCodeExecutable: binaryPath,
|
||||
abortController: abort,
|
||||
maxTurns: 0,
|
||||
settingSources: [],
|
||||
allowedTools: [],
|
||||
stderr: () => {},
|
||||
},
|
||||
});
|
||||
const init = await q.initializationResult();
|
||||
return { subscriptionType: init.account?.subscriptionType };
|
||||
}).pipe(
|
||||
Effect.ensuring(
|
||||
Effect.sync(() => {
|
||||
if (!abort.signal.aborted) abort.abort();
|
||||
}),
|
||||
),
|
||||
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
Effect.map((result) => {
|
||||
if (Result.isFailure(result)) return undefined;
|
||||
return Option.isSome(result.success) ? result.success.value : undefined;
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
|
||||
@@ -208,144 +438,81 @@ const runClaudeCommand = (args: ReadonlyArray<string>) =>
|
||||
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
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,
|
||||
);
|
||||
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(function* (
|
||||
resolveSubscriptionType?: (binaryPath: string) => Effect.Effect<string | undefined>,
|
||||
): 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.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!claudeSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Claude is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runClaudeCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
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 (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "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.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "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);
|
||||
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,
|
||||
@@ -354,13 +521,99 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
status: "error",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Claude Agent CLI is installed but failed to run. ${detail}`
|
||||
: "Claude Agent CLI is installed but failed to run.",
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ── Auth check + subscription detection ────────────────────────────
|
||||
|
||||
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
|
||||
// Determine subscription type from multiple sources (cheapest first):
|
||||
// 1. `claude auth status` JSON output (may or may not contain it)
|
||||
// 2. Cached SDK probe (spawns a Claude process on miss, reads
|
||||
// `initializationResult()` for account metadata, then aborts
|
||||
// immediately — no API tokens are consumed)
|
||||
|
||||
let subscriptionType: string | undefined;
|
||||
let authMethod: string | undefined;
|
||||
|
||||
if (Result.isSuccess(authProbe) && Option.isSome(authProbe.success)) {
|
||||
subscriptionType = extractSubscriptionTypeFromOutput(authProbe.success.value);
|
||||
authMethod = extractClaudeAuthMethodFromOutput(authProbe.success.value);
|
||||
}
|
||||
|
||||
if (!subscriptionType && resolveSubscriptionType) {
|
||||
subscriptionType = yield* resolveSubscriptionType(claudeSettings.binaryPath);
|
||||
}
|
||||
|
||||
const resolvedModels = adjustModelsForSubscription(models, subscriptionType);
|
||||
|
||||
// ── Handle auth results (same logic as before, adjusted models) ──
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "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: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Could not verify Claude authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
|
||||
const authMetadata = claudeAuthMetadata({ subscriptionType, authMethod });
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: claudeSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
auth: {
|
||||
...parsed.auth,
|
||||
...(authMetadata ? authMetadata : {}),
|
||||
},
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const ClaudeProviderLive = Layer.effect(
|
||||
ClaudeProvider,
|
||||
@@ -368,7 +621,16 @@ export const ClaudeProviderLive = Layer.effect(
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus().pipe(
|
||||
const subscriptionProbeCache = yield* Cache.make({
|
||||
capacity: 1,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (binaryPath: string) =>
|
||||
probeClaudeCapabilities(binaryPath).pipe(Effect.map((r) => r?.subscriptionType)),
|
||||
});
|
||||
|
||||
const checkProvider = checkClaudeProviderStatus((binaryPath) =>
|
||||
Cache.get(subscriptionProbeCache, binaryPath),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
|
||||
);
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
import * as OS from "node:os";
|
||||
import type {
|
||||
ModelCapabilities,
|
||||
CodexModelOptions,
|
||||
CodexSettings,
|
||||
ServerProvider,
|
||||
ServerProviderModel,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderAuth,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
|
||||
import {
|
||||
Cache,
|
||||
Duration,
|
||||
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,
|
||||
@@ -29,6 +38,13 @@ import {
|
||||
isCodexCliVersionSupported,
|
||||
parseCodexCliVersion,
|
||||
} from "../codexCliVersion";
|
||||
import {
|
||||
adjustCodexModelsForAccount,
|
||||
codexAuthSubLabel,
|
||||
codexAuthSubType,
|
||||
type CodexAccountSnapshot,
|
||||
} from "../codexAccount";
|
||||
import { probeCodexAccount } from "../codexAppServer";
|
||||
import { CodexProvider } from "../Services/CodexProvider";
|
||||
import { ServerSettingsError, ServerSettingsService } from "../../serverSettings";
|
||||
|
||||
@@ -152,25 +168,9 @@ export function getCodexModelCapabilities(model: string | null | undefined): Mod
|
||||
);
|
||||
}
|
||||
|
||||
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 auth: Pick<ServerProviderAuth, "status">;
|
||||
readonly message?: string;
|
||||
} {
|
||||
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
|
||||
@@ -182,7 +182,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
};
|
||||
}
|
||||
@@ -196,7 +196,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
@@ -217,31 +217,31 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
|
||||
})();
|
||||
|
||||
if (parsedAuth.auth === true) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
if (parsedAuth.auth === false) {
|
||||
return {
|
||||
status: "error",
|
||||
authStatus: "unauthenticated",
|
||||
auth: { status: "unauthenticated" },
|
||||
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
};
|
||||
}
|
||||
if (parsedAuth.attemptedJsonParse) {
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message:
|
||||
"Could not verify Codex authentication status from JSON output (missing auth marker).",
|
||||
};
|
||||
}
|
||||
if (result.code === 0) {
|
||||
return { status: "ready", authStatus: "authenticated" };
|
||||
return { status: "ready", auth: { status: "authenticated" } };
|
||||
}
|
||||
|
||||
const detail = detailFromResult(result);
|
||||
return {
|
||||
status: "warning",
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
message: detail
|
||||
? `Could not verify Codex authentication status. ${detail}`
|
||||
: "Could not verify Codex authentication status.",
|
||||
@@ -290,6 +290,21 @@ export const hasCustomModelProvider = readCodexConfigModelProvider().pipe(
|
||||
Effect.orElseSucceed(() => false),
|
||||
);
|
||||
|
||||
const CAPABILITIES_PROBE_TIMEOUT_MS = 8_000;
|
||||
|
||||
const probeCodexCapabilities = (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
}) =>
|
||||
Effect.tryPromise((signal) => probeCodexAccount({ ...input, signal })).pipe(
|
||||
Effect.timeoutOption(CAPABILITIES_PROBE_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
Effect.map((result) => {
|
||||
if (Result.isFailure(result)) return undefined;
|
||||
return Option.isSome(result.success) ? result.success.value : undefined;
|
||||
}),
|
||||
);
|
||||
|
||||
const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
Effect.gen(function* () {
|
||||
const settingsService = yield* ServerSettingsService;
|
||||
@@ -306,179 +321,88 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
|
||||
return yield* spawnAndCollect(codexSettings.binaryPath, command);
|
||||
});
|
||||
|
||||
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,
|
||||
);
|
||||
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(function* (
|
||||
resolveAccount?: (input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
}) => Effect.Effect<CodexAccountSnapshot | undefined>,
|
||||
): 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.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!codexSettings.enabled) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: false,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: false,
|
||||
version: null,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Codex is disabled in T3 Code settings.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const versionProbe = yield* runCodexCommand(["--version"]).pipe(
|
||||
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
|
||||
Effect.result,
|
||||
);
|
||||
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 (Result.isFailure(versionProbe)) {
|
||||
const error = versionProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: !isCommandMissingCause(error),
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "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.",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (Option.isNone(versionProbe.success)) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: null,
|
||||
status: "error",
|
||||
auth: { status: "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);
|
||||
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,
|
||||
@@ -487,13 +411,116 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
authStatus: parsed.authStatus,
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
status: "error",
|
||||
auth: { status: "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",
|
||||
auth: { status: "unknown" },
|
||||
message: formatCodexCliUpgradeMessage(parsedVersion),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (yield* hasCustomModelProvider) {
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "ready",
|
||||
auth: { status: "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,
|
||||
);
|
||||
const account = resolveAccount
|
||||
? yield* resolveAccount({
|
||||
binaryPath: codexSettings.binaryPath,
|
||||
homePath: codexSettings.homePath,
|
||||
})
|
||||
: undefined;
|
||||
const resolvedModels = adjustCodexModelsForAccount(models, account);
|
||||
|
||||
if (Result.isFailure(authProbe)) {
|
||||
const error = authProbe.failure;
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "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: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: "warning",
|
||||
auth: { status: "unknown" },
|
||||
message: "Could not verify Codex authentication status. Timed out while running command.",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
|
||||
const authType = codexAuthSubType(account);
|
||||
const authLabel = codexAuthSubLabel(account);
|
||||
return buildServerProvider({
|
||||
provider: PROVIDER,
|
||||
enabled: codexSettings.enabled,
|
||||
checkedAt,
|
||||
models: resolvedModels,
|
||||
probe: {
|
||||
installed: true,
|
||||
version: parsedVersion,
|
||||
status: parsed.status,
|
||||
auth: {
|
||||
...parsed.auth,
|
||||
...(authType ? { type: authType } : {}),
|
||||
...(authLabel ? { label: authLabel } : {}),
|
||||
},
|
||||
...(parsed.message ? { message: parsed.message } : {}),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
export const CodexProviderLive = Layer.effect(
|
||||
CodexProvider,
|
||||
@@ -502,8 +529,21 @@ export const CodexProviderLive = Layer.effect(
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
|
||||
const accountProbeCache = yield* Cache.make({
|
||||
capacity: 4,
|
||||
timeToLive: Duration.minutes(5),
|
||||
lookup: (key: string) => {
|
||||
const [binaryPath, homePath] = JSON.parse(key) as [string, string | undefined];
|
||||
return probeCodexCapabilities({
|
||||
binaryPath,
|
||||
...(homePath ? { homePath } : {}),
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const checkProvider = checkCodexProviderStatus().pipe(
|
||||
const checkProvider = checkCodexProviderStatus((input) =>
|
||||
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
|
||||
).pipe(
|
||||
Effect.provideService(ServerSettingsService, serverSettings),
|
||||
Effect.provideService(FileSystem.FileSystem, fileSystem),
|
||||
Effect.provideService(Path.Path, path),
|
||||
|
||||
@@ -173,7 +173,133 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
assert.strictEqual(status.auth.status, "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 the codex plan type in auth and keeps spark for supported plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "pro" as const,
|
||||
sparkEnabled: true,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "pro");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Pro Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
true,
|
||||
);
|
||||
}).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("hides spark from codex models for unsupported chatgpt plans", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "plus" as const,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "plus");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Plus Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).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("hides spark from codex models for non-pro chatgpt subscriptions", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "chatgpt" as const,
|
||||
planType: "team" as const,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.auth.type, "team");
|
||||
assert.strictEqual(status.auth.label, "ChatGPT Team Subscription");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).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 an api key label for codex api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
yield* withTempCodexHome();
|
||||
const status = yield* checkCodexProviderStatus(() =>
|
||||
Effect.succeed({
|
||||
type: "apiKey" as const,
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
}),
|
||||
);
|
||||
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "apiKey");
|
||||
assert.strictEqual(status.auth.label, "OpenAI API Key");
|
||||
assert.deepStrictEqual(
|
||||
status.models.some((model) => model.slug === "gpt-5.3-codex-spark"),
|
||||
false,
|
||||
);
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -235,7 +361,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
} finally {
|
||||
process.env.PATH = previousPath;
|
||||
}
|
||||
@@ -249,7 +375,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, false);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI (`codex`) is not installed or not on PATH.",
|
||||
@@ -264,7 +390,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "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.",
|
||||
@@ -287,7 +413,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
@@ -313,7 +439,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI is not authenticated. Run `codex login` and try again.",
|
||||
@@ -338,7 +464,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Codex CLI authentication status command is unavailable in this Codex version.",
|
||||
@@ -366,7 +492,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
status: "ready",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
@@ -376,7 +502,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
status: "warning",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
authStatus: "unknown",
|
||||
auth: { status: "unknown" },
|
||||
checkedAt: "2026-03-25T00:00:00.000Z",
|
||||
version: "1.0.0",
|
||||
models: [],
|
||||
@@ -494,7 +620,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "codex");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Using a custom Codex model provider; OpenAI login check skipped.",
|
||||
@@ -537,7 +663,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
const status = yield* checkCodexProviderStatus();
|
||||
// The auth probe runs and sees "not logged in" → error
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -558,7 +684,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
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");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with authenticated=false is unauthenticated", () => {
|
||||
@@ -568,7 +694,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
assert.strictEqual(parsed.auth.status, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
@@ -578,7 +704,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
assert.strictEqual(parsed.auth.status, "unknown");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -715,7 +841,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "authenticated");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -733,13 +859,63 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("returns a display label for claude subscription types", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus(() => Effect.succeed("maxplan"));
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "maxplan");
|
||||
assert.strictEqual(status.auth.label, "Claude Max Subscription");
|
||||
}).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 an api key label for claude api key auth", () =>
|
||||
Effect.gen(function* () {
|
||||
const status = yield* checkClaudeProviderStatus();
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "ready");
|
||||
assert.strictEqual(status.auth.status, "authenticated");
|
||||
assert.strictEqual(status.auth.type, "apiKey");
|
||||
assert.strictEqual(status.auth.label, "Claude API Key");
|
||||
}).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":"api-key"}\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.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
|
||||
@@ -771,7 +947,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude is not authenticated. Run `claude auth login` and try again.",
|
||||
@@ -799,7 +975,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "error");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unauthenticated");
|
||||
assert.strictEqual(status.auth.status, "unauthenticated");
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
mockSpawnerLayer((args) => {
|
||||
@@ -819,7 +995,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
assert.strictEqual(status.provider, "claudeAgent");
|
||||
assert.strictEqual(status.status, "warning");
|
||||
assert.strictEqual(status.installed, true);
|
||||
assert.strictEqual(status.authStatus, "unknown");
|
||||
assert.strictEqual(status.auth.status, "unknown");
|
||||
assert.strictEqual(
|
||||
status.message,
|
||||
"Claude Agent authentication status command is unavailable in this version of Claude.",
|
||||
@@ -844,7 +1020,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
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");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=true is authenticated", () => {
|
||||
@@ -854,7 +1030,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "ready");
|
||||
assert.strictEqual(parsed.authStatus, "authenticated");
|
||||
assert.strictEqual(parsed.auth.status, "authenticated");
|
||||
});
|
||||
|
||||
it("JSON with loggedIn=false is unauthenticated", () => {
|
||||
@@ -864,7 +1040,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "error");
|
||||
assert.strictEqual(parsed.authStatus, "unauthenticated");
|
||||
assert.strictEqual(parsed.auth.status, "unauthenticated");
|
||||
});
|
||||
|
||||
it("JSON without auth marker is warning", () => {
|
||||
@@ -874,7 +1050,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
|
||||
code: 0,
|
||||
});
|
||||
assert.strictEqual(parsed.status, "warning");
|
||||
assert.strictEqual(parsed.authStatus, "unknown");
|
||||
assert.strictEqual(parsed.auth.status, "unknown");
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ServerProviderModel } from "@t3tools/contracts";
|
||||
|
||||
export type CodexPlanType =
|
||||
| "free"
|
||||
| "go"
|
||||
| "plus"
|
||||
| "pro"
|
||||
| "team"
|
||||
| "business"
|
||||
| "enterprise"
|
||||
| "edu"
|
||||
| "unknown";
|
||||
|
||||
export interface CodexAccountSnapshot {
|
||||
readonly type: "apiKey" | "chatgpt" | "unknown";
|
||||
readonly planType: CodexPlanType | null;
|
||||
readonly sparkEnabled: boolean;
|
||||
}
|
||||
|
||||
export const CODEX_DEFAULT_MODEL = "gpt-5.3-codex";
|
||||
export const CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
|
||||
const CODEX_SPARK_ENABLED_PLAN_TYPES = new Set<CodexPlanType>(["pro"]);
|
||||
|
||||
function asObject(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
export function readCodexAccountSnapshot(response: unknown): CodexAccountSnapshot {
|
||||
const record = asObject(response);
|
||||
const account = asObject(record?.account) ?? record;
|
||||
const accountType = asString(account?.type);
|
||||
|
||||
if (accountType === "apiKey") {
|
||||
return {
|
||||
type: "apiKey",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (accountType === "chatgpt") {
|
||||
const planType = (account?.planType as CodexPlanType | null) ?? "unknown";
|
||||
return {
|
||||
type: "chatgpt",
|
||||
planType,
|
||||
sparkEnabled: CODEX_SPARK_ENABLED_PLAN_TYPES.has(planType),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
type: "unknown",
|
||||
planType: null,
|
||||
sparkEnabled: false,
|
||||
};
|
||||
}
|
||||
|
||||
export function codexAuthSubType(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
if (account?.type === "apiKey") {
|
||||
return "apiKey";
|
||||
}
|
||||
|
||||
if (account?.type !== "chatgpt") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return account.planType && account.planType !== "unknown" ? account.planType : "chatgpt";
|
||||
}
|
||||
|
||||
export function codexAuthSubLabel(account: CodexAccountSnapshot | undefined): string | undefined {
|
||||
switch (codexAuthSubType(account)) {
|
||||
case "apiKey":
|
||||
return "OpenAI API Key";
|
||||
case "chatgpt":
|
||||
return "ChatGPT Subscription";
|
||||
case "free":
|
||||
return "ChatGPT Free Subscription";
|
||||
case "go":
|
||||
return "ChatGPT Go Subscription";
|
||||
case "plus":
|
||||
return "ChatGPT Plus Subscription";
|
||||
case "pro":
|
||||
return "ChatGPT Pro Subscription";
|
||||
case "team":
|
||||
return "ChatGPT Team Subscription";
|
||||
case "business":
|
||||
return "ChatGPT Business Subscription";
|
||||
case "enterprise":
|
||||
return "ChatGPT Enterprise Subscription";
|
||||
case "edu":
|
||||
return "ChatGPT Edu Subscription";
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function adjustCodexModelsForAccount(
|
||||
baseModels: ReadonlyArray<ServerProviderModel>,
|
||||
account: CodexAccountSnapshot | undefined,
|
||||
): ReadonlyArray<ServerProviderModel> {
|
||||
if (account?.sparkEnabled !== false) {
|
||||
return baseModels;
|
||||
}
|
||||
|
||||
return baseModels.filter((model) => model.isCustom || model.slug !== CODEX_SPARK_MODEL);
|
||||
}
|
||||
|
||||
export function resolveCodexModelForAccount(
|
||||
model: string | undefined,
|
||||
account: CodexAccountSnapshot,
|
||||
): string | undefined {
|
||||
if (model !== CODEX_SPARK_MODEL || account.sparkEnabled) {
|
||||
return model;
|
||||
}
|
||||
|
||||
return CODEX_DEFAULT_MODEL;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import { readCodexAccountSnapshot, type CodexAccountSnapshot } from "./codexAccount";
|
||||
|
||||
interface JsonRpcProbeResponse {
|
||||
readonly id?: unknown;
|
||||
readonly result?: unknown;
|
||||
readonly error?: {
|
||||
readonly message?: unknown;
|
||||
};
|
||||
}
|
||||
|
||||
function readErrorMessage(response: JsonRpcProbeResponse): string | undefined {
|
||||
return typeof response.error?.message === "string" ? response.error.message : undefined;
|
||||
}
|
||||
|
||||
export function buildCodexInitializeParams() {
|
||||
return {
|
||||
clientInfo: {
|
||||
name: "t3code_desktop",
|
||||
title: "T3 Code Desktop",
|
||||
version: "0.1.0",
|
||||
},
|
||||
capabilities: {
|
||||
experimentalApi: true,
|
||||
},
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function killCodexChildProcess(child: ChildProcessWithoutNullStreams): void {
|
||||
if (process.platform === "win32" && child.pid !== undefined) {
|
||||
try {
|
||||
spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
|
||||
return;
|
||||
} catch {
|
||||
// Fall through to direct kill when taskkill is unavailable.
|
||||
}
|
||||
}
|
||||
|
||||
child.kill();
|
||||
}
|
||||
|
||||
export async function probeCodexAccount(input: {
|
||||
readonly binaryPath: string;
|
||||
readonly homePath?: string;
|
||||
readonly signal?: AbortSignal;
|
||||
}): Promise<CodexAccountSnapshot> {
|
||||
return await new Promise((resolve, reject) => {
|
||||
const child = spawn(input.binaryPath, ["app-server"], {
|
||||
env: {
|
||||
...process.env,
|
||||
...(input.homePath ? { CODEX_HOME: input.homePath } : {}),
|
||||
},
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
shell: process.platform === "win32",
|
||||
});
|
||||
const output = readline.createInterface({ input: child.stdout });
|
||||
|
||||
let completed = false;
|
||||
|
||||
const cleanup = () => {
|
||||
output.removeAllListeners();
|
||||
output.close();
|
||||
child.removeAllListeners();
|
||||
if (!child.killed) {
|
||||
killCodexChildProcess(child);
|
||||
}
|
||||
};
|
||||
|
||||
const finish = (callback: () => void) => {
|
||||
if (completed) return;
|
||||
completed = true;
|
||||
cleanup();
|
||||
callback();
|
||||
};
|
||||
|
||||
const fail = (error: unknown) =>
|
||||
finish(() =>
|
||||
reject(
|
||||
error instanceof Error
|
||||
? error
|
||||
: new Error(`Codex account probe failed: ${String(error)}.`),
|
||||
),
|
||||
);
|
||||
|
||||
if (input.signal?.aborted) {
|
||||
fail(new Error("Codex account probe aborted."));
|
||||
return;
|
||||
}
|
||||
input.signal?.addEventListener("abort", () => fail(new Error("Codex account probe aborted.")));
|
||||
|
||||
const writeMessage = (message: unknown) => {
|
||||
if (!child.stdin.writable) {
|
||||
fail(new Error("Cannot write to codex app-server stdin."));
|
||||
return;
|
||||
}
|
||||
|
||||
child.stdin.write(`${JSON.stringify(message)}\n`);
|
||||
};
|
||||
|
||||
output.on("line", (line) => {
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(line);
|
||||
} catch {
|
||||
fail(new Error("Received invalid JSON from codex app-server during account probe."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!parsed || typeof parsed !== "object") {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = parsed as JsonRpcProbeResponse;
|
||||
if (response.id === 1) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`initialize failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
writeMessage({ method: "initialized" });
|
||||
writeMessage({ id: 2, method: "account/read", params: {} });
|
||||
return;
|
||||
}
|
||||
|
||||
if (response.id === 2) {
|
||||
const errorMessage = readErrorMessage(response);
|
||||
if (errorMessage) {
|
||||
fail(new Error(`account/read failed: ${errorMessage}`));
|
||||
return;
|
||||
}
|
||||
|
||||
finish(() => resolve(readCodexAccountSnapshot(response.result)));
|
||||
}
|
||||
});
|
||||
|
||||
child.once("error", fail);
|
||||
child.once("exit", (code, signal) => {
|
||||
if (completed) return;
|
||||
fail(
|
||||
new Error(
|
||||
`codex app-server exited before probe completed (code=${code ?? "null"}, signal=${signal ?? "null"}).`,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
writeMessage({
|
||||
id: 1,
|
||||
method: "initialize",
|
||||
params: buildCodexInitializeParams(),
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import type {
|
||||
ServerProvider,
|
||||
ServerProviderAuthStatus,
|
||||
ServerProviderAuth,
|
||||
ServerProviderModel,
|
||||
ServerProviderState,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -21,7 +21,7 @@ export interface ProviderProbeResult {
|
||||
readonly installed: boolean;
|
||||
readonly version: string | null;
|
||||
readonly status: Exclude<ServerProviderState, "disabled">;
|
||||
readonly authStatus: ServerProviderAuthStatus;
|
||||
readonly auth: ServerProviderAuth;
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
@@ -137,7 +137,7 @@ export function buildServerProvider(input: {
|
||||
installed: input.probe.installed,
|
||||
version: input.probe.version,
|
||||
status: input.enabled ? input.probe.status : "disabled",
|
||||
authStatus: input.probe.authStatus,
|
||||
auth: input.probe.auth,
|
||||
checkedAt: input.checkedAt,
|
||||
...(input.probe.message ? { message: input.probe.message } : {}),
|
||||
models: input.models,
|
||||
|
||||
@@ -104,6 +104,43 @@ it.layer(NodeServices.layer)("server settings", (it) => {
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("preserves model when switching providers via textGenerationModelSelection", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
// Start with Claude text generation selection
|
||||
yield* serverSettings.updateSettings({
|
||||
textGenerationModelSelection: {
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
options: {
|
||||
effort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Switch to Codex — the stale Claude "effort" in options must not
|
||||
// cause the update to lose the selected model.
|
||||
const next = yield* serverSettings.updateSettings({
|
||||
textGenerationModelSelection: {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(next.textGenerationModelSelection, {
|
||||
provider: "codex",
|
||||
model: "gpt-5.4",
|
||||
options: {
|
||||
reasoningEffort: "high",
|
||||
},
|
||||
});
|
||||
}).pipe(Effect.provide(makeServerSettingsLayer())),
|
||||
);
|
||||
|
||||
it.effect("trims provider path settings when updates are applied", () =>
|
||||
Effect.gen(function* () {
|
||||
const serverSettings = yield* ServerSettingsService;
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
FileSystem,
|
||||
Layer,
|
||||
Path,
|
||||
Equal,
|
||||
PubSub,
|
||||
Ref,
|
||||
Schema,
|
||||
@@ -130,9 +131,12 @@ function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings
|
||||
};
|
||||
}
|
||||
|
||||
// Values under these keys are compared as a whole — never stripped field-by-field.
|
||||
const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
|
||||
|
||||
function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
|
||||
if (Array.isArray(current) || Array.isArray(defaults)) {
|
||||
return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current;
|
||||
return Equal.equals(current, defaults) ? undefined : current;
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -146,9 +150,15 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow
|
||||
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;
|
||||
if (ATOMIC_SETTINGS_KEYS.has(key)) {
|
||||
if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
|
||||
next[key] = currentRecord[key];
|
||||
}
|
||||
} else {
|
||||
const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
|
||||
if (stripped !== undefined) {
|
||||
next[key] = stripped;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@ const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [],
|
||||
},
|
||||
|
||||
@@ -397,7 +397,6 @@ export function BranchToolbarBranchSelector({
|
||||
key={itemValue}
|
||||
index={index}
|
||||
value={itemValue}
|
||||
className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined}
|
||||
style={style}
|
||||
onClick={() => selectBranch(branch)}
|
||||
>
|
||||
|
||||
@@ -117,7 +117,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: NOW_ISO,
|
||||
models: [],
|
||||
},
|
||||
@@ -1041,6 +1041,19 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it("shows an explicit empty state for projects without threads in the sidebar", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createDraftOnlySnapshot(),
|
||||
});
|
||||
|
||||
try {
|
||||
await expect.element(page.getByText("No threads yet")).toBeInTheDocument();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("opens the project cwd for draft threads without a worktree path", async () => {
|
||||
setDraftThreadWithoutWorktree();
|
||||
|
||||
@@ -1760,6 +1773,117 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("restores the connecting composer state without showing the stop button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-connecting-state" as MessageId,
|
||||
targetText: "connecting state target",
|
||||
sessionStatus: "starting",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const connectingButton = await waitForElement(
|
||||
() => document.querySelector<HTMLButtonElement>('button[aria-label="Connecting"]'),
|
||||
"Unable to find connecting send button.",
|
||||
);
|
||||
expect(connectingButton.disabled).toBe(true);
|
||||
expect(
|
||||
document.querySelector<HTMLButtonElement>('button[aria-label="Stop generation"]'),
|
||||
).toBeNull();
|
||||
|
||||
const composerEditor = await waitForElement(
|
||||
() => document.querySelector<HTMLElement>('[contenteditable="false"]'),
|
||||
"Unable to find disabled composer editor.",
|
||||
);
|
||||
expect(composerEditor).toBeTruthy();
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("hides the archive action when the pointer leaves a thread row", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-archive-hover-test" as MessageId,
|
||||
targetText: "archive hover target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
|
||||
|
||||
await expect.element(threadRow).toBeInTheDocument();
|
||||
const archiveButton = await waitForElement(
|
||||
() =>
|
||||
document.querySelector<HTMLButtonElement>(`[data-testid="thread-archive-${THREAD_ID}"]`),
|
||||
"Unable to find archive button.",
|
||||
);
|
||||
const archiveAction = archiveButton.parentElement;
|
||||
expect(
|
||||
archiveAction,
|
||||
"Archive button should render inside a visibility wrapper.",
|
||||
).not.toBeNull();
|
||||
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
|
||||
|
||||
await threadRow.hover();
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(getComputedStyle(archiveAction!).opacity).toBe("1");
|
||||
},
|
||||
{ timeout: 4_000, interval: 16 },
|
||||
);
|
||||
|
||||
await page.getByTestId("composer-editor").hover();
|
||||
await vi.waitFor(
|
||||
() => {
|
||||
expect(getComputedStyle(archiveAction!).opacity).toBe("0");
|
||||
},
|
||||
{ timeout: 4_000, interval: 16 },
|
||||
);
|
||||
} finally {
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("shows the confirm archive action after clicking the archive button", async () => {
|
||||
localStorage.setItem(
|
||||
"t3code:client-settings:v1",
|
||||
JSON.stringify({
|
||||
...DEFAULT_CLIENT_SETTINGS,
|
||||
confirmThreadArchive: true,
|
||||
}),
|
||||
);
|
||||
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
snapshot: createSnapshotForTargetUser({
|
||||
targetMessageId: "msg-user-archive-confirm-test" as MessageId,
|
||||
targetText: "archive confirm target",
|
||||
}),
|
||||
});
|
||||
|
||||
try {
|
||||
const threadRow = page.getByTestId(`thread-row-${THREAD_ID}`);
|
||||
|
||||
await expect.element(threadRow).toBeInTheDocument();
|
||||
await threadRow.hover();
|
||||
|
||||
const archiveButton = page.getByTestId(`thread-archive-${THREAD_ID}`);
|
||||
await expect.element(archiveButton).toBeInTheDocument();
|
||||
await archiveButton.click();
|
||||
|
||||
const confirmButton = page.getByTestId(`thread-archive-confirm-${THREAD_ID}`);
|
||||
await expect.element(confirmButton).toBeInTheDocument();
|
||||
await expect.element(confirmButton).toBeVisible();
|
||||
} finally {
|
||||
localStorage.removeItem("t3code:client-settings:v1");
|
||||
await mounted.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("keeps the new thread selected after clicking the new-thread button", async () => {
|
||||
const mounted = await mountChatView({
|
||||
viewport: DEFAULT_VIEWPORT,
|
||||
|
||||
@@ -75,8 +75,6 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
|
||||
return previewUrls;
|
||||
}
|
||||
|
||||
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
|
||||
|
||||
export interface PullRequestDialogState {
|
||||
initialReference: string | null;
|
||||
key: number;
|
||||
|
||||
@@ -175,7 +175,6 @@ import {
|
||||
readFileAsDataUrl,
|
||||
revokeBlobPreviewUrl,
|
||||
revokeUserMessagePreviewUrls,
|
||||
SendPhase,
|
||||
} from "./ChatView.logic";
|
||||
import { useLocalStorage } from "~/hooks/useLocalStorage";
|
||||
|
||||
@@ -246,9 +245,15 @@ interface PendingPullRequestSetupRequest {
|
||||
}
|
||||
|
||||
export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const beginThreadSend = useStore((store) => store.beginThreadSend);
|
||||
const clearThreadSend = useStore((store) => store.clearThreadSend);
|
||||
const markThreadSendSettled = useStore((store) => store.markThreadSendSettled);
|
||||
const moveThreadSend = useStore((store) => store.moveThreadSend);
|
||||
const threads = useStore((store) => store.threads);
|
||||
const projects = useStore((store) => store.projects);
|
||||
const markThreadVisited = useStore((store) => store.markThreadVisited);
|
||||
const pendingThreadSend = useStore((store) => store.pendingThreadSendById[threadId] ?? null);
|
||||
const setThreadSendPhase = useStore((store) => store.setThreadSendPhase);
|
||||
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
|
||||
const setStoreThreadError = useStore((store) => store.setError);
|
||||
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
|
||||
@@ -325,14 +330,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);
|
||||
const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);
|
||||
const optimisticUserMessagesRef = useRef(optimisticUserMessages);
|
||||
optimisticUserMessagesRef.current = optimisticUserMessages;
|
||||
const composerTerminalContextsRef = useRef<TerminalContextDraft[]>(composerTerminalContexts);
|
||||
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
|
||||
Record<ThreadId, string | null>
|
||||
>({});
|
||||
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
|
||||
const [sendStartedAt, setSendStartedAt] = useState<string | null>(null);
|
||||
const [isConnecting, _setIsConnecting] = useState(false);
|
||||
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
|
||||
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
|
||||
const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<
|
||||
@@ -664,14 +665,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
);
|
||||
const selectedModelForPicker = selectedModel;
|
||||
const phase = derivePhase(activeThread?.session ?? null);
|
||||
const isSendBusy = sendPhase !== "idle";
|
||||
const isPreparingWorktree = sendPhase === "preparing-worktree";
|
||||
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
|
||||
const activeSendStartedAt = pendingThreadSend?.startedAt ?? null;
|
||||
const isSendBusy = pendingThreadSend !== null;
|
||||
const isPreparingWorktree =
|
||||
pendingThreadSend?.phase === "preparing-worktree" && createWorktreeMutation.isPending;
|
||||
const isConnecting = phase === "connecting";
|
||||
const showConnectingState = isConnecting && !isSendBusy;
|
||||
const isWorking = phase === "running" || isSendBusy || isRevertingCheckpoint;
|
||||
const nowIso = new Date(nowTick).toISOString();
|
||||
const activeWorkStartedAt = deriveActiveWorkStartedAt(
|
||||
activeLatestTurn,
|
||||
activeThread?.session ?? null,
|
||||
sendStartedAt,
|
||||
activeSendStartedAt,
|
||||
);
|
||||
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
|
||||
const workLogEntries = useMemo(
|
||||
@@ -1138,9 +1143,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
null,
|
||||
[composerHighlightedItemId, composerMenuItems],
|
||||
);
|
||||
composerMenuOpenRef.current = composerMenuOpen;
|
||||
composerMenuItemsRef.current = composerMenuItems;
|
||||
activeComposerMenuItemRef.current = activeComposerMenuItem;
|
||||
const nonPersistedComposerImageIdSet = useMemo(
|
||||
() => new Set(nonPersistedComposerImageIds),
|
||||
[nonPersistedComposerImageIds],
|
||||
@@ -1980,6 +1982,16 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
composerTerminalContextsRef.current = composerTerminalContexts;
|
||||
}, [composerTerminalContexts]);
|
||||
|
||||
useEffect(() => {
|
||||
optimisticUserMessagesRef.current = optimisticUserMessages;
|
||||
}, [optimisticUserMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
composerMenuOpenRef.current = composerMenuOpen;
|
||||
composerMenuItemsRef.current = composerMenuItems;
|
||||
activeComposerMenuItemRef.current = activeComposerMenuItem;
|
||||
}, [activeComposerMenuItem, composerMenuItems, composerMenuOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThread?.id) return;
|
||||
if (activeThread.messages.length === 0) {
|
||||
@@ -2020,8 +2032,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
return [];
|
||||
});
|
||||
setSendPhase("idle");
|
||||
setSendStartedAt(null);
|
||||
sendInFlightRef.current = false;
|
||||
setComposerHighlightedItemId(null);
|
||||
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
|
||||
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
|
||||
@@ -2152,45 +2163,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: "local";
|
||||
|
||||
useEffect(() => {
|
||||
if (phase !== "running") return;
|
||||
if (phase !== "running" && !isSendBusy) return;
|
||||
const timer = window.setInterval(() => {
|
||||
setNowTick(Date.now());
|
||||
}, 1000);
|
||||
return () => {
|
||||
window.clearInterval(timer);
|
||||
};
|
||||
}, [phase]);
|
||||
|
||||
const beginSendPhase = useCallback((nextPhase: Exclude<SendPhase, "idle">) => {
|
||||
setSendStartedAt((current) => current ?? new Date().toISOString());
|
||||
setSendPhase(nextPhase);
|
||||
}, []);
|
||||
|
||||
const resetSendPhase = useCallback(() => {
|
||||
setSendPhase("idle");
|
||||
setSendStartedAt(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (sendPhase === "idle") {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
phase === "running" ||
|
||||
activePendingApproval !== null ||
|
||||
activePendingUserInput !== null ||
|
||||
activeThread?.error
|
||||
) {
|
||||
resetSendPhase();
|
||||
}
|
||||
}, [
|
||||
activePendingApproval,
|
||||
activePendingUserInput,
|
||||
activeThread?.error,
|
||||
phase,
|
||||
resetSendPhase,
|
||||
sendPhase,
|
||||
]);
|
||||
}, [isSendBusy, phase]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!activeThreadId) return;
|
||||
@@ -2410,7 +2390,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThread || isRevertingCheckpoint) return;
|
||||
|
||||
if (phase === "running" || isSendBusy || isConnecting) {
|
||||
if (phase === "running" || isSendBusy) {
|
||||
setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");
|
||||
return;
|
||||
}
|
||||
@@ -2443,13 +2423,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
}
|
||||
setIsRevertingCheckpoint(false);
|
||||
},
|
||||
[activeThread, isConnecting, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
|
||||
[activeThread, isRevertingCheckpoint, isSendBusy, phase, setThreadError],
|
||||
);
|
||||
|
||||
const onSend = async (e?: { preventDefault: () => void }) => {
|
||||
e?.preventDefault();
|
||||
const api = readNativeApi();
|
||||
if (!api || !activeThread || isSendBusy || isConnecting || sendInFlightRef.current) return;
|
||||
if (!api || !activeThread || isSendBusy || sendInFlightRef.current) return;
|
||||
if (activePendingProgress) {
|
||||
onAdvanceActivePendingUserInput();
|
||||
return;
|
||||
@@ -2528,8 +2508,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
return;
|
||||
}
|
||||
|
||||
const sendStartedAt = new Date().toISOString();
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
|
||||
beginThreadSend(
|
||||
threadIdForSend,
|
||||
baseBranchForWorktree ? "preparing-worktree" : "sending-turn",
|
||||
sendStartedAt,
|
||||
);
|
||||
|
||||
const composerImagesSnapshot = [...composerImages];
|
||||
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
|
||||
@@ -2600,10 +2585,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
let turnStartSucceeded = false;
|
||||
let nextThreadBranch = activeThread.branch;
|
||||
let nextThreadWorktreePath = activeThread.worktreePath;
|
||||
await (async () => {
|
||||
try {
|
||||
// On first message: lock in branch + create worktree if needed.
|
||||
if (baseBranchForWorktree) {
|
||||
beginSendPhase("preparing-worktree");
|
||||
const newBranch = buildTemporaryWorktreeBranchName();
|
||||
const result = await createWorktreeMutation.mutateAsync({
|
||||
cwd: activeProject.cwd,
|
||||
@@ -2678,10 +2662,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
let shouldRunSetupScript = false;
|
||||
if (isServerThread) {
|
||||
shouldRunSetupScript = true;
|
||||
} else {
|
||||
if (createdServerThreadForLocalDraft) {
|
||||
shouldRunSetupScript = true;
|
||||
}
|
||||
} else if (createdServerThreadForLocalDraft) {
|
||||
shouldRunSetupScript = true;
|
||||
}
|
||||
if (shouldRunSetupScript) {
|
||||
const setupScriptOptions: Parameters<typeof runProjectScript>[1] = {
|
||||
@@ -2715,7 +2697,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
}
|
||||
|
||||
beginSendPhase("sending-turn");
|
||||
if (baseBranchForWorktree) {
|
||||
setThreadSendPhase(threadIdForSend, "sending-turn");
|
||||
}
|
||||
const turnAttachments = await turnAttachmentsPromise;
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
@@ -2734,7 +2718,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
createdAt: messageCreatedAt,
|
||||
});
|
||||
turnStartSucceeded = true;
|
||||
})().catch(async (err: unknown) => {
|
||||
markThreadSendSettled(threadIdForSend);
|
||||
} catch (err: unknown) {
|
||||
if (createdServerThreadForLocalDraft && !turnStartSucceeded) {
|
||||
await api.orchestration
|
||||
.dispatchCommand({
|
||||
@@ -2769,11 +2754,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
threadIdForSend,
|
||||
err instanceof Error ? err.message : "Failed to send message.",
|
||||
);
|
||||
});
|
||||
sendInFlightRef.current = false;
|
||||
if (!turnStartSucceeded) {
|
||||
resetSendPhase();
|
||||
clearThreadSend(threadIdForSend);
|
||||
}
|
||||
sendInFlightRef.current = false;
|
||||
};
|
||||
|
||||
const onInterrupt = async () => {
|
||||
@@ -2943,14 +2926,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
interactionMode: "default" | "plan";
|
||||
}) => {
|
||||
const api = readNativeApi();
|
||||
if (
|
||||
!api ||
|
||||
!activeThread ||
|
||||
!isServerThread ||
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
sendInFlightRef.current
|
||||
) {
|
||||
if (!api || !activeThread || !isServerThread || isSendBusy || sendInFlightRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2971,7 +2947,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
});
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase("sending-turn");
|
||||
beginThreadSend(threadIdForSend, "sending-turn", new Date().toISOString());
|
||||
setThreadError(threadIdForSend, null);
|
||||
setOptimisticUserMessages((existing) => [
|
||||
...existing,
|
||||
@@ -3023,6 +2999,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
: {}),
|
||||
createdAt: messageCreatedAt,
|
||||
});
|
||||
markThreadSendSettled(threadIdForSend);
|
||||
// Optimistically open the plan sidebar when implementing (not refining).
|
||||
// "default" mode here means the agent is executing the plan, which produces
|
||||
// step-tracking activities that the sidebar will display.
|
||||
@@ -3030,34 +3007,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
planSidebarDismissedForTurnRef.current = null;
|
||||
setPlanSidebarOpen(true);
|
||||
}
|
||||
sendInFlightRef.current = false;
|
||||
} catch (err) {
|
||||
setOptimisticUserMessages((existing) =>
|
||||
existing.filter((message) => message.id !== messageIdForSend),
|
||||
);
|
||||
clearThreadSend(threadIdForSend);
|
||||
setThreadError(
|
||||
threadIdForSend,
|
||||
err instanceof Error ? err.message : "Failed to send plan follow-up.",
|
||||
);
|
||||
sendInFlightRef.current = false;
|
||||
resetSendPhase();
|
||||
}
|
||||
sendInFlightRef.current = false;
|
||||
},
|
||||
[
|
||||
activeThread,
|
||||
activeProposedPlan,
|
||||
beginSendPhase,
|
||||
forceStickToBottom,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
persistThreadSettingsForNextTurn,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
selectedProvider,
|
||||
selectedProviderModels,
|
||||
beginThreadSend,
|
||||
clearThreadSend,
|
||||
markThreadSendSettled,
|
||||
setComposerDraftInteractionMode,
|
||||
setThreadError,
|
||||
selectedModel,
|
||||
@@ -3073,7 +3049,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
!activeProposedPlan ||
|
||||
!isServerThread ||
|
||||
isSendBusy ||
|
||||
isConnecting ||
|
||||
sendInFlightRef.current
|
||||
) {
|
||||
return;
|
||||
@@ -3094,14 +3069,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
|
||||
|
||||
sendInFlightRef.current = true;
|
||||
beginSendPhase("sending-turn");
|
||||
const finish = () => {
|
||||
sendInFlightRef.current = false;
|
||||
resetSendPhase();
|
||||
};
|
||||
beginThreadSend(activeThread.id, "sending-turn", createdAt);
|
||||
|
||||
await api.orchestration
|
||||
.dispatchCommand({
|
||||
try {
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.create",
|
||||
commandId: newCommandId(),
|
||||
threadId: nextThreadId,
|
||||
@@ -3113,72 +3084,75 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
branch: activeThread.branch,
|
||||
worktreePath: activeThread.worktreePath,
|
||||
createdAt,
|
||||
})
|
||||
.then(() => {
|
||||
return api.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
});
|
||||
|
||||
await api.orchestration.dispatchCommand({
|
||||
type: "thread.turn.start",
|
||||
commandId: newCommandId(),
|
||||
threadId: nextThreadId,
|
||||
message: {
|
||||
messageId: newMessageId(),
|
||||
role: "user",
|
||||
text: outgoingImplementationPrompt,
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: selectedModelSelection,
|
||||
titleSeed: nextThreadTitle,
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
createdAt,
|
||||
});
|
||||
|
||||
moveThreadSend(activeThread.id, nextThreadId);
|
||||
markThreadSendSettled(nextThreadId);
|
||||
const snapshot = await api.orchestration.getSnapshot();
|
||||
syncServerReadModel(snapshot);
|
||||
// Signal that the plan sidebar should open on the new thread.
|
||||
planSidebarOpenOnNextThreadRef.current = true;
|
||||
await navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: nextThreadId },
|
||||
});
|
||||
} catch (err) {
|
||||
clearThreadSend(activeThread.id);
|
||||
clearThreadSend(nextThreadId);
|
||||
await api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
threadId: nextThreadId,
|
||||
message: {
|
||||
messageId: newMessageId(),
|
||||
role: "user",
|
||||
text: outgoingImplementationPrompt,
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection: selectedModelSelection,
|
||||
titleSeed: nextThreadTitle,
|
||||
runtimeMode,
|
||||
interactionMode: "default",
|
||||
createdAt,
|
||||
});
|
||||
})
|
||||
.then(() => api.orchestration.getSnapshot())
|
||||
.then((snapshot) => {
|
||||
syncServerReadModel(snapshot);
|
||||
// Signal that the plan sidebar should open on the new thread.
|
||||
planSidebarOpenOnNextThreadRef.current = true;
|
||||
return navigate({
|
||||
to: "/$threadId",
|
||||
params: { threadId: nextThreadId },
|
||||
});
|
||||
})
|
||||
.catch(async (err) => {
|
||||
await api.orchestration
|
||||
.dispatchCommand({
|
||||
type: "thread.delete",
|
||||
commandId: newCommandId(),
|
||||
threadId: nextThreadId,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
await api.orchestration
|
||||
.getSnapshot()
|
||||
.then((snapshot) => {
|
||||
syncServerReadModel(snapshot);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not start implementation thread",
|
||||
description:
|
||||
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
|
||||
});
|
||||
})
|
||||
.then(finish, finish);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
await api.orchestration
|
||||
.getSnapshot()
|
||||
.then((snapshot) => {
|
||||
syncServerReadModel(snapshot);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
toastManager.add({
|
||||
type: "error",
|
||||
title: "Could not start implementation thread",
|
||||
description:
|
||||
err instanceof Error ? err.message : "An error occurred while creating the new thread.",
|
||||
});
|
||||
}
|
||||
sendInFlightRef.current = false;
|
||||
}, [
|
||||
activeProject,
|
||||
activeProposedPlan,
|
||||
activeThread,
|
||||
beginSendPhase,
|
||||
isConnecting,
|
||||
isSendBusy,
|
||||
isServerThread,
|
||||
navigate,
|
||||
resetSendPhase,
|
||||
runtimeMode,
|
||||
selectedPromptEffort,
|
||||
selectedModelSelection,
|
||||
selectedProvider,
|
||||
selectedProviderModels,
|
||||
beginThreadSend,
|
||||
clearThreadSend,
|
||||
markThreadSendSettled,
|
||||
moveThreadSend,
|
||||
syncServerReadModel,
|
||||
selectedModel,
|
||||
]);
|
||||
@@ -3846,7 +3820,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
? "Ask for follow-up changes or attach images"
|
||||
: "Ask anything, @tag files/folders, or use / to show available commands"
|
||||
}
|
||||
disabled={isConnecting || isComposerApprovalState}
|
||||
disabled={showConnectingState || isComposerApprovalState}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -4071,9 +4045,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
type="submit"
|
||||
size="sm"
|
||||
className="h-9 rounded-full px-4 sm:h-8"
|
||||
disabled={isSendBusy || isConnecting}
|
||||
disabled={isSendBusy || showConnectingState}
|
||||
>
|
||||
{isConnecting || isSendBusy ? "Sending..." : "Refine"}
|
||||
{showConnectingState
|
||||
? "Connecting..."
|
||||
: isSendBusy
|
||||
? "Sending..."
|
||||
: "Refine"}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="flex items-center">
|
||||
@@ -4081,9 +4059,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
type="submit"
|
||||
size="sm"
|
||||
className="h-9 rounded-l-full rounded-r-none px-4 sm:h-8"
|
||||
disabled={isSendBusy || isConnecting}
|
||||
disabled={isSendBusy || showConnectingState}
|
||||
>
|
||||
{isConnecting || isSendBusy ? "Sending..." : "Implement"}
|
||||
{showConnectingState
|
||||
? "Connecting..."
|
||||
: isSendBusy
|
||||
? "Sending..."
|
||||
: "Implement"}
|
||||
</Button>
|
||||
<Menu>
|
||||
<MenuTrigger
|
||||
@@ -4093,7 +4075,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
variant="default"
|
||||
className="h-9 rounded-l-none rounded-r-full border-l-white/12 px-2 sm:h-8"
|
||||
aria-label="Implementation actions"
|
||||
disabled={isSendBusy || isConnecting}
|
||||
disabled={isSendBusy || showConnectingState}
|
||||
/>
|
||||
}
|
||||
>
|
||||
@@ -4101,7 +4083,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
</MenuTrigger>
|
||||
<MenuPopup align="end" side="top">
|
||||
<MenuItem
|
||||
disabled={isSendBusy || isConnecting}
|
||||
disabled={isSendBusy || showConnectingState}
|
||||
onClick={() => void onImplementPlanInNewThread()}
|
||||
>
|
||||
Implement in a new thread
|
||||
@@ -4115,19 +4097,21 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
type="submit"
|
||||
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
|
||||
isSendBusy ||
|
||||
showConnectingState ||
|
||||
!composerSendState.hasSendableContent
|
||||
}
|
||||
aria-label={
|
||||
isConnecting
|
||||
? "Connecting"
|
||||
: isPreparingWorktree
|
||||
? "Preparing worktree"
|
||||
isPreparingWorktree
|
||||
? "Preparing worktree"
|
||||
: showConnectingState
|
||||
? "Connecting"
|
||||
: isSendBusy
|
||||
? "Sending"
|
||||
: "Send message"
|
||||
}
|
||||
>
|
||||
{isConnecting || isSendBusy ? (
|
||||
{showConnectingState || isSendBusy ? (
|
||||
<svg
|
||||
width="14"
|
||||
height="14"
|
||||
|
||||
@@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: NOW_ISO,
|
||||
models: [],
|
||||
},
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createThreadJumpHintVisibilityController,
|
||||
getVisibleSidebarThreadIds,
|
||||
resolveAdjacentThreadId,
|
||||
getFallbackThreadIdAfterDelete,
|
||||
@@ -15,6 +16,7 @@ import {
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
} from "./Sidebar.logic";
|
||||
import { ProjectId, ThreadId } from "@t3tools/contracts";
|
||||
import {
|
||||
@@ -52,6 +54,68 @@ describe("hasUnseenCompletion", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("createThreadJumpHintVisibilityController", () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("delays showing jump hints until the configured delay elapses", () => {
|
||||
const visibilityChanges: boolean[] = [];
|
||||
const controller = createThreadJumpHintVisibilityController({
|
||||
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
onVisibilityChange: (visible) => {
|
||||
visibilityChanges.push(visible);
|
||||
},
|
||||
});
|
||||
|
||||
controller.sync(true);
|
||||
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS - 1);
|
||||
|
||||
expect(visibilityChanges).toEqual([]);
|
||||
|
||||
vi.advanceTimersByTime(1);
|
||||
|
||||
expect(visibilityChanges).toEqual([true]);
|
||||
});
|
||||
|
||||
it("hides immediately when the modifiers are released", () => {
|
||||
const visibilityChanges: boolean[] = [];
|
||||
const controller = createThreadJumpHintVisibilityController({
|
||||
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
onVisibilityChange: (visible) => {
|
||||
visibilityChanges.push(visible);
|
||||
},
|
||||
});
|
||||
|
||||
controller.sync(true);
|
||||
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
|
||||
controller.sync(false);
|
||||
|
||||
expect(visibilityChanges).toEqual([true, false]);
|
||||
});
|
||||
|
||||
it("cancels a pending reveal when the modifier is released early", () => {
|
||||
const visibilityChanges: boolean[] = [];
|
||||
const controller = createThreadJumpHintVisibilityController({
|
||||
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
onVisibilityChange: (visible) => {
|
||||
visibilityChanges.push(visible);
|
||||
},
|
||||
});
|
||||
|
||||
controller.sync(true);
|
||||
vi.advanceTimersByTime(Math.floor(THREAD_JUMP_HINT_SHOW_DELAY_MS / 2));
|
||||
controller.sync(false);
|
||||
vi.advanceTimersByTime(THREAD_JUMP_HINT_SHOW_DELAY_MS);
|
||||
|
||||
expect(visibilityChanges).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("shouldClearThreadSelectionOnMouseDown", () => {
|
||||
it("preserves selection for thread items", () => {
|
||||
const child = {
|
||||
@@ -171,6 +235,27 @@ describe("getVisibleSidebarThreadIds", () => {
|
||||
ThreadId.makeUnsafe("thread-6"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("skips threads from collapsed projects whose thread panels are not shown", () => {
|
||||
expect(
|
||||
getVisibleSidebarThreadIds([
|
||||
{
|
||||
shouldShowThreadPanel: false,
|
||||
renderedThreads: [
|
||||
{ id: ThreadId.makeUnsafe("thread-hidden-2") },
|
||||
{ id: ThreadId.makeUnsafe("thread-hidden-1") },
|
||||
],
|
||||
},
|
||||
{
|
||||
shouldShowThreadPanel: true,
|
||||
renderedThreads: [
|
||||
{ id: ThreadId.makeUnsafe("thread-12") },
|
||||
{ id: ThreadId.makeUnsafe("thread-11") },
|
||||
],
|
||||
},
|
||||
]),
|
||||
).toEqual([ThreadId.makeUnsafe("thread-12"), ThreadId.makeUnsafe("thread-11")]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isContextMenuPointerDown", () => {
|
||||
@@ -429,6 +514,9 @@ describe("getVisibleThreadsForProject", () => {
|
||||
ThreadId.makeUnsafe("thread-6"),
|
||||
ThreadId.makeUnsafe("thread-8"),
|
||||
]);
|
||||
expect(result.hiddenThreads.map((thread) => thread.id)).toEqual([
|
||||
ThreadId.makeUnsafe("thread-7"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("returns all threads when the list is expanded", () => {
|
||||
@@ -449,6 +537,7 @@ describe("getVisibleThreadsForProject", () => {
|
||||
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
|
||||
threads.map((thread) => thread.id),
|
||||
);
|
||||
expect(result.hiddenThreads).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import * as React from "react";
|
||||
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
|
||||
import type { Thread } from "../types";
|
||||
import { cn } from "../lib/utils";
|
||||
@@ -8,6 +9,7 @@ import {
|
||||
} from "../session-logic";
|
||||
|
||||
export const THREAD_SELECTION_SAFE_SELECTOR = "[data-thread-item], [data-thread-selection-safe]";
|
||||
export const THREAD_JUMP_HINT_SHOW_DELAY_MS = 100;
|
||||
export type SidebarNewThreadEnvMode = "local" | "worktree";
|
||||
type SidebarProject = {
|
||||
id: string;
|
||||
@@ -46,6 +48,91 @@ type ThreadStatusInput = Pick<
|
||||
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
|
||||
>;
|
||||
|
||||
export interface ThreadJumpHintVisibilityController {
|
||||
sync: (shouldShow: boolean) => void;
|
||||
dispose: () => void;
|
||||
}
|
||||
|
||||
export function createThreadJumpHintVisibilityController(input: {
|
||||
delayMs: number;
|
||||
onVisibilityChange: (visible: boolean) => void;
|
||||
setTimeoutFn?: typeof globalThis.setTimeout;
|
||||
clearTimeoutFn?: typeof globalThis.clearTimeout;
|
||||
}): ThreadJumpHintVisibilityController {
|
||||
const setTimeoutFn = input.setTimeoutFn ?? globalThis.setTimeout;
|
||||
const clearTimeoutFn = input.clearTimeoutFn ?? globalThis.clearTimeout;
|
||||
let isVisible = false;
|
||||
let timeoutId: NodeJS.Timeout | null = null;
|
||||
|
||||
const clearPendingShow = () => {
|
||||
if (timeoutId === null) {
|
||||
return;
|
||||
}
|
||||
clearTimeoutFn(timeoutId);
|
||||
timeoutId = null;
|
||||
};
|
||||
|
||||
return {
|
||||
sync: (shouldShow) => {
|
||||
if (!shouldShow) {
|
||||
clearPendingShow();
|
||||
if (isVisible) {
|
||||
isVisible = false;
|
||||
input.onVisibilityChange(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (isVisible || timeoutId !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
timeoutId = setTimeoutFn(() => {
|
||||
timeoutId = null;
|
||||
isVisible = true;
|
||||
input.onVisibilityChange(true);
|
||||
}, input.delayMs);
|
||||
},
|
||||
dispose: () => {
|
||||
clearPendingShow();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function useThreadJumpHintVisibility(): {
|
||||
showThreadJumpHints: boolean;
|
||||
updateThreadJumpHintsVisibility: (shouldShow: boolean) => void;
|
||||
} {
|
||||
const [showThreadJumpHints, setShowThreadJumpHints] = React.useState(false);
|
||||
const controllerRef = React.useRef<ThreadJumpHintVisibilityController | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
const controller = createThreadJumpHintVisibilityController({
|
||||
delayMs: THREAD_JUMP_HINT_SHOW_DELAY_MS,
|
||||
onVisibilityChange: (visible) => {
|
||||
setShowThreadJumpHints(visible);
|
||||
},
|
||||
setTimeoutFn: window.setTimeout.bind(window),
|
||||
clearTimeoutFn: window.clearTimeout.bind(window),
|
||||
});
|
||||
controllerRef.current = controller;
|
||||
|
||||
return () => {
|
||||
controller.dispose();
|
||||
controllerRef.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const updateThreadJumpHintsVisibility = React.useCallback((shouldShow: boolean) => {
|
||||
controllerRef.current?.sync(shouldShow);
|
||||
}, []);
|
||||
|
||||
return {
|
||||
showThreadJumpHints,
|
||||
updateThreadJumpHintsVisibility,
|
||||
};
|
||||
}
|
||||
|
||||
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
|
||||
if (!thread.latestTurn?.completedAt) return false;
|
||||
const completedAt = Date.parse(thread.latestTurn.completedAt);
|
||||
@@ -71,13 +158,16 @@ export function resolveSidebarNewThreadEnvMode(input: {
|
||||
|
||||
export function getVisibleSidebarThreadIds<TThreadId>(
|
||||
renderedProjects: readonly {
|
||||
shouldShowThreadPanel?: boolean;
|
||||
renderedThreads: readonly {
|
||||
id: TThreadId;
|
||||
}[];
|
||||
}[],
|
||||
): TThreadId[] {
|
||||
return renderedProjects.flatMap((renderedProject) =>
|
||||
renderedProject.renderedThreads.map((thread) => thread.id),
|
||||
renderedProject.shouldShowThreadPanel === false
|
||||
? []
|
||||
: renderedProject.renderedThreads.map((thread) => thread.id),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -244,6 +334,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
previewLimit: number;
|
||||
}): {
|
||||
hasHiddenThreads: boolean;
|
||||
hiddenThreads: Thread[];
|
||||
visibleThreads: Thread[];
|
||||
} {
|
||||
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
|
||||
@@ -252,6 +343,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!hasHiddenThreads || isThreadListExpanded) {
|
||||
return {
|
||||
hasHiddenThreads,
|
||||
hiddenThreads: [],
|
||||
visibleThreads: [...threads],
|
||||
};
|
||||
}
|
||||
@@ -260,6 +352,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.slice(previewLimit),
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
@@ -268,6 +361,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!activeThread) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.slice(previewLimit),
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
@@ -276,6 +370,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
|
||||
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
|
||||
};
|
||||
}
|
||||
|
||||
+189
-114
@@ -69,6 +69,7 @@ import { serverConfigQueryOptions } from "../lib/serverReactQuery";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { useComposerDraftStore } from "../composerDraftStore";
|
||||
import { useHandleNewThread } from "../hooks/useHandleNewThread";
|
||||
|
||||
import { useThreadActions } from "../hooks/useThreadActions";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { toastManager } from "./ui/toast";
|
||||
@@ -116,6 +117,7 @@ import {
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
useThreadJumpHintVisibility,
|
||||
} from "./Sidebar.logic";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
@@ -151,6 +153,44 @@ interface PrStatusIndicator {
|
||||
|
||||
type ThreadPr = GitStatusResult["pr"];
|
||||
|
||||
function ThreadStatusLabel({
|
||||
status,
|
||||
compact = false,
|
||||
}: {
|
||||
status: NonNullable<ReturnType<typeof resolveThreadStatusPill>>;
|
||||
compact?: boolean;
|
||||
}) {
|
||||
if (compact) {
|
||||
return (
|
||||
<span
|
||||
title={status.label}
|
||||
className={`inline-flex size-3.5 shrink-0 items-center justify-center ${status.colorClass}`}
|
||||
>
|
||||
<span
|
||||
className={`size-[9px] rounded-full ${status.dotClass} ${
|
||||
status.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="sr-only">{status.label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span
|
||||
title={status.label}
|
||||
className={`inline-flex items-center gap-1 text-[10px] ${status.colorClass}`}
|
||||
>
|
||||
<span
|
||||
className={`h-1.5 w-1.5 rounded-full ${status.dotClass} ${
|
||||
status.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="hidden md:inline">{status.label}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function terminalStatusFromRunningIds(
|
||||
runningTerminalIds: string[],
|
||||
): TerminalStatusIndicator | null {
|
||||
@@ -356,14 +396,14 @@ export default function Sidebar() {
|
||||
const addProjectInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const [renamingThreadId, setRenamingThreadId] = useState<ThreadId | null>(null);
|
||||
const [renamingTitle, setRenamingTitle] = useState("");
|
||||
const [hoveredThreadId, setHoveredThreadId] = useState<ThreadId | null>(null);
|
||||
const [confirmingArchiveThreadId, setConfirmingArchiveThreadId] = useState<ThreadId | null>(null);
|
||||
const [expandedThreadListsByProject, setExpandedThreadListsByProject] = useState<
|
||||
ReadonlySet<ProjectId>
|
||||
>(() => new Set());
|
||||
const [showThreadJumpHints, setShowThreadJumpHints] = useState(false);
|
||||
const { showThreadJumpHints, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility();
|
||||
const renamingCommittedRef = useRef(false);
|
||||
const renamingInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const confirmArchiveButtonRefs = useRef(new Map<ThreadId, HTMLButtonElement>());
|
||||
const dragInProgressRef = useRef(false);
|
||||
const suppressProjectClickAfterDragRef = useRef(false);
|
||||
const suppressProjectClickForContextMenuRef = useRef(false);
|
||||
@@ -1023,14 +1063,18 @@ export default function Sidebar() {
|
||||
visibleThreads.filter((thread) => thread.projectId === project.id),
|
||||
appSettings.sidebarThreadSortOrder,
|
||||
);
|
||||
const projectStatus = resolveProjectStatusIndicator(
|
||||
projectThreads.map((thread) =>
|
||||
const threadStatuses = new Map(
|
||||
projectThreads.map((thread) => [
|
||||
thread.id,
|
||||
resolveThreadStatusPill({
|
||||
thread,
|
||||
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
|
||||
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
|
||||
}),
|
||||
),
|
||||
]),
|
||||
);
|
||||
const projectStatus = resolveProjectStatusIndicator(
|
||||
projectThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
|
||||
);
|
||||
const activeThreadId = routeThreadId ?? undefined;
|
||||
const isThreadListExpanded = expandedThreadListsByProject.has(project.id);
|
||||
@@ -1039,25 +1083,35 @@ export default function Sidebar() {
|
||||
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
|
||||
: null;
|
||||
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
|
||||
const { hasHiddenThreads, visibleThreads: visibleProjectThreads } =
|
||||
getVisibleThreadsForProject({
|
||||
threads: projectThreads,
|
||||
activeThreadId,
|
||||
isThreadListExpanded,
|
||||
previewLimit: THREAD_PREVIEW_LIMIT,
|
||||
});
|
||||
const {
|
||||
hasHiddenThreads,
|
||||
hiddenThreads,
|
||||
visibleThreads: visibleProjectThreads,
|
||||
} = getVisibleThreadsForProject({
|
||||
threads: projectThreads,
|
||||
activeThreadId,
|
||||
isThreadListExpanded,
|
||||
previewLimit: THREAD_PREVIEW_LIMIT,
|
||||
});
|
||||
const hiddenThreadStatus = resolveProjectStatusIndicator(
|
||||
hiddenThreads.map((thread) => threadStatuses.get(thread.id) ?? null),
|
||||
);
|
||||
const orderedProjectThreadIds = projectThreads.map((thread) => thread.id);
|
||||
const renderedThreads = pinnedCollapsedThread
|
||||
? [pinnedCollapsedThread]
|
||||
: visibleProjectThreads;
|
||||
const showEmptyThreadState = project.expanded && projectThreads.length === 0;
|
||||
|
||||
return {
|
||||
hasHiddenThreads,
|
||||
hiddenThreadStatus,
|
||||
orderedProjectThreadIds,
|
||||
project,
|
||||
projectStatus,
|
||||
projectThreads,
|
||||
threadStatuses,
|
||||
renderedThreads,
|
||||
showEmptyThreadState,
|
||||
shouldShowThreadPanel,
|
||||
isThreadListExpanded,
|
||||
};
|
||||
@@ -1070,23 +1124,22 @@ export default function Sidebar() {
|
||||
visibleThreads,
|
||||
],
|
||||
);
|
||||
const visibleSidebarThreadIds = useMemo(
|
||||
() => getVisibleSidebarThreadIds(renderedProjects),
|
||||
[renderedProjects],
|
||||
);
|
||||
const threadJumpCommandById = useMemo(() => {
|
||||
const mapping = new Map<ThreadId, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
|
||||
let visibleThreadIndex = 0;
|
||||
|
||||
for (const renderedProject of renderedProjects) {
|
||||
for (const thread of renderedProject.renderedThreads) {
|
||||
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
|
||||
if (!jumpCommand) {
|
||||
return mapping;
|
||||
}
|
||||
mapping.set(thread.id, jumpCommand);
|
||||
visibleThreadIndex += 1;
|
||||
for (const [visibleThreadIndex, threadId] of visibleSidebarThreadIds.entries()) {
|
||||
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
|
||||
if (!jumpCommand) {
|
||||
return mapping;
|
||||
}
|
||||
mapping.set(threadId, jumpCommand);
|
||||
}
|
||||
|
||||
return mapping;
|
||||
}, [renderedProjects]);
|
||||
}, [visibleSidebarThreadIds]);
|
||||
const threadJumpThreadIds = useMemo(
|
||||
() => [...threadJumpCommandById.keys()],
|
||||
[threadJumpCommandById],
|
||||
@@ -1101,10 +1154,7 @@ export default function Sidebar() {
|
||||
}
|
||||
return mapping;
|
||||
}, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]);
|
||||
const orderedSidebarThreadIds = useMemo(
|
||||
() => getVisibleSidebarThreadIds(renderedProjects),
|
||||
[renderedProjects],
|
||||
);
|
||||
const orderedSidebarThreadIds = visibleSidebarThreadIds;
|
||||
|
||||
useEffect(() => {
|
||||
const getShortcutContext = () => ({
|
||||
@@ -1113,7 +1163,7 @@ export default function Sidebar() {
|
||||
});
|
||||
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
setShowThreadJumpHints(
|
||||
updateThreadJumpHintsVisibility(
|
||||
shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: getShortcutContext(),
|
||||
@@ -1161,7 +1211,7 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const onWindowKeyUp = (event: KeyboardEvent) => {
|
||||
setShowThreadJumpHints(
|
||||
updateThreadJumpHintsVisibility(
|
||||
shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: getShortcutContext(),
|
||||
@@ -1170,7 +1220,7 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const onWindowBlur = () => {
|
||||
setShowThreadJumpHints(false);
|
||||
updateThreadJumpHintsVisibility(false);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
@@ -1190,6 +1240,7 @@ export default function Sidebar() {
|
||||
routeTerminalOpen,
|
||||
routeThreadId,
|
||||
threadJumpThreadIds,
|
||||
updateThreadJumpHintsVisibility,
|
||||
]);
|
||||
|
||||
function renderProjectItem(
|
||||
@@ -1198,11 +1249,14 @@ export default function Sidebar() {
|
||||
) {
|
||||
const {
|
||||
hasHiddenThreads,
|
||||
hiddenThreadStatus,
|
||||
orderedProjectThreadIds,
|
||||
project,
|
||||
projectStatus,
|
||||
projectThreads,
|
||||
threadStatuses,
|
||||
renderedThreads,
|
||||
showEmptyThreadState,
|
||||
shouldShowThreadPanel,
|
||||
isThreadListExpanded,
|
||||
} = renderedProject;
|
||||
@@ -1213,37 +1267,45 @@ export default function Sidebar() {
|
||||
const jumpLabel = threadJumpLabelById.get(thread.id) ?? null;
|
||||
const isThreadRunning =
|
||||
thread.session?.status === "running" && thread.session.activeTurnId != null;
|
||||
const threadStatus = resolveThreadStatusPill({
|
||||
thread,
|
||||
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
|
||||
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
|
||||
});
|
||||
const threadStatus = threadStatuses.get(thread.id) ?? null;
|
||||
const prStatus = prStatusIndicator(prByThreadId.get(thread.id) ?? null);
|
||||
const terminalStatus = terminalStatusFromRunningIds(
|
||||
selectThreadTerminalState(terminalStateByThreadId, thread.id).runningTerminalIds,
|
||||
);
|
||||
const isConfirmingArchive = confirmingArchiveThreadId === thread.id && !isThreadRunning;
|
||||
const threadMetaClassName = isConfirmingArchive
|
||||
? "pointer-events-none opacity-0"
|
||||
: !isThreadRunning
|
||||
? "pointer-events-none transition-opacity duration-150 group-hover/menu-sub-item:opacity-0 group-focus-within/menu-sub-item:opacity-0"
|
||||
: "pointer-events-none";
|
||||
|
||||
return (
|
||||
<SidebarMenuSubItem
|
||||
key={thread.id}
|
||||
className="w-full"
|
||||
data-thread-item
|
||||
onMouseEnter={() => {
|
||||
setHoveredThreadId(thread.id);
|
||||
}}
|
||||
onMouseLeave={() => {
|
||||
setHoveredThreadId((current) => (current === thread.id ? null : current));
|
||||
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
|
||||
}}
|
||||
onBlurCapture={(event) => {
|
||||
const currentTarget = event.currentTarget;
|
||||
requestAnimationFrame(() => {
|
||||
if (currentTarget.contains(document.activeElement)) {
|
||||
return;
|
||||
}
|
||||
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SidebarMenuSubButton
|
||||
render={<div role="button" tabIndex={0} />}
|
||||
size="sm"
|
||||
isActive={isActive}
|
||||
data-testid={`thread-row-${thread.id}`}
|
||||
className={`${resolveThreadRowClassName({
|
||||
isActive,
|
||||
isSelected,
|
||||
})} relative`}
|
||||
})} relative isolate`}
|
||||
onClick={(event) => {
|
||||
handleThreadClick(event, thread.id, orderedProjectThreadIds);
|
||||
}}
|
||||
@@ -1254,7 +1316,6 @@ export default function Sidebar() {
|
||||
}}
|
||||
onContextMenu={(event) => {
|
||||
event.preventDefault();
|
||||
setHoveredThreadId((current) => (current === thread.id ? null : current));
|
||||
if (selectedThreadIds.size > 0 && selectedThreadIds.has(thread.id)) {
|
||||
void handleMultiSelectContextMenu({
|
||||
x: event.clientX,
|
||||
@@ -1291,18 +1352,7 @@ export default function Sidebar() {
|
||||
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
|
||||
</Tooltip>
|
||||
)}
|
||||
{threadStatus && (
|
||||
<span
|
||||
className={`inline-flex items-center gap-1 text-[10px] ${threadStatus.colorClass}`}
|
||||
>
|
||||
<span
|
||||
className={`h-1.5 w-1.5 rounded-full ${threadStatus.dotClass} ${
|
||||
threadStatus.pulse ? "animate-pulse" : ""
|
||||
}`}
|
||||
/>
|
||||
<span className="hidden md:inline">{threadStatus.label}</span>
|
||||
</span>
|
||||
)}
|
||||
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
|
||||
{renamingThreadId === thread.id ? (
|
||||
<input
|
||||
ref={(el) => {
|
||||
@@ -1352,10 +1402,18 @@ export default function Sidebar() {
|
||||
</span>
|
||||
)}
|
||||
<div className="flex min-w-12 justify-end">
|
||||
{confirmingArchiveThreadId === thread.id && !isThreadRunning ? (
|
||||
{isConfirmingArchive ? (
|
||||
<button
|
||||
ref={(element) => {
|
||||
if (element) {
|
||||
confirmArchiveButtonRefs.current.set(thread.id, element);
|
||||
} else {
|
||||
confirmArchiveButtonRefs.current.delete(thread.id);
|
||||
}
|
||||
}}
|
||||
type="button"
|
||||
data-thread-selection-safe
|
||||
data-testid={`thread-archive-confirm-${thread.id}`}
|
||||
aria-label={`Confirm archive ${thread.title}`}
|
||||
className="absolute top-1/2 right-1 inline-flex h-5 -translate-y-1/2 cursor-pointer items-center rounded-full bg-destructive/12 px-2 text-[10px] font-medium text-destructive transition-colors hover:bg-destructive/18 focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-destructive/40"
|
||||
onPointerDown={(event) => {
|
||||
@@ -1367,80 +1425,84 @@ export default function Sidebar() {
|
||||
setConfirmingArchiveThreadId((current) =>
|
||||
current === thread.id ? null : current,
|
||||
);
|
||||
setHoveredThreadId((current) => (current === thread.id ? null : current));
|
||||
void attemptArchiveThread(thread.id);
|
||||
}}
|
||||
>
|
||||
Confirm
|
||||
</button>
|
||||
) : hoveredThreadId === thread.id && !isThreadRunning ? (
|
||||
) : !isThreadRunning ? (
|
||||
appSettings.confirmThreadArchive ? (
|
||||
<button
|
||||
type="button"
|
||||
data-thread-selection-safe
|
||||
aria-label={`Archive ${thread.title}`}
|
||||
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setConfirmingArchiveThreadId(thread.id);
|
||||
}}
|
||||
>
|
||||
<ArchiveIcon className="size-3.5" />
|
||||
</button>
|
||||
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
|
||||
<button
|
||||
type="button"
|
||||
data-thread-selection-safe
|
||||
data-testid={`thread-archive-${thread.id}`}
|
||||
aria-label={`Archive ${thread.title}`}
|
||||
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setConfirmingArchiveThreadId(thread.id);
|
||||
requestAnimationFrame(() => {
|
||||
confirmArchiveButtonRefs.current.get(thread.id)?.focus();
|
||||
});
|
||||
}}
|
||||
>
|
||||
<ArchiveIcon className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
data-thread-selection-safe
|
||||
aria-label={`Archive ${thread.title}`}
|
||||
className="absolute top-1/2 right-1 inline-flex size-5 -translate-y-1/2 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
setHoveredThreadId((current) =>
|
||||
current === thread.id ? null : current,
|
||||
);
|
||||
void attemptArchiveThread(thread.id);
|
||||
}}
|
||||
>
|
||||
<ArchiveIcon className="size-3.5" />
|
||||
</button>
|
||||
<div className="pointer-events-none absolute top-1/2 right-1 -translate-y-1/2 opacity-0 transition-opacity duration-150 group-hover/menu-sub-item:pointer-events-auto group-hover/menu-sub-item:opacity-100 group-focus-within/menu-sub-item:pointer-events-auto group-focus-within/menu-sub-item:opacity-100">
|
||||
<button
|
||||
type="button"
|
||||
data-thread-selection-safe
|
||||
data-testid={`thread-archive-${thread.id}`}
|
||||
aria-label={`Archive ${thread.title}`}
|
||||
className="inline-flex size-5 cursor-pointer items-center justify-center text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring"
|
||||
onPointerDown={(event) => {
|
||||
event.stopPropagation();
|
||||
}}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
void attemptArchiveThread(thread.id);
|
||||
}}
|
||||
>
|
||||
<ArchiveIcon className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<TooltipPopup side="top">Archive</TooltipPopup>
|
||||
</Tooltip>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{showThreadJumpHints && jumpLabel ? (
|
||||
<span
|
||||
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
|
||||
title={jumpLabel}
|
||||
>
|
||||
{jumpLabel}
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className={`text-[10px] ${
|
||||
isHighlighted
|
||||
? "text-foreground/72 dark:text-foreground/82"
|
||||
: "text-muted-foreground/40"
|
||||
}`}
|
||||
>
|
||||
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
) : null}
|
||||
<span className={threadMetaClassName}>
|
||||
{showThreadJumpHints && jumpLabel ? (
|
||||
<span
|
||||
className="inline-flex h-5 items-center rounded-full border border-border/80 bg-background/90 px-1.5 font-mono text-[10px] font-medium tracking-tight text-foreground shadow-sm"
|
||||
title={jumpLabel}
|
||||
>
|
||||
{jumpLabel}
|
||||
</span>
|
||||
) : (
|
||||
<span
|
||||
className={`text-[10px] ${
|
||||
isHighlighted
|
||||
? "text-foreground/72 dark:text-foreground/82"
|
||||
: "text-muted-foreground/40"
|
||||
}`}
|
||||
>
|
||||
{formatRelativeTimeLabel(thread.updatedAt ?? thread.createdAt)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</SidebarMenuSubButton>
|
||||
@@ -1535,6 +1597,16 @@ export default function Sidebar() {
|
||||
ref={attachThreadListAutoAnimateRef}
|
||||
className="mx-1 my-0 w-full translate-x-0 gap-0.5 overflow-hidden px-1.5 py-0"
|
||||
>
|
||||
{shouldShowThreadPanel && showEmptyThreadState ? (
|
||||
<SidebarMenuSubItem className="w-full" data-thread-selection-safe>
|
||||
<div
|
||||
data-thread-selection-safe
|
||||
className="flex h-6 w-full translate-x-0 items-center px-2 text-left text-[10px] text-muted-foreground/60"
|
||||
>
|
||||
<span>No threads yet</span>
|
||||
</div>
|
||||
</SidebarMenuSubItem>
|
||||
) : null}
|
||||
{shouldShowThreadPanel && renderedThreads.map((thread) => renderThreadRow(thread))}
|
||||
|
||||
{project.expanded && hasHiddenThreads && !isThreadListExpanded && (
|
||||
@@ -1548,7 +1620,10 @@ export default function Sidebar() {
|
||||
expandThreadListForProject(project.id);
|
||||
}}
|
||||
>
|
||||
<span>Show more</span>
|
||||
<span className="flex min-w-0 flex-1 items-center gap-2">
|
||||
{hiddenThreadStatus && <ThreadStatusLabel status={hiddenThreadStatus} compact />}
|
||||
<span>Show more</span>
|
||||
</span>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
)}
|
||||
|
||||
@@ -50,6 +50,7 @@ export const ChangedFilesTree = memo(function ChangedFilesTree(props: {
|
||||
<div key={`dir:${node.path}`}>
|
||||
<button
|
||||
type="button"
|
||||
data-scroll-anchor-ignore
|
||||
className="group flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left hover:bg-background/80"
|
||||
style={{ paddingLeft: `${leftPadding}px` }}
|
||||
onClick={() => toggleDirectory(node.path, depth === 0)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { type ProjectEntry, type ProviderKind } from "@t3tools/contracts";
|
||||
import { memo } from "react";
|
||||
import { memo, useLayoutEffect, useRef } from "react";
|
||||
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
|
||||
import { BotIcon } from "lucide-react";
|
||||
import { cn } from "~/lib/utils";
|
||||
@@ -41,8 +41,19 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
onHighlightedItemChange: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!props.activeItemId || !listRef.current) return;
|
||||
const el = listRef.current.querySelector<HTMLElement>(
|
||||
`[data-composer-item-id="${CSS.escape(props.activeItemId)}"]`,
|
||||
);
|
||||
el?.scrollIntoView({ block: "nearest" });
|
||||
}, [props.activeItemId]);
|
||||
|
||||
return (
|
||||
<Command
|
||||
autoHighlight={false}
|
||||
mode="none"
|
||||
onItemHighlighted={(highlightedValue) => {
|
||||
props.onHighlightedItemChange(
|
||||
@@ -50,7 +61,10 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
);
|
||||
}}
|
||||
>
|
||||
<div className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs">
|
||||
<div
|
||||
ref={listRef}
|
||||
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
|
||||
>
|
||||
<CommandList className="max-h-64">
|
||||
{props.items.map((item) => (
|
||||
<ComposerCommandMenuItem
|
||||
@@ -58,6 +72,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
|
||||
item={item}
|
||||
resolvedTheme={props.resolvedTheme}
|
||||
isActive={props.activeItemId === item.id}
|
||||
onHighlight={props.onHighlightedItemChange}
|
||||
onSelect={props.onSelect}
|
||||
/>
|
||||
))}
|
||||
@@ -80,15 +95,20 @@ const ComposerCommandMenuItem = memo(function ComposerCommandMenuItem(props: {
|
||||
item: ComposerCommandItem;
|
||||
resolvedTheme: "light" | "dark";
|
||||
isActive: boolean;
|
||||
onHighlight: (itemId: string | null) => void;
|
||||
onSelect: (item: ComposerCommandItem) => void;
|
||||
}) {
|
||||
return (
|
||||
<CommandItem
|
||||
value={props.item.id}
|
||||
data-composer-item-id={props.item.id}
|
||||
className={cn(
|
||||
"cursor-pointer select-none gap-2",
|
||||
props.isActive && "bg-accent text-accent-foreground",
|
||||
"cursor-pointer select-none gap-2 hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit",
|
||||
props.isActive && "bg-accent! text-accent-foreground!",
|
||||
)}
|
||||
onMouseMove={() => {
|
||||
if (!props.isActive) props.onHighlight(props.item.id);
|
||||
}}
|
||||
onMouseDown={(event) => {
|
||||
event.preventDefault();
|
||||
}}
|
||||
|
||||
@@ -264,9 +264,14 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
rowVirtualizer.measure();
|
||||
}, [rowVirtualizer, timelineWidthPx]);
|
||||
useEffect(() => {
|
||||
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (_item, _delta, instance) => {
|
||||
rowVirtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
|
||||
const viewportHeight = instance.scrollRect?.height ?? 0;
|
||||
const scrollOffset = instance.scrollOffset ?? 0;
|
||||
const itemIntersectsViewport =
|
||||
item.end > scrollOffset && item.start < scrollOffset + viewportHeight;
|
||||
if (itemIntersectsViewport) {
|
||||
return false;
|
||||
}
|
||||
const remainingDistance = instance.getTotalSize() - (scrollOffset + viewportHeight);
|
||||
return remainingDistance > AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
|
||||
};
|
||||
@@ -483,6 +488,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
type="button"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
data-scroll-anchor-ignore
|
||||
onClick={() => onToggleAllDirectories(turnSummary.turnId)}
|
||||
>
|
||||
{allDirectoriesExpanded ? "Collapse all" : "Expand all"}
|
||||
@@ -543,9 +549,10 @@ export const MessagesTimeline = memo(function MessagesTimeline({
|
||||
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-pulse [animation-delay:400ms]" />
|
||||
</span>
|
||||
<span>
|
||||
{row.createdAt
|
||||
? `Working for ${formatWorkingTimer(row.createdAt, nowIso) ?? "0s"}`
|
||||
: "Working..."}
|
||||
{(() => {
|
||||
const elapsed = row.createdAt ? formatWorkingTimer(row.createdAt, nowIso) : null;
|
||||
return elapsed ? `Working for ${elapsed}` : "Working...";
|
||||
})()}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -637,6 +644,9 @@ function formatWorkingTimer(startIso: string, endIso: string): string | null {
|
||||
}
|
||||
|
||||
const elapsedSeconds = Math.max(0, Math.floor((endedAtMs - startedAtMs) / 1000));
|
||||
if (elapsedSeconds < 1) {
|
||||
return null;
|
||||
}
|
||||
if (elapsedSeconds < 60) {
|
||||
return `${elapsedSeconds}s`;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: new Date().toISOString(),
|
||||
models: [
|
||||
{
|
||||
@@ -57,7 +57,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
installed: true,
|
||||
version: "1.0.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: new Date().toISOString(),
|
||||
models: [
|
||||
{
|
||||
@@ -110,6 +110,19 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
},
|
||||
];
|
||||
|
||||
function buildCodexProvider(models: ServerProvider["models"]): ServerProvider {
|
||||
return {
|
||||
provider: "codex",
|
||||
enabled: true,
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: new Date().toISOString(),
|
||||
models,
|
||||
};
|
||||
}
|
||||
|
||||
async function mountPicker(props: {
|
||||
provider: ProviderKind;
|
||||
model: string;
|
||||
@@ -241,6 +254,93 @@ describe("ProviderModelPicker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("only shows codex spark when the server reports it for the account", async () => {
|
||||
const providersWithoutSpark: ReadonlyArray<ServerProvider> = [
|
||||
buildCodexProvider([
|
||||
{
|
||||
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: [],
|
||||
},
|
||||
},
|
||||
]),
|
||||
TEST_PROVIDERS[1]!,
|
||||
];
|
||||
const providersWithSpark: ReadonlyArray<ServerProvider> = [
|
||||
buildCodexProvider([
|
||||
{
|
||||
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: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
slug: "gpt-5.3-codex-spark",
|
||||
name: "GPT-5.3 Codex Spark",
|
||||
isCustom: false,
|
||||
capabilities: {
|
||||
reasoningEffortLevels: [effort("low"), effort("medium", true), effort("high")],
|
||||
supportsFastMode: true,
|
||||
supportsThinkingToggle: false,
|
||||
contextWindowOptions: [],
|
||||
promptInjectedEffortLevels: [],
|
||||
},
|
||||
},
|
||||
]),
|
||||
TEST_PROVIDERS[1]!,
|
||||
];
|
||||
|
||||
const hidden = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: null,
|
||||
providers: providersWithoutSpark,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitem", { name: "Codex" }).hover();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const text = document.body.textContent ?? "";
|
||||
expect(text).toContain("GPT-5.3 Codex");
|
||||
expect(text).not.toContain("GPT-5.3 Codex Spark");
|
||||
});
|
||||
} finally {
|
||||
await hidden.cleanup();
|
||||
}
|
||||
|
||||
const visible = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
lockedProvider: null,
|
||||
providers: providersWithSpark,
|
||||
});
|
||||
|
||||
try {
|
||||
await page.getByRole("button").click();
|
||||
await page.getByRole("menuitem", { name: "Codex" }).hover();
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(document.body.textContent ?? "").toContain("GPT-5.3 Codex Spark");
|
||||
});
|
||||
} finally {
|
||||
await visible.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("dispatches the canonical slug when a model is selected", async () => {
|
||||
const mounted = await mountPicker({
|
||||
provider: "claudeAgent",
|
||||
|
||||
@@ -35,7 +35,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
installed: true,
|
||||
version: "0.1.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [
|
||||
{
|
||||
@@ -61,7 +61,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
|
||||
installed: true,
|
||||
version: "0.1.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [
|
||||
{
|
||||
|
||||
@@ -71,6 +71,41 @@ const CLAUDE_MODELS: ReadonlyArray<ServerProviderModel> = [
|
||||
},
|
||||
];
|
||||
|
||||
const CLAUDE_MODELS_WITH_CONTEXT_WINDOW: 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: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
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({
|
||||
@@ -156,6 +191,7 @@ describe("getComposerProviderState", () => {
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -268,7 +304,116 @@ describe("getComposerProviderState", () => {
|
||||
promptEffort: "high",
|
||||
modelOptionsForDispatch: {
|
||||
effort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves explicit fastMode: false so deepMerge can overwrite a prior true", () => {
|
||||
// Regression: normalizeClaudeModelOptionsWithCapabilities used to strip
|
||||
// fastMode: false, which meant deepMerge could never clear a previous true.
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
fastMode: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state.modelOptionsForDispatch).toHaveProperty("fastMode", false);
|
||||
});
|
||||
|
||||
it("preserves explicit thinking: true so deepMerge can overwrite a prior false", () => {
|
||||
// Regression: thinking: true (the default) used to be stripped, which
|
||||
// meant deepMerge could never clear a previous thinking: false.
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
thinking: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state.modelOptionsForDispatch).toHaveProperty("thinking", true);
|
||||
});
|
||||
|
||||
it("preserves Claude default context window explicitly in dispatch options", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
contextWindow: "200k",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state.modelOptionsForDispatch).toMatchObject({
|
||||
effort: "high",
|
||||
contextWindow: "200k",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves explicit contextWindow default so deepMerge can overwrite a prior 1m", () => {
|
||||
// Regression: the default contextWindow must survive normalization so
|
||||
// deepMerge can clear an older non-default 1m selection.
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-opus-4-6",
|
||||
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
contextWindow: "200k",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state.modelOptionsForDispatch).toHaveProperty("contextWindow", "200k");
|
||||
});
|
||||
|
||||
it("omits contextWindow when the model does not support it", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-haiku-4-5",
|
||||
models: CLAUDE_MODELS_WITH_CONTEXT_WINDOW,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
contextWindow: "1m",
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state.modelOptionsForDispatch).toBeUndefined();
|
||||
});
|
||||
|
||||
it("omits fastMode when the model does not support it", () => {
|
||||
const state = getComposerProviderState({
|
||||
provider: "claudeAgent",
|
||||
model: "claude-sonnet-4-6",
|
||||
models: CLAUDE_MODELS,
|
||||
prompt: "",
|
||||
modelOptions: {
|
||||
claudeAgent: {
|
||||
effort: "high",
|
||||
fastMode: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(state.modelOptionsForDispatch).not.toHaveProperty("fastMode");
|
||||
});
|
||||
});
|
||||
@@ -6,12 +6,12 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { isClaudeUltrathinkPrompt, resolveEffort } from "@t3tools/shared/model";
|
||||
import type { ReactNode } from "react";
|
||||
import { getProviderModelCapabilities } from "../../providerModels";
|
||||
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
|
||||
import {
|
||||
getProviderModelCapabilities,
|
||||
normalizeClaudeModelOptionsWithCapabilities,
|
||||
normalizeCodexModelOptionsWithCapabilities,
|
||||
} from "../../providerModels";
|
||||
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
|
||||
} from "@t3tools/shared/model";
|
||||
|
||||
export type ComposerProviderStateInput = {
|
||||
provider: ProviderKind;
|
||||
|
||||
@@ -146,13 +146,14 @@ function getProviderSummary(provider: ServerProvider | undefined) {
|
||||
detail: provider.message ?? "CLI not detected on PATH.",
|
||||
};
|
||||
}
|
||||
if (provider.authStatus === "authenticated") {
|
||||
if (provider.auth.status === "authenticated") {
|
||||
const authLabel = provider.auth.label ?? provider.auth.type;
|
||||
return {
|
||||
headline: "Authenticated",
|
||||
headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",
|
||||
detail: provider.message ?? null,
|
||||
};
|
||||
}
|
||||
if (provider.authStatus === "unauthenticated") {
|
||||
if (provider.auth.status === "unauthenticated") {
|
||||
return {
|
||||
headline: "Not authenticated",
|
||||
detail: provider.message ?? null,
|
||||
|
||||
@@ -125,7 +125,7 @@ function AutocompleteItem({ className, children, ...props }: AutocompletePrimiti
|
||||
return (
|
||||
<AutocompletePrimitive.Item
|
||||
className={cn(
|
||||
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
|
||||
"flex min-h-8 cursor-default select-none items-center rounded-sm px-2 py-1 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm",
|
||||
className,
|
||||
)}
|
||||
data-slot="autocomplete-item"
|
||||
|
||||
@@ -195,7 +195,7 @@ function ComboboxItem({
|
||||
return (
|
||||
<ComboboxPrimitive.Item
|
||||
className={cn(
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none data-disabled:pointer-events-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
"grid min-h-8 in-data-[side=none]:min-w-[calc(var(--anchor-width)+1.25rem)] cursor-default grid-cols-[1rem_1fr] items-center gap-2 rounded-sm py-1 ps-2 pe-4 text-base outline-none hover:bg-accent data-disabled:pointer-events-none data-selected:bg-accent/50 data-selected:text-foreground data-highlighted:bg-accent data-highlighted:text-accent-foreground [&[data-highlighted][data-selected]]:bg-accent [&[data-highlighted][data-selected]]:text-accent-foreground data-disabled:opacity-64 sm:min-h-7 sm:text-sm [&_svg:not([class*='size-'])]:size-4.5 sm:[&_svg:not([class*='size-'])]:size-4 [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
className,
|
||||
)}
|
||||
data-slot="combobox-item"
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
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";
|
||||
import { normalizeModelSlug } from "@t3tools/shared/model";
|
||||
|
||||
const EMPTY_CAPABILITIES: ModelCapabilities = {
|
||||
reasoningEffortLevels: [],
|
||||
@@ -69,36 +67,3 @@ export function getDefaultServerModel(
|
||||
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;
|
||||
}
|
||||
+158
-1
@@ -7,7 +7,16 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
|
||||
import {
|
||||
beginThreadSend,
|
||||
clearThreadSend,
|
||||
markThreadUnread,
|
||||
markThreadSendSettled,
|
||||
reorderProjects,
|
||||
setThreadSendPhase,
|
||||
syncServerReadModel,
|
||||
type AppState,
|
||||
} from "./store";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
@@ -39,6 +48,7 @@ function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
|
||||
function makeState(thread: Thread): AppState {
|
||||
return {
|
||||
pendingThreadSendById: {},
|
||||
projects: [
|
||||
{
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
@@ -171,6 +181,7 @@ describe("store pure functions", () => {
|
||||
const project2 = ProjectId.makeUnsafe("project-2");
|
||||
const project3 = ProjectId.makeUnsafe("project-3");
|
||||
const state: AppState = {
|
||||
pendingThreadSendById: {},
|
||||
projects: [
|
||||
{
|
||||
id: project1,
|
||||
@@ -292,6 +303,7 @@ describe("store read model sync", () => {
|
||||
const project2 = ProjectId.makeUnsafe("project-2");
|
||||
const project3 = ProjectId.makeUnsafe("project-3");
|
||||
const initialState: AppState = {
|
||||
pendingThreadSendById: {},
|
||||
projects: [
|
||||
{
|
||||
id: project2,
|
||||
@@ -346,4 +358,149 @@ describe("store read model sync", () => {
|
||||
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
|
||||
});
|
||||
|
||||
it("keeps pending sends until the server catches up to the send", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const initialState = beginThreadSend(
|
||||
makeState(makeThread()),
|
||||
threadId,
|
||||
"sending-turn",
|
||||
"2026-02-27T00:01:00.000Z",
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(
|
||||
initialState,
|
||||
makeReadModel(
|
||||
makeReadModelThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-27T00:00:59.000Z",
|
||||
startedAt: "2026-02-27T00:01:01.000Z",
|
||||
completedAt: "2026-02-27T00:01:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.pendingThreadSendById[threadId]).toEqual({
|
||||
phase: "sending-turn",
|
||||
startedAt: "2026-02-27T00:01:00.000Z",
|
||||
requestSettled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("does not clear pending sends when the turn appears before the request settles", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const initialState = beginThreadSend(
|
||||
makeState(makeThread()),
|
||||
threadId,
|
||||
"sending-turn",
|
||||
"2026-02-27T00:01:00.000Z",
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(
|
||||
initialState,
|
||||
makeReadModel(
|
||||
makeReadModelThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-27T00:01:01.000Z",
|
||||
startedAt: "2026-02-27T00:01:02.000Z",
|
||||
completedAt: "2026-02-27T00:01:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.pendingThreadSendById[threadId]).toEqual({
|
||||
phase: "sending-turn",
|
||||
startedAt: "2026-02-27T00:01:00.000Z",
|
||||
requestSettled: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("clears pending sends once the server session starts running", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const initialState = beginThreadSend(
|
||||
makeState(makeThread()),
|
||||
threadId,
|
||||
"sending-turn",
|
||||
"2026-02-27T00:01:00.000Z",
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(
|
||||
initialState,
|
||||
makeReadModel(
|
||||
makeReadModelThread({
|
||||
session: {
|
||||
threadId,
|
||||
status: "running",
|
||||
providerName: "codex",
|
||||
runtimeMode: "full-access",
|
||||
activeTurnId: TurnId.makeUnsafe("turn-1"),
|
||||
lastError: null,
|
||||
updatedAt: "2026-02-27T00:01:02.000Z",
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.pendingThreadSendById[threadId]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("clears settled pending sends once the turn has caught up", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const initialState = markThreadSendSettled(
|
||||
beginThreadSend(
|
||||
makeState(makeThread()),
|
||||
threadId,
|
||||
"sending-turn",
|
||||
"2026-02-27T00:01:00.000Z",
|
||||
),
|
||||
threadId,
|
||||
);
|
||||
|
||||
const next = syncServerReadModel(
|
||||
initialState,
|
||||
makeReadModel(
|
||||
makeReadModelThread({
|
||||
latestTurn: {
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
state: "completed",
|
||||
requestedAt: "2026-02-27T00:01:01.000Z",
|
||||
startedAt: "2026-02-27T00:01:02.000Z",
|
||||
completedAt: "2026-02-27T00:01:03.000Z",
|
||||
assistantMessageId: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
expect(next.pendingThreadSendById[threadId]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("store pending thread send helpers", () => {
|
||||
it("updates and clears pending thread send state", () => {
|
||||
const threadId = ThreadId.makeUnsafe("thread-1");
|
||||
const startedState = beginThreadSend(
|
||||
makeState(makeThread()),
|
||||
threadId,
|
||||
"preparing-worktree",
|
||||
"2026-02-27T00:01:00.000Z",
|
||||
);
|
||||
const sendingState = setThreadSendPhase(startedState, threadId, "sending-turn");
|
||||
const settledState = markThreadSendSettled(sendingState, threadId);
|
||||
const clearedState = clearThreadSend(settledState, threadId);
|
||||
|
||||
expect(startedState.pendingThreadSendById[threadId]?.phase).toBe("preparing-worktree");
|
||||
expect(startedState.pendingThreadSendById[threadId]?.requestSettled).toBe(false);
|
||||
expect(sendingState.pendingThreadSendById[threadId]?.phase).toBe("sending-turn");
|
||||
expect(settledState.pendingThreadSendById[threadId]?.requestSettled).toBe(true);
|
||||
expect(clearedState.pendingThreadSendById[threadId]).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+196
-1
@@ -7,12 +7,19 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { resolveModelSlugForProvider } from "@t3tools/shared/model";
|
||||
import { create } from "zustand";
|
||||
import { type ChatMessage, type Project, type Thread } from "./types";
|
||||
import {
|
||||
type ChatMessage,
|
||||
type PendingThreadSend,
|
||||
type PendingThreadSendPhase,
|
||||
type Project,
|
||||
type Thread,
|
||||
} from "./types";
|
||||
import { Debouncer } from "@tanstack/react-pacer";
|
||||
|
||||
// ── State ────────────────────────────────────────────────────────────
|
||||
|
||||
export interface AppState {
|
||||
pendingThreadSendById: Record<ThreadId, PendingThreadSend | undefined>;
|
||||
projects: Project[];
|
||||
threads: Thread[];
|
||||
threadsHydrated: boolean;
|
||||
@@ -32,6 +39,7 @@ const LEGACY_PERSISTED_STATE_KEYS = [
|
||||
] as const;
|
||||
|
||||
const initialState: AppState = {
|
||||
pendingThreadSendById: {},
|
||||
projects: [],
|
||||
threads: [],
|
||||
threadsHydrated: false,
|
||||
@@ -111,6 +119,71 @@ function updateThread(
|
||||
return changed ? next : threads;
|
||||
}
|
||||
|
||||
function hasLatestTurnCaughtUpToPendingSend(
|
||||
latestTurnRequestedAt: string | null,
|
||||
pendingSendStartedAt: string,
|
||||
): boolean {
|
||||
if (latestTurnRequestedAt === null) {
|
||||
return false;
|
||||
}
|
||||
const latestTurnRequestedAtMs = Date.parse(latestTurnRequestedAt);
|
||||
const pendingSendStartedAtMs = Date.parse(pendingSendStartedAt);
|
||||
if (Number.isNaN(latestTurnRequestedAtMs) || Number.isNaN(pendingSendStartedAtMs)) {
|
||||
return false;
|
||||
}
|
||||
return latestTurnRequestedAtMs >= pendingSendStartedAtMs;
|
||||
}
|
||||
|
||||
function reconcilePendingThreadSends(
|
||||
pendingThreadSendById: AppState["pendingThreadSendById"],
|
||||
readModel: OrchestrationReadModel,
|
||||
): AppState["pendingThreadSendById"] {
|
||||
const readModelThreadById = new Map(
|
||||
readModel.threads.map((thread) => [thread.id, thread] as const),
|
||||
);
|
||||
let changed = false;
|
||||
const nextPendingThreadSendById: AppState["pendingThreadSendById"] = {};
|
||||
|
||||
for (const [threadId, pendingSend] of Object.entries(pendingThreadSendById) as Array<
|
||||
[ThreadId, PendingThreadSend | undefined]
|
||||
>) {
|
||||
if (!pendingSend) {
|
||||
continue;
|
||||
}
|
||||
const thread = readModelThreadById.get(threadId);
|
||||
if (!thread) {
|
||||
nextPendingThreadSendById[threadId] = pendingSend;
|
||||
continue;
|
||||
}
|
||||
|
||||
const authoritativeSendStarted = thread.session?.status === "running";
|
||||
const authoritativeSendFailed = thread.session?.lastError != null;
|
||||
const latestTurnCaughtUp = hasLatestTurnCaughtUpToPendingSend(
|
||||
thread.latestTurn?.requestedAt ?? null,
|
||||
pendingSend.startedAt,
|
||||
);
|
||||
|
||||
if (
|
||||
authoritativeSendStarted ||
|
||||
authoritativeSendFailed ||
|
||||
(pendingSend.requestSettled && latestTurnCaughtUp)
|
||||
) {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
nextPendingThreadSendById[threadId] = pendingSend;
|
||||
}
|
||||
|
||||
if (
|
||||
!changed &&
|
||||
Object.keys(nextPendingThreadSendById).length === Object.keys(pendingThreadSendById).length
|
||||
) {
|
||||
return pendingThreadSendById;
|
||||
}
|
||||
return nextPendingThreadSendById;
|
||||
}
|
||||
|
||||
function mapProjectsFromReadModel(
|
||||
incoming: OrchestrationReadModel["projects"],
|
||||
previous: Project[],
|
||||
@@ -319,12 +392,121 @@ export function syncServerReadModel(state: AppState, readModel: OrchestrationRea
|
||||
});
|
||||
return {
|
||||
...state,
|
||||
pendingThreadSendById: reconcilePendingThreadSends(state.pendingThreadSendById, readModel),
|
||||
projects,
|
||||
threads,
|
||||
threadsHydrated: true,
|
||||
};
|
||||
}
|
||||
|
||||
export function beginThreadSend(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
phase: PendingThreadSendPhase,
|
||||
startedAt: string,
|
||||
): AppState {
|
||||
const existing = state.pendingThreadSendById[threadId];
|
||||
if (
|
||||
existing?.phase === phase &&
|
||||
existing.startedAt === startedAt &&
|
||||
existing.requestSettled === false
|
||||
) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
pendingThreadSendById: {
|
||||
...state.pendingThreadSendById,
|
||||
[threadId]: { phase, startedAt, requestSettled: false },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function setThreadSendPhase(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
phase: PendingThreadSendPhase,
|
||||
): AppState {
|
||||
const existing = state.pendingThreadSendById[threadId];
|
||||
if (!existing || existing.phase === phase) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
pendingThreadSendById: {
|
||||
...state.pendingThreadSendById,
|
||||
[threadId]: {
|
||||
...existing,
|
||||
phase,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadSendSettled(state: AppState, threadId: ThreadId): AppState {
|
||||
const existing = state.pendingThreadSendById[threadId];
|
||||
if (!existing) {
|
||||
return state;
|
||||
}
|
||||
const thread = state.threads.find((candidate) => candidate.id === threadId) ?? null;
|
||||
const authoritativeSendStarted = thread?.session?.orchestrationStatus === "running";
|
||||
const authoritativeSendFailed = thread?.session?.lastError != null;
|
||||
const latestTurnCaughtUp = hasLatestTurnCaughtUpToPendingSend(
|
||||
thread?.latestTurn?.requestedAt ?? null,
|
||||
existing.startedAt,
|
||||
);
|
||||
|
||||
if (authoritativeSendStarted || authoritativeSendFailed || latestTurnCaughtUp) {
|
||||
return clearThreadSend(state, threadId);
|
||||
}
|
||||
if (existing.requestSettled) {
|
||||
return state;
|
||||
}
|
||||
return {
|
||||
...state,
|
||||
pendingThreadSendById: {
|
||||
...state.pendingThreadSendById,
|
||||
[threadId]: {
|
||||
...existing,
|
||||
requestSettled: true,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function clearThreadSend(state: AppState, threadId: ThreadId): AppState {
|
||||
if (!(threadId in state.pendingThreadSendById)) {
|
||||
return state;
|
||||
}
|
||||
const pendingThreadSendById = { ...state.pendingThreadSendById };
|
||||
delete pendingThreadSendById[threadId];
|
||||
return {
|
||||
...state,
|
||||
pendingThreadSendById,
|
||||
};
|
||||
}
|
||||
|
||||
export function moveThreadSend(
|
||||
state: AppState,
|
||||
fromThreadId: ThreadId,
|
||||
toThreadId: ThreadId,
|
||||
): AppState {
|
||||
if (fromThreadId === toThreadId) {
|
||||
return state;
|
||||
}
|
||||
const pendingSend = state.pendingThreadSendById[fromThreadId];
|
||||
if (!pendingSend) {
|
||||
return state;
|
||||
}
|
||||
const pendingThreadSendById = { ...state.pendingThreadSendById };
|
||||
delete pendingThreadSendById[fromThreadId];
|
||||
pendingThreadSendById[toThreadId] = pendingSend;
|
||||
return {
|
||||
...state,
|
||||
pendingThreadSendById,
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadVisited(
|
||||
state: AppState,
|
||||
threadId: ThreadId,
|
||||
@@ -425,6 +607,10 @@ export function setThreadBranch(
|
||||
// ── Zustand store ────────────────────────────────────────────────────
|
||||
|
||||
interface AppStore extends AppState {
|
||||
beginThreadSend: (threadId: ThreadId, phase: PendingThreadSendPhase, startedAt: string) => void;
|
||||
clearThreadSend: (threadId: ThreadId) => void;
|
||||
markThreadSendSettled: (threadId: ThreadId) => void;
|
||||
moveThreadSend: (fromThreadId: ThreadId, toThreadId: ThreadId) => void;
|
||||
syncServerReadModel: (readModel: OrchestrationReadModel) => void;
|
||||
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
|
||||
markThreadUnread: (threadId: ThreadId) => void;
|
||||
@@ -432,11 +618,18 @@ interface AppStore extends AppState {
|
||||
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
|
||||
reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void;
|
||||
setError: (threadId: ThreadId, error: string | null) => void;
|
||||
setThreadSendPhase: (threadId: ThreadId, phase: PendingThreadSendPhase) => void;
|
||||
setThreadBranch: (threadId: ThreadId, branch: string | null, worktreePath: string | null) => void;
|
||||
}
|
||||
|
||||
export const useStore = create<AppStore>((set) => ({
|
||||
...readPersistedState(),
|
||||
beginThreadSend: (threadId, phase, startedAt) =>
|
||||
set((state) => beginThreadSend(state, threadId, phase, startedAt)),
|
||||
clearThreadSend: (threadId) => set((state) => clearThreadSend(state, threadId)),
|
||||
markThreadSendSettled: (threadId) => set((state) => markThreadSendSettled(state, threadId)),
|
||||
moveThreadSend: (fromThreadId, toThreadId) =>
|
||||
set((state) => moveThreadSend(state, fromThreadId, toThreadId)),
|
||||
syncServerReadModel: (readModel) => set((state) => syncServerReadModel(state, readModel)),
|
||||
markThreadVisited: (threadId, visitedAt) =>
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
@@ -447,6 +640,8 @@ export const useStore = create<AppStore>((set) => ({
|
||||
reorderProjects: (draggedProjectId, targetProjectId) =>
|
||||
set((state) => reorderProjects(state, draggedProjectId, targetProjectId)),
|
||||
setError: (threadId, error) => set((state) => setError(state, threadId, error)),
|
||||
setThreadSendPhase: (threadId, phase) =>
|
||||
set((state) => setThreadSendPhase(state, threadId, phase)),
|
||||
setThreadBranch: (threadId, branch, worktreePath) =>
|
||||
set((state) => setThreadBranch(state, threadId, branch, worktreePath)),
|
||||
}));
|
||||
|
||||
@@ -16,6 +16,7 @@ import type {
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
export type SessionPhase = "disconnected" | "connecting" | "ready" | "running";
|
||||
export type PendingThreadSendPhase = "preparing-worktree" | "sending-turn";
|
||||
export const DEFAULT_RUNTIME_MODE: RuntimeMode = "full-access";
|
||||
|
||||
export const DEFAULT_INTERACTION_MODE: ProviderInteractionMode = "default";
|
||||
@@ -120,3 +121,9 @@ export interface ThreadSession {
|
||||
lastError?: string;
|
||||
orchestrationStatus: OrchestrationSessionStatus;
|
||||
}
|
||||
|
||||
export interface PendingThreadSend {
|
||||
phase: PendingThreadSendPhase;
|
||||
startedAt: string;
|
||||
requestSettled: boolean;
|
||||
}
|
||||
@@ -99,7 +99,7 @@ const defaultProviders: ReadonlyArray<ServerProvider> = [
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: "2026-01-01T00:00:00.000Z",
|
||||
models: [],
|
||||
},
|
||||
|
||||
@@ -35,6 +35,13 @@ export const ServerProviderAuthStatus = Schema.Literals([
|
||||
]);
|
||||
export type ServerProviderAuthStatus = typeof ServerProviderAuthStatus.Type;
|
||||
|
||||
export const ServerProviderAuth = Schema.Struct({
|
||||
status: ServerProviderAuthStatus,
|
||||
type: Schema.optional(TrimmedNonEmptyString),
|
||||
label: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
export type ServerProviderAuth = typeof ServerProviderAuth.Type;
|
||||
|
||||
export const ServerProviderModel = Schema.Struct({
|
||||
slug: TrimmedNonEmptyString,
|
||||
name: TrimmedNonEmptyString,
|
||||
@@ -49,7 +56,7 @@ export const ServerProvider = Schema.Struct({
|
||||
installed: Schema.Boolean,
|
||||
version: Schema.NullOr(TrimmedNonEmptyString),
|
||||
status: ServerProviderState,
|
||||
authStatus: ServerProviderAuthStatus,
|
||||
auth: ServerProviderAuth,
|
||||
checkedAt: IsoDateTime,
|
||||
message: Schema.optional(TrimmedNonEmptyString),
|
||||
models: Schema.Array(ServerProviderModel),
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DEFAULT_CLIENT_SETTINGS } from "./settings";
|
||||
|
||||
describe("DEFAULT_CLIENT_SETTINGS", () => {
|
||||
it("includes archive confirmation with a false default", () => {
|
||||
expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -112,6 +112,7 @@ const ClaudeModelOptionsPatch = Schema.Struct({
|
||||
thinking: Schema.optionalKey(ClaudeModelOptions.fields.thinking),
|
||||
effort: Schema.optionalKey(ClaudeModelOptions.fields.effort),
|
||||
fastMode: Schema.optionalKey(ClaudeModelOptions.fields.fastMode),
|
||||
contextWindow: Schema.optionalKey(ClaudeModelOptions.fields.contextWindow),
|
||||
});
|
||||
|
||||
const ModelSelectionPatch = Schema.Union([
|
||||
|
||||
@@ -8,6 +8,8 @@ import {
|
||||
hasContextWindowOption,
|
||||
hasEffortLevel,
|
||||
isClaudeUltrathinkPrompt,
|
||||
normalizeClaudeModelOptionsWithCapabilities,
|
||||
normalizeCodexModelOptionsWithCapabilities,
|
||||
normalizeModelSlug,
|
||||
resolveApiModelId,
|
||||
resolveContextWindow,
|
||||
@@ -226,3 +228,57 @@ describe("resolveApiModelId", () => {
|
||||
expect(resolveApiModelId({ provider: "codex", model: "gpt-5.4" })).toBe("gpt-5.4");
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalize*ModelOptionsWithCapabilities", () => {
|
||||
it("preserves explicit false codex fast mode", () => {
|
||||
expect(
|
||||
normalizeCodexModelOptionsWithCapabilities(codexCaps, {
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
}),
|
||||
).toEqual({
|
||||
reasoningEffort: "high",
|
||||
fastMode: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves the default Claude context window explicitly", () => {
|
||||
expect(
|
||||
normalizeClaudeModelOptionsWithCapabilities(
|
||||
{
|
||||
...claudeCaps,
|
||||
contextWindowOptions: [
|
||||
{ value: "200k", label: "200k", isDefault: true },
|
||||
{ value: "1m", label: "1M" },
|
||||
],
|
||||
},
|
||||
{
|
||||
effort: "high",
|
||||
contextWindow: "200k",
|
||||
},
|
||||
),
|
||||
).toEqual({
|
||||
effort: "high",
|
||||
contextWindow: "200k",
|
||||
});
|
||||
});
|
||||
|
||||
it("omits unsupported Claude context window options", () => {
|
||||
expect(
|
||||
normalizeClaudeModelOptionsWithCapabilities(
|
||||
{
|
||||
...claudeCaps,
|
||||
reasoningEffortLevels: [],
|
||||
supportsThinkingToggle: true,
|
||||
contextWindowOptions: [],
|
||||
},
|
||||
{
|
||||
thinking: true,
|
||||
contextWindow: "1m",
|
||||
},
|
||||
),
|
||||
).toEqual({
|
||||
thinking: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,8 @@ import {
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
MODEL_SLUG_ALIASES_BY_PROVIDER,
|
||||
type ClaudeCodeEffort,
|
||||
type ClaudeModelOptions,
|
||||
type CodexModelOptions,
|
||||
type ModelCapabilities,
|
||||
type ModelSelection,
|
||||
type ProviderKind,
|
||||
@@ -83,6 +85,38 @@ export function resolveContextWindow(
|
||||
return hasContextWindowOption(caps, raw) ? raw : (defaultValue ?? undefined);
|
||||
}
|
||||
|
||||
export function normalizeCodexModelOptionsWithCapabilities(
|
||||
caps: ModelCapabilities,
|
||||
modelOptions: CodexModelOptions | null | undefined,
|
||||
): CodexModelOptions | undefined {
|
||||
const reasoningEffort = resolveEffort(caps, modelOptions?.reasoningEffort);
|
||||
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
|
||||
const nextOptions: CodexModelOptions = {
|
||||
...(reasoningEffort
|
||||
? { reasoningEffort: reasoningEffort as CodexModelOptions["reasoningEffort"] }
|
||||
: {}),
|
||||
...(fastMode !== undefined ? { fastMode } : {}),
|
||||
};
|
||||
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 : undefined;
|
||||
const fastMode = caps.supportsFastMode ? modelOptions?.fastMode : undefined;
|
||||
const contextWindow = resolveContextWindow(caps, modelOptions?.contextWindow);
|
||||
const nextOptions: ClaudeModelOptions = {
|
||||
...(thinking !== undefined ? { thinking } : {}),
|
||||
...(effort ? { effort: effort as ClaudeModelOptions["effort"] } : {}),
|
||||
...(fastMode !== undefined ? { fastMode } : {}),
|
||||
...(contextWindow !== undefined ? { contextWindow } : {}),
|
||||
};
|
||||
return Object.keys(nextOptions).length > 0 ? nextOptions : undefined;
|
||||
}
|
||||
|
||||
export function isClaudeUltrathinkPrompt(text: string | null | undefined): boolean {
|
||||
return typeof text === "string" && /\bultrathink\b/i.test(text);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user