Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
67e3f2c7d5 | ||
|
|
8622b952ca | ||
|
|
f47c1f1046 | ||
|
|
145ddfc408 | ||
|
|
0bb787b90d | ||
|
|
59f23d7bfd | ||
|
|
4a4795e5f0 | ||
|
|
5b58f74e9a | ||
|
|
32dca3b76b | ||
|
|
6358444900 | ||
|
|
792ad4b5c1 | ||
|
|
d41781987c | ||
|
|
fc6507066e | ||
|
|
bf9c828aef | ||
|
|
7b676b76de | ||
|
|
d5f2333173 | ||
|
|
40e7dbdae9 |
No files matched your search
@@ -2,18 +2,42 @@
|
||||
|
||||
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
|
||||
|
||||
## How to use
|
||||
## Installation
|
||||
|
||||
> [!WARNING]
|
||||
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
|
||||
> T3 Code currently supports Codex and Claude.
|
||||
> Install and authenticate at least one provider before use:
|
||||
>
|
||||
> - Codex: install [Codex CLI](https://github.com/openai/codex) and run `codex login`
|
||||
> - Claude: install Claude Code and run `claude auth login`
|
||||
|
||||
### Run without installing
|
||||
|
||||
```bash
|
||||
npx t3
|
||||
```
|
||||
|
||||
You can also just install the desktop app. It's cooler.
|
||||
### Desktop app
|
||||
|
||||
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
|
||||
Install the latest version of the desktop app from [GitHub Releases](https://github.com/pingdotgg/t3code/releases), or from your favorite package registry:
|
||||
|
||||
#### Windows (`winget`)
|
||||
|
||||
```bash
|
||||
winget install T3Tools.T3Code
|
||||
```
|
||||
|
||||
#### macOS (Homebrew)
|
||||
|
||||
```bash
|
||||
brew install --cask t3-code
|
||||
```
|
||||
|
||||
#### Arch Linux (AUR)
|
||||
|
||||
```bash
|
||||
yay -S t3code-bin
|
||||
```
|
||||
|
||||
## Some notes
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -14,47 +14,81 @@ import {
|
||||
TerminalResizeInput,
|
||||
TerminalRestartInput,
|
||||
TerminalSessionSnapshot,
|
||||
TerminalSessionStatus,
|
||||
TerminalWriteInput,
|
||||
} from "@t3tools/contracts";
|
||||
import { PtyProcess } from "./PTY";
|
||||
import { Effect, Schema, ServiceMap } from "effect";
|
||||
|
||||
export class TerminalError extends Schema.TaggedErrorClass<TerminalError>()("TerminalError", {
|
||||
message: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
}) {}
|
||||
|
||||
export interface TerminalSessionState {
|
||||
threadId: string;
|
||||
terminalId: string;
|
||||
cwd: string;
|
||||
status: TerminalSessionStatus;
|
||||
pid: number | null;
|
||||
history: string;
|
||||
pendingHistoryControlSequence: string;
|
||||
exitCode: number | null;
|
||||
exitSignal: number | null;
|
||||
updatedAt: string;
|
||||
cols: number;
|
||||
rows: number;
|
||||
process: PtyProcess | null;
|
||||
unsubscribeData: (() => void) | null;
|
||||
unsubscribeExit: (() => void) | null;
|
||||
hasRunningSubprocess: boolean;
|
||||
runtimeEnv: Record<string, string> | null;
|
||||
export class TerminalCwdError extends Schema.TaggedErrorClass<TerminalCwdError>()(
|
||||
"TerminalCwdError",
|
||||
{
|
||||
cwd: Schema.String,
|
||||
reason: Schema.Literals(["notFound", "notDirectory", "statFailed"]),
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
if (this.reason === "notDirectory") {
|
||||
return `Terminal cwd is not a directory: ${this.cwd}`;
|
||||
}
|
||||
if (this.reason === "notFound") {
|
||||
return `Terminal cwd does not exist: ${this.cwd}`;
|
||||
}
|
||||
const causeMessage =
|
||||
this.cause && typeof this.cause === "object" && "message" in this.cause
|
||||
? this.cause.message
|
||||
: undefined;
|
||||
return causeMessage
|
||||
? `Failed to access terminal cwd: ${this.cwd} (${causeMessage})`
|
||||
: `Failed to access terminal cwd: ${this.cwd}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface ShellCandidate {
|
||||
shell: string;
|
||||
args?: string[];
|
||||
export class TerminalHistoryError extends Schema.TaggedErrorClass<TerminalHistoryError>()(
|
||||
"TerminalHistoryError",
|
||||
{
|
||||
operation: Schema.Literals(["read", "truncate", "migrate"]),
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
cause: Schema.optional(Schema.Defect),
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Failed to ${this.operation} terminal history for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface TerminalStartInput extends TerminalOpenInput {
|
||||
cols: number;
|
||||
rows: number;
|
||||
export class TerminalSessionLookupError extends Schema.TaggedErrorClass<TerminalSessionLookupError>()(
|
||||
"TerminalSessionLookupError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Unknown terminal thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export class TerminalNotRunningError extends Schema.TaggedErrorClass<TerminalNotRunningError>()(
|
||||
"TerminalNotRunningError",
|
||||
{
|
||||
threadId: Schema.String,
|
||||
terminalId: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message() {
|
||||
return `Terminal is not running for thread: ${this.threadId}, terminal: ${this.terminalId}`;
|
||||
}
|
||||
}
|
||||
|
||||
export const TerminalError = Schema.Union([
|
||||
TerminalCwdError,
|
||||
TerminalHistoryError,
|
||||
TerminalSessionLookupError,
|
||||
TerminalNotRunningError,
|
||||
]);
|
||||
export type TerminalError = typeof TerminalError.Type;
|
||||
|
||||
/**
|
||||
* TerminalManagerShape - Service API for terminal session lifecycle operations.
|
||||
*/
|
||||
@@ -101,14 +135,13 @@ export interface TerminalManagerShape {
|
||||
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
|
||||
|
||||
/**
|
||||
* Subscribe to terminal runtime events.
|
||||
* Subscribe to terminal runtime events with a direct callback.
|
||||
*
|
||||
* Returns an unsubscribe function.
|
||||
*/
|
||||
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
|
||||
|
||||
/**
|
||||
* Dispose all managed terminal resources.
|
||||
*/
|
||||
readonly dispose: Effect.Effect<void>;
|
||||
readonly subscribe: (
|
||||
listener: (event: TerminalEvent) => Effect.Effect<void>,
|
||||
) => Effect.Effect<() => void>;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { Effect, Exit, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
|
||||
import { describe, expect, it, afterEach, vi } from "vitest";
|
||||
import { createServer } from "./wsServer";
|
||||
import WebSocket from "ws";
|
||||
@@ -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: [],
|
||||
},
|
||||
@@ -90,20 +90,19 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
|
||||
|
||||
class MockTerminalManager implements TerminalManagerShape {
|
||||
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
|
||||
private readonly listeners = new Set<(event: TerminalEvent) => void>();
|
||||
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
|
||||
private activeSubscriptions = 0;
|
||||
|
||||
private key(threadId: string, terminalId: string): string {
|
||||
return `${threadId}\u0000${terminalId}`;
|
||||
}
|
||||
|
||||
emitEvent(event: TerminalEvent): void {
|
||||
for (const listener of this.listeners) {
|
||||
listener(event);
|
||||
}
|
||||
Effect.runSync(PubSub.publish(this.eventPubSub, event));
|
||||
}
|
||||
|
||||
subscriptionCount(): number {
|
||||
return this.listeners.size;
|
||||
return this.activeSubscriptions;
|
||||
}
|
||||
|
||||
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
|
||||
@@ -210,13 +209,15 @@ class MockTerminalManager implements TerminalManagerShape {
|
||||
|
||||
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
|
||||
Effect.sync(() => {
|
||||
this.listeners.add(listener);
|
||||
this.activeSubscriptions += 1;
|
||||
const fiber = Effect.runFork(
|
||||
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
|
||||
);
|
||||
return () => {
|
||||
this.listeners.delete(listener);
|
||||
this.activeSubscriptions -= 1;
|
||||
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
|
||||
};
|
||||
});
|
||||
|
||||
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -1454,19 +1455,25 @@ describe("WebSocket Server", () => {
|
||||
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
|
||||
});
|
||||
|
||||
it("detaches terminal event listener on stop for injected manager", async () => {
|
||||
it("shuts down cleanly for injected terminal managers", async () => {
|
||||
const terminalManager = new MockTerminalManager();
|
||||
server = await createTestServer({
|
||||
cwd: "/test",
|
||||
terminalManager,
|
||||
});
|
||||
|
||||
expect(terminalManager.subscriptionCount()).toBe(1);
|
||||
|
||||
await closeTestServer();
|
||||
server = null;
|
||||
|
||||
expect(terminalManager.subscriptionCount()).toBe(0);
|
||||
expect(() =>
|
||||
terminalManager.emitEvent({
|
||||
type: "output",
|
||||
threadId: "thread-1",
|
||||
terminalId: DEFAULT_TERMINAL_ID,
|
||||
createdAt: new Date().toISOString(),
|
||||
data: "after shutdown\n",
|
||||
}),
|
||||
).not.toThrow();
|
||||
});
|
||||
|
||||
it("returns validation errors for invalid terminal open params", async () => {
|
||||
|
||||
@@ -719,9 +719,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
|
||||
}
|
||||
|
||||
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
|
||||
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
|
||||
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
|
||||
);
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
|
||||
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
|
||||
yield* readiness.markTerminalSubscriptionsReady;
|
||||
|
||||
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
|
||||
|
||||
@@ -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,87 @@ describe("ChatView timeline estimator parity (full app)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
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,
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -464,6 +553,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
|
||||
...defaultModelSelection,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
createdAt: "2026-03-09T10:00:00.000Z",
|
||||
updatedAt: "2026-03-09T10:00:00.000Z",
|
||||
scripts: [],
|
||||
@@ -795,8 +885,8 @@ describe("sortProjectsForSidebar", () => {
|
||||
|
||||
it("preserves manual project ordering", () => {
|
||||
const projects = [
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second" }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First" }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-2"), name: "Second", pinned: true }),
|
||||
makeProject({ id: ProjectId.makeUnsafe("project-1"), name: "First", pinned: false }),
|
||||
];
|
||||
|
||||
const sorted = sortProjectsForSidebar(projects, [], "manual");
|
||||
@@ -807,6 +897,58 @@ describe("sortProjectsForSidebar", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps pinned projects ahead of unpinned projects in auto sort modes", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Unpinned newer",
|
||||
pinned: false,
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-2"),
|
||||
name: "Pinned older",
|
||||
pinned: true,
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
],
|
||||
[],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("still sorts pinned projects relative to each other by the active auto sort", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-1"),
|
||||
name: "Pinned older",
|
||||
pinned: true,
|
||||
updatedAt: "2026-03-09T10:01:00.000Z",
|
||||
}),
|
||||
makeProject({
|
||||
id: ProjectId.makeUnsafe("project-2"),
|
||||
name: "Pinned newer",
|
||||
pinned: true,
|
||||
updatedAt: "2026-03-09T10:05:00.000Z",
|
||||
}),
|
||||
],
|
||||
[],
|
||||
"updated_at",
|
||||
);
|
||||
|
||||
expect(sorted.map((project) => project.id)).toEqual([
|
||||
ProjectId.makeUnsafe("project-2"),
|
||||
ProjectId.makeUnsafe("project-1"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("ignores archived threads when sorting projects", () => {
|
||||
const sorted = sortProjectsForSidebar(
|
||||
[
|
||||
|
||||
@@ -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,10 +9,12 @@ 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;
|
||||
name: string;
|
||||
pinned: boolean;
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
};
|
||||
@@ -46,6 +49,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 +159,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 +335,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
previewLimit: number;
|
||||
}): {
|
||||
hasHiddenThreads: boolean;
|
||||
hiddenThreads: Thread[];
|
||||
visibleThreads: Thread[];
|
||||
} {
|
||||
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
|
||||
@@ -252,6 +344,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!hasHiddenThreads || isThreadListExpanded) {
|
||||
return {
|
||||
hasHiddenThreads,
|
||||
hiddenThreads: [],
|
||||
visibleThreads: [...threads],
|
||||
};
|
||||
}
|
||||
@@ -260,6 +353,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.slice(previewLimit),
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
@@ -268,6 +362,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
if (!activeThread) {
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.slice(previewLimit),
|
||||
visibleThreads: previewThreads,
|
||||
};
|
||||
}
|
||||
@@ -276,6 +371,7 @@ export function getVisibleThreadsForProject(input: {
|
||||
|
||||
return {
|
||||
hasHiddenThreads: true,
|
||||
hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
|
||||
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
|
||||
};
|
||||
}
|
||||
@@ -391,6 +487,8 @@ export function sortProjectsForSidebar<TProject extends SidebarProject, TThread
|
||||
}
|
||||
|
||||
return [...projects].toSorted((left, right) => {
|
||||
const byPinned = Number(right.pinned) - Number(left.pinned);
|
||||
if (byPinned !== 0) return byPinned;
|
||||
const rightTimestamp = getProjectSortTimestamp(
|
||||
right,
|
||||
threadsByProjectId.get(right.id) ?? [],
|
||||
|
||||
+203
-114
@@ -4,6 +4,7 @@ import {
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
GitPullRequestIcon,
|
||||
PinIcon,
|
||||
PlusIcon,
|
||||
SettingsIcon,
|
||||
SquarePenIcon,
|
||||
@@ -69,6 +70,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 +118,7 @@ import {
|
||||
shouldClearThreadSelectionOnMouseDown,
|
||||
sortProjectsForSidebar,
|
||||
sortThreadsForSidebar,
|
||||
useThreadJumpHintVisibility,
|
||||
} from "./Sidebar.logic";
|
||||
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
|
||||
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
|
||||
@@ -151,6 +154,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 {
|
||||
@@ -324,6 +365,7 @@ export default function Sidebar() {
|
||||
const threads = useStore((store) => store.threads);
|
||||
const markThreadUnread = useStore((store) => store.markThreadUnread);
|
||||
const toggleProject = useStore((store) => store.toggleProject);
|
||||
const toggleProjectPinned = useStore((store) => store.toggleProjectPinned);
|
||||
const reorderProjects = useStore((store) => store.reorderProjects);
|
||||
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
|
||||
const getDraftThreadByProjectId = useComposerDraftStore(
|
||||
@@ -356,14 +398,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);
|
||||
@@ -869,11 +911,16 @@ export default function Sidebar() {
|
||||
|
||||
const clicked = await api.contextMenu.show(
|
||||
[
|
||||
{ id: "toggle-pin", label: project.pinned ? "Unpin project" : "Pin project" },
|
||||
{ id: "copy-path", label: "Copy Project Path" },
|
||||
{ id: "delete", label: "Remove project", destructive: true },
|
||||
],
|
||||
position,
|
||||
);
|
||||
if (clicked === "toggle-pin") {
|
||||
toggleProjectPinned(projectId);
|
||||
return;
|
||||
}
|
||||
if (clicked === "copy-path") {
|
||||
copyPathToClipboard(project.cwd, { path: project.cwd });
|
||||
return;
|
||||
@@ -921,6 +968,7 @@ export default function Sidebar() {
|
||||
getDraftThreadByProjectId,
|
||||
projects,
|
||||
threads,
|
||||
toggleProjectPinned,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1023,14 +1071,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 +1091,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 +1132,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 +1162,7 @@ export default function Sidebar() {
|
||||
}
|
||||
return mapping;
|
||||
}, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]);
|
||||
const orderedSidebarThreadIds = useMemo(
|
||||
() => getVisibleSidebarThreadIds(renderedProjects),
|
||||
[renderedProjects],
|
||||
);
|
||||
const orderedSidebarThreadIds = visibleSidebarThreadIds;
|
||||
|
||||
useEffect(() => {
|
||||
const getShortcutContext = () => ({
|
||||
@@ -1113,7 +1171,7 @@ export default function Sidebar() {
|
||||
});
|
||||
|
||||
const onWindowKeyDown = (event: KeyboardEvent) => {
|
||||
setShowThreadJumpHints(
|
||||
updateThreadJumpHintsVisibility(
|
||||
shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: getShortcutContext(),
|
||||
@@ -1161,7 +1219,7 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const onWindowKeyUp = (event: KeyboardEvent) => {
|
||||
setShowThreadJumpHints(
|
||||
updateThreadJumpHintsVisibility(
|
||||
shouldShowThreadJumpHints(event, keybindings, {
|
||||
platform,
|
||||
context: getShortcutContext(),
|
||||
@@ -1170,7 +1228,7 @@ export default function Sidebar() {
|
||||
};
|
||||
|
||||
const onWindowBlur = () => {
|
||||
setShowThreadJumpHints(false);
|
||||
updateThreadJumpHintsVisibility(false);
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onWindowKeyDown);
|
||||
@@ -1190,6 +1248,7 @@ export default function Sidebar() {
|
||||
routeTerminalOpen,
|
||||
routeThreadId,
|
||||
threadJumpThreadIds,
|
||||
updateThreadJumpHintsVisibility,
|
||||
]);
|
||||
|
||||
function renderProjectItem(
|
||||
@@ -1198,11 +1257,14 @@ export default function Sidebar() {
|
||||
) {
|
||||
const {
|
||||
hasHiddenThreads,
|
||||
hiddenThreadStatus,
|
||||
orderedProjectThreadIds,
|
||||
project,
|
||||
projectStatus,
|
||||
projectThreads,
|
||||
threadStatuses,
|
||||
renderedThreads,
|
||||
showEmptyThreadState,
|
||||
shouldShowThreadPanel,
|
||||
isThreadListExpanded,
|
||||
} = renderedProject;
|
||||
@@ -1213,37 +1275,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 +1324,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 +1360,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 +1410,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 +1433,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>
|
||||
@@ -1497,6 +1567,12 @@ export default function Sidebar() {
|
||||
<span className="flex-1 truncate text-xs font-medium text-foreground/90">
|
||||
{project.name}
|
||||
</span>
|
||||
{project.pinned ? (
|
||||
<PinIcon
|
||||
aria-hidden="true"
|
||||
className="size-3 shrink-0 rotate-45 text-muted-foreground/55"
|
||||
/>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -1535,6 +1611,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 +1634,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"}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -7,7 +7,13 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
|
||||
import {
|
||||
markThreadUnread,
|
||||
reorderProjects,
|
||||
syncServerReadModel,
|
||||
toggleProjectPinned,
|
||||
type AppState,
|
||||
} from "./store";
|
||||
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
|
||||
|
||||
function makeThread(overrides: Partial<Thread> = {}): Thread {
|
||||
@@ -49,6 +55,7 @@ function makeState(thread: Thread): AppState {
|
||||
model: "gpt-5-codex",
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
@@ -181,6 +188,7 @@ describe("store pure functions", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
@@ -192,6 +200,7 @@ describe("store pure functions", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
@@ -203,6 +212,7 @@ describe("store pure functions", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
@@ -214,6 +224,16 @@ describe("store pure functions", () => {
|
||||
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]);
|
||||
});
|
||||
|
||||
it("toggleProjectPinned flips the pinned flag for the selected project", () => {
|
||||
const projectId = ProjectId.makeUnsafe("project-1");
|
||||
const initialState = makeState(makeThread());
|
||||
|
||||
const next = toggleProjectPinned(initialState, projectId);
|
||||
|
||||
expect(next.projects[0]?.pinned).toBe(true);
|
||||
expect(initialState.projects[0]?.pinned).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("store read model sync", () => {
|
||||
@@ -302,6 +322,7 @@ describe("store read model sync", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: true,
|
||||
scripts: [],
|
||||
},
|
||||
{
|
||||
@@ -313,6 +334,7 @@ describe("store read model sync", () => {
|
||||
model: DEFAULT_MODEL_BY_PROVIDER.codex,
|
||||
},
|
||||
expanded: true,
|
||||
pinned: false,
|
||||
scripts: [],
|
||||
},
|
||||
],
|
||||
@@ -345,5 +367,6 @@ describe("store read model sync", () => {
|
||||
const next = syncServerReadModel(initialState, readModel);
|
||||
|
||||
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
|
||||
expect(next.projects.map((project) => project.pinned)).toEqual([true, false, false]);
|
||||
});
|
||||
});
|
||||
@@ -37,6 +37,7 @@ const initialState: AppState = {
|
||||
threadsHydrated: false,
|
||||
};
|
||||
const persistedExpandedProjectCwds = new Set<string>();
|
||||
const persistedPinnedProjectCwds = new Set<string>();
|
||||
const persistedProjectOrderCwds: string[] = [];
|
||||
|
||||
// ── Persist helpers ──────────────────────────────────────────────────
|
||||
@@ -48,15 +49,22 @@ function readPersistedState(): AppState {
|
||||
if (!raw) return initialState;
|
||||
const parsed = JSON.parse(raw) as {
|
||||
expandedProjectCwds?: string[];
|
||||
pinnedProjectCwds?: string[];
|
||||
projectOrderCwds?: string[];
|
||||
};
|
||||
persistedExpandedProjectCwds.clear();
|
||||
persistedPinnedProjectCwds.clear();
|
||||
persistedProjectOrderCwds.length = 0;
|
||||
for (const cwd of parsed.expandedProjectCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0) {
|
||||
persistedExpandedProjectCwds.add(cwd);
|
||||
}
|
||||
}
|
||||
for (const cwd of parsed.pinnedProjectCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0) {
|
||||
persistedPinnedProjectCwds.add(cwd);
|
||||
}
|
||||
}
|
||||
for (const cwd of parsed.projectOrderCwds ?? []) {
|
||||
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
|
||||
persistedProjectOrderCwds.push(cwd);
|
||||
@@ -79,6 +87,9 @@ function persistState(state: AppState): void {
|
||||
expandedProjectCwds: state.projects
|
||||
.filter((project) => project.expanded)
|
||||
.map((project) => project.cwd),
|
||||
pinnedProjectCwds: state.projects
|
||||
.filter((project) => project.pinned)
|
||||
.map((project) => project.cwd),
|
||||
projectOrderCwds: state.projects.map((project) => project.cwd),
|
||||
}),
|
||||
);
|
||||
@@ -148,6 +159,7 @@ function mapProjectsFromReadModel(
|
||||
(persistedExpandedProjectCwds.size > 0
|
||||
? persistedExpandedProjectCwds.has(project.workspaceRoot)
|
||||
: true),
|
||||
pinned: existing?.pinned ?? persistedPinnedProjectCwds.has(project.workspaceRoot),
|
||||
createdAt: project.createdAt,
|
||||
updatedAt: project.updatedAt,
|
||||
scripts: project.scripts.map((script) => ({ ...script })),
|
||||
@@ -379,6 +391,16 @@ export function setProjectExpanded(
|
||||
return changed ? { ...state, projects } : state;
|
||||
}
|
||||
|
||||
export function toggleProjectPinned(state: AppState, projectId: Project["id"]): AppState {
|
||||
let changed = false;
|
||||
const projects = state.projects.map((project) => {
|
||||
if (project.id !== projectId) return project;
|
||||
changed = true;
|
||||
return { ...project, pinned: !project.pinned };
|
||||
});
|
||||
return changed ? { ...state, projects } : state;
|
||||
}
|
||||
|
||||
export function reorderProjects(
|
||||
state: AppState,
|
||||
draggedProjectId: Project["id"],
|
||||
@@ -429,6 +451,7 @@ interface AppStore extends AppState {
|
||||
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
|
||||
markThreadUnread: (threadId: ThreadId) => void;
|
||||
toggleProject: (projectId: Project["id"]) => void;
|
||||
toggleProjectPinned: (projectId: Project["id"]) => void;
|
||||
setProjectExpanded: (projectId: Project["id"], expanded: boolean) => void;
|
||||
reorderProjects: (draggedProjectId: Project["id"], targetProjectId: Project["id"]) => void;
|
||||
setError: (threadId: ThreadId, error: string | null) => void;
|
||||
@@ -442,6 +465,7 @@ export const useStore = create<AppStore>((set) => ({
|
||||
set((state) => markThreadVisited(state, threadId, visitedAt)),
|
||||
markThreadUnread: (threadId) => set((state) => markThreadUnread(state, threadId)),
|
||||
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
|
||||
toggleProjectPinned: (projectId) => set((state) => toggleProjectPinned(state, projectId)),
|
||||
setProjectExpanded: (projectId, expanded) =>
|
||||
set((state) => setProjectExpanded(state, projectId, expanded)),
|
||||
reorderProjects: (draggedProjectId, targetProjectId) =>
|
||||
|
||||
@@ -83,6 +83,7 @@ export interface Project {
|
||||
cwd: string;
|
||||
defaultModelSelection: ModelSelection | null;
|
||||
expanded: boolean;
|
||||
pinned: boolean;
|
||||
createdAt?: string | undefined;
|
||||
updatedAt?: string | undefined;
|
||||
scripts: ProjectScript[];
|
||||
|
||||
@@ -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: [],
|
||||
},
|
||||
|
||||
@@ -130,12 +130,12 @@ export interface NativeApi {
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
};
|
||||
terminal: {
|
||||
open: (input: TerminalOpenInput) => Promise<TerminalSessionSnapshot>;
|
||||
write: (input: TerminalWriteInput) => Promise<void>;
|
||||
resize: (input: TerminalResizeInput) => Promise<void>;
|
||||
clear: (input: TerminalClearInput) => Promise<void>;
|
||||
restart: (input: TerminalRestartInput) => Promise<TerminalSessionSnapshot>;
|
||||
close: (input: TerminalCloseInput) => Promise<void>;
|
||||
open: (input: typeof TerminalOpenInput.Encoded) => Promise<TerminalSessionSnapshot>;
|
||||
write: (input: typeof TerminalWriteInput.Encoded) => Promise<void>;
|
||||
resize: (input: typeof TerminalResizeInput.Encoded) => Promise<void>;
|
||||
clear: (input: typeof TerminalClearInput.Encoded) => Promise<void>;
|
||||
restart: (input: typeof TerminalRestartInput.Encoded) => Promise<TerminalSessionSnapshot>;
|
||||
close: (input: typeof TerminalCloseInput.Encoded) => Promise<void>;
|
||||
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
|
||||
};
|
||||
projects: {
|
||||
|
||||
@@ -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([
|
||||
|
||||
@@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
|
||||
export const TerminalThreadInput = Schema.Struct({
|
||||
threadId: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type TerminalThreadInput = Schema.Codec.Encoded<typeof TerminalThreadInput>;
|
||||
export type TerminalThreadInput = typeof TerminalThreadInput.Type;
|
||||
|
||||
const TerminalSessionInput = Schema.Struct({
|
||||
...TerminalThreadInput.fields,
|
||||
@@ -73,7 +73,7 @@ export const TerminalCloseInput = Schema.Struct({
|
||||
terminalId: Schema.optional(TerminalIdSchema),
|
||||
deleteHistory: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type TerminalCloseInput = Schema.Codec.Encoded<typeof TerminalCloseInput>;
|
||||
export type TerminalCloseInput = typeof TerminalCloseInput.Type;
|
||||
|
||||
export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
|
||||
export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
|
||||
|
||||
@@ -28,6 +28,10 @@
|
||||
"types": "./src/DrainableWorker.ts",
|
||||
"import": "./src/DrainableWorker.ts"
|
||||
},
|
||||
"./KeyedCoalescingWorker": {
|
||||
"types": "./src/KeyedCoalescingWorker.ts",
|
||||
"import": "./src/KeyedCoalescingWorker.ts"
|
||||
},
|
||||
"./schemaJson": {
|
||||
"types": "./src/schemaJson.ts",
|
||||
"import": "./src/schemaJson.ts"
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
import { it } from "@effect/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
import { Deferred, Effect } from "effect";
|
||||
|
||||
import { makeKeyedCoalescingWorker } from "./KeyedCoalescingWorker";
|
||||
|
||||
describe("makeKeyedCoalescingWorker", () => {
|
||||
it.live("waits for latest work enqueued during active processing before draining the key", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const processed: string[] = [];
|
||||
const firstStarted = yield* Deferred.make<void>();
|
||||
const releaseFirst = yield* Deferred.make<void>();
|
||||
const secondStarted = yield* Deferred.make<void>();
|
||||
const releaseSecond = yield* Deferred.make<void>();
|
||||
|
||||
const worker = yield* makeKeyedCoalescingWorker<string, string, never, never>({
|
||||
merge: (_current, next) => next,
|
||||
process: (key, value) =>
|
||||
Effect.gen(function* () {
|
||||
processed.push(`${key}:${value}`);
|
||||
|
||||
if (value === "first") {
|
||||
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
|
||||
yield* Deferred.await(releaseFirst);
|
||||
}
|
||||
|
||||
if (value === "second") {
|
||||
yield* Deferred.succeed(secondStarted, undefined).pipe(Effect.orDie);
|
||||
yield* Deferred.await(releaseSecond);
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
yield* worker.enqueue("terminal-1", "first");
|
||||
yield* Deferred.await(firstStarted);
|
||||
|
||||
const drained = yield* Deferred.make<void>();
|
||||
yield* Effect.forkChild(
|
||||
worker
|
||||
.drainKey("terminal-1")
|
||||
.pipe(Effect.tap(() => Deferred.succeed(drained, undefined).pipe(Effect.orDie))),
|
||||
);
|
||||
|
||||
yield* worker.enqueue("terminal-1", "second");
|
||||
yield* Deferred.succeed(releaseFirst, undefined);
|
||||
yield* Deferred.await(secondStarted);
|
||||
|
||||
expect(yield* Deferred.isDone(drained)).toBe(false);
|
||||
|
||||
yield* Deferred.succeed(releaseSecond, undefined);
|
||||
yield* Deferred.await(drained);
|
||||
|
||||
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
it.live("requeues pending work for a key after a processor failure and keeps draining", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const processed: string[] = [];
|
||||
const firstStarted = yield* Deferred.make<void>();
|
||||
const releaseFailure = yield* Deferred.make<void>();
|
||||
const secondProcessed = yield* Deferred.make<void>();
|
||||
|
||||
const worker = yield* makeKeyedCoalescingWorker<string, string, string, never>({
|
||||
merge: (_current, next) => next,
|
||||
process: (key, value) =>
|
||||
Effect.gen(function* () {
|
||||
processed.push(`${key}:${value}`);
|
||||
|
||||
if (value === "first") {
|
||||
yield* Deferred.succeed(firstStarted, undefined).pipe(Effect.orDie);
|
||||
yield* Deferred.await(releaseFailure);
|
||||
yield* Effect.fail("boom");
|
||||
}
|
||||
|
||||
if (value === "second") {
|
||||
yield* Deferred.succeed(secondProcessed, undefined).pipe(Effect.orDie);
|
||||
}
|
||||
}),
|
||||
});
|
||||
|
||||
yield* worker.enqueue("terminal-1", "first");
|
||||
yield* Deferred.await(firstStarted);
|
||||
yield* worker.enqueue("terminal-1", "second");
|
||||
yield* Deferred.succeed(releaseFailure, undefined);
|
||||
yield* Deferred.await(secondProcessed);
|
||||
yield* worker.drainKey("terminal-1");
|
||||
|
||||
expect(processed).toEqual(["terminal-1:first", "terminal-1:second"]);
|
||||
}),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* KeyedCoalescingWorker - A keyed worker that keeps only the latest value per key.
|
||||
*
|
||||
* Enqueues for an active or already-queued key are merged atomically instead of
|
||||
* creating duplicate queued items. `drainKey()` resolves only when that key has
|
||||
* no queued, pending, or active work left.
|
||||
*
|
||||
* @module KeyedCoalescingWorker
|
||||
*/
|
||||
import type { Scope } from "effect";
|
||||
import { Effect, TxQueue, TxRef } from "effect";
|
||||
|
||||
export interface KeyedCoalescingWorker<K, V> {
|
||||
readonly enqueue: (key: K, value: V) => Effect.Effect<void>;
|
||||
readonly drainKey: (key: K) => Effect.Effect<void>;
|
||||
}
|
||||
|
||||
interface KeyedCoalescingWorkerState<K, V> {
|
||||
readonly latestByKey: Map<K, V>;
|
||||
readonly queuedKeys: Set<K>;
|
||||
readonly activeKeys: Set<K>;
|
||||
}
|
||||
|
||||
export const makeKeyedCoalescingWorker = <K, V, E, R>(options: {
|
||||
readonly merge: (current: V, next: V) => V;
|
||||
readonly process: (key: K, value: V) => Effect.Effect<void, E, R>;
|
||||
}): Effect.Effect<KeyedCoalescingWorker<K, V>, never, Scope.Scope | R> =>
|
||||
Effect.gen(function* () {
|
||||
const queue = yield* Effect.acquireRelease(TxQueue.unbounded<K>(), TxQueue.shutdown);
|
||||
const stateRef = yield* TxRef.make<KeyedCoalescingWorkerState<K, V>>({
|
||||
latestByKey: new Map(),
|
||||
queuedKeys: new Set(),
|
||||
activeKeys: new Set(),
|
||||
});
|
||||
|
||||
const processKey = (key: K, value: V): Effect.Effect<void, E, R> =>
|
||||
options.process(key, value).pipe(
|
||||
Effect.flatMap(() =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const nextValue = state.latestByKey.get(key);
|
||||
if (nextValue === undefined) {
|
||||
const activeKeys = new Set(state.activeKeys);
|
||||
activeKeys.delete(key);
|
||||
return [null, { ...state, activeKeys }] as const;
|
||||
}
|
||||
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
latestByKey.delete(key);
|
||||
return [nextValue, { ...state, latestByKey }] as const;
|
||||
}).pipe(Effect.tx),
|
||||
),
|
||||
Effect.flatMap((nextValue) =>
|
||||
nextValue === null ? Effect.void : processKey(key, nextValue),
|
||||
),
|
||||
);
|
||||
|
||||
const cleanupFailedKey = (key: K): Effect.Effect<void> =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const activeKeys = new Set(state.activeKeys);
|
||||
activeKeys.delete(key);
|
||||
|
||||
if (state.latestByKey.has(key) && !state.queuedKeys.has(key)) {
|
||||
const queuedKeys = new Set(state.queuedKeys);
|
||||
queuedKeys.add(key);
|
||||
return [true, { ...state, activeKeys, queuedKeys }] as const;
|
||||
}
|
||||
|
||||
return [false, { ...state, activeKeys }] as const;
|
||||
}).pipe(
|
||||
Effect.tx,
|
||||
Effect.flatMap((shouldRequeue) =>
|
||||
shouldRequeue ? TxQueue.offer(queue, key) : Effect.void,
|
||||
),
|
||||
);
|
||||
|
||||
yield* TxQueue.take(queue).pipe(
|
||||
Effect.flatMap((key) =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const queuedKeys = new Set(state.queuedKeys);
|
||||
queuedKeys.delete(key);
|
||||
|
||||
const value = state.latestByKey.get(key);
|
||||
if (value === undefined) {
|
||||
return [null, { ...state, queuedKeys }] as const;
|
||||
}
|
||||
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
latestByKey.delete(key);
|
||||
const activeKeys = new Set(state.activeKeys);
|
||||
activeKeys.add(key);
|
||||
|
||||
return [
|
||||
{ key, value } as const,
|
||||
{ ...state, latestByKey, queuedKeys, activeKeys },
|
||||
] as const;
|
||||
}).pipe(Effect.tx),
|
||||
),
|
||||
Effect.flatMap((item) =>
|
||||
item === null
|
||||
? Effect.void
|
||||
: processKey(item.key, item.value).pipe(
|
||||
Effect.catchCause(() => cleanupFailedKey(item.key)),
|
||||
),
|
||||
),
|
||||
Effect.forever,
|
||||
Effect.forkScoped,
|
||||
);
|
||||
|
||||
const enqueue: KeyedCoalescingWorker<K, V>["enqueue"] = (key, value) =>
|
||||
TxRef.modify(stateRef, (state) => {
|
||||
const latestByKey = new Map(state.latestByKey);
|
||||
const existing = latestByKey.get(key);
|
||||
latestByKey.set(key, existing === undefined ? value : options.merge(existing, value));
|
||||
|
||||
if (state.queuedKeys.has(key) || state.activeKeys.has(key)) {
|
||||
return [false, { ...state, latestByKey }] as const;
|
||||
}
|
||||
|
||||
const queuedKeys = new Set(state.queuedKeys);
|
||||
queuedKeys.add(key);
|
||||
return [true, { ...state, latestByKey, queuedKeys }] as const;
|
||||
}).pipe(
|
||||
Effect.flatMap((shouldOffer) => (shouldOffer ? TxQueue.offer(queue, key) : Effect.void)),
|
||||
Effect.tx,
|
||||
Effect.asVoid,
|
||||
);
|
||||
|
||||
const drainKey: KeyedCoalescingWorker<K, V>["drainKey"] = (key) =>
|
||||
TxRef.get(stateRef).pipe(
|
||||
Effect.tap((state) =>
|
||||
state.latestByKey.has(key) || state.queuedKeys.has(key) || state.activeKeys.has(key)
|
||||
? Effect.txRetry
|
||||
: Effect.void,
|
||||
),
|
||||
Effect.asVoid,
|
||||
Effect.tx,
|
||||
);
|
||||
|
||||
return { enqueue, drainKey } satisfies KeyedCoalescingWorker<K, V>;
|
||||
});
|
||||
@@ -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