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,
|
||||
|
||||
@@ -50,7 +50,6 @@ syncShellEnvironment();
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const SET_APPEARANCE_CHANNEL = "desktop:set-appearance";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
@@ -1161,17 +1160,6 @@ function registerIpcHandlers(): void {
|
||||
nativeTheme.themeSource = theme;
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(SET_APPEARANCE_CHANNEL);
|
||||
ipcMain.handle(SET_APPEARANCE_CHANNEL, async (_event, raw: unknown) => {
|
||||
if (typeof raw !== "object" || raw === null) return;
|
||||
const appearance = raw as Record<string, unknown>;
|
||||
const mode = getSafeTheme(appearance.mode);
|
||||
if (!mode) return;
|
||||
nativeTheme.themeSource = mode;
|
||||
// themeId and accentHue are stored for future Electron shell styling
|
||||
// (title bar tint, vibrancy, etc.)
|
||||
});
|
||||
|
||||
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
|
||||
ipcMain.handle(
|
||||
CONTEXT_MENU_CHANNEL,
|
||||
|
||||
@@ -4,7 +4,6 @@ import type { DesktopBridge } from "@t3tools/contracts";
|
||||
const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
|
||||
const CONFIRM_CHANNEL = "desktop:confirm";
|
||||
const SET_THEME_CHANNEL = "desktop:set-theme";
|
||||
const SET_APPEARANCE_CHANNEL = "desktop:set-appearance";
|
||||
const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
|
||||
const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
|
||||
const MENU_ACTION_CHANNEL = "desktop:menu-action";
|
||||
@@ -23,7 +22,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
pickFolder: () => ipcRenderer.invoke(PICK_FOLDER_CHANNEL),
|
||||
confirm: (message) => ipcRenderer.invoke(CONFIRM_CHANNEL, message),
|
||||
setTheme: (theme) => ipcRenderer.invoke(SET_THEME_CHANNEL, theme),
|
||||
setAppearance: (appearance) => ipcRenderer.invoke(SET_APPEARANCE_CHANNEL, appearance),
|
||||
showContextMenu: (items, position) => ipcRenderer.invoke(CONTEXT_MENU_CHANNEL, items, position),
|
||||
openExternal: (url: string) => ipcRenderer.invoke(OPEN_EXTERNAL_CHANNEL, url),
|
||||
onMenuAction: (listener) => {
|
||||
|
||||
@@ -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)}
|
||||
>
|
||||
|
||||
@@ -20,7 +20,7 @@ import { openInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
import { LRUCache } from "../lib/lruCache";
|
||||
import { useAppearance } from "../hooks/useAppearance";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
|
||||
@@ -236,7 +236,7 @@ function SuspenseShikiCodeBlock({
|
||||
}
|
||||
|
||||
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
|
||||
const { resolvedTheme } = useAppearance();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const markdownComponents = useMemo<Components>(
|
||||
() => ({
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -79,7 +79,7 @@ import {
|
||||
type TurnDiffSummary,
|
||||
} from "../types";
|
||||
import { basenameOfPath } from "../vscode-icons";
|
||||
import { useAppearance } from "../hooks/useAppearance";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
import BranchToolbar from "./BranchToolbar";
|
||||
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
|
||||
@@ -262,7 +262,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
strict: false,
|
||||
select: (params) => parseDiffRouteSearch(params),
|
||||
});
|
||||
const { resolvedTheme } = useAppearance();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const queryClient = useQueryClient();
|
||||
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
|
||||
const composerDraft = useComposerThreadDraft(threadId);
|
||||
|
||||
@@ -25,7 +25,7 @@ import { cn } from "~/lib/utils";
|
||||
import { readNativeApi } from "../nativeApi";
|
||||
import { resolvePathLinkTarget } from "../terminal-links";
|
||||
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
|
||||
import { useAppearance } from "../hooks/useAppearance";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { buildPatchCacheKey } from "../lib/diffRendering";
|
||||
import { resolveDiffThemeName } from "../lib/diffRendering";
|
||||
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
|
||||
@@ -165,7 +165,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
|
||||
|
||||
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
|
||||
const navigate = useNavigate();
|
||||
const { resolvedTheme } = useAppearance();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
|
||||
const [diffWordWrap, setDiffWordWrap] = useState(settings.diffWordWrap);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { WorkerPoolContextProvider, useWorkerPool } from "@pierre/diffs/react";
|
||||
import DiffsWorker from "@pierre/diffs/worker/worker.js?worker";
|
||||
import { useEffect, useMemo, type ReactNode } from "react";
|
||||
import { useAppearance } from "../hooks/useAppearance";
|
||||
import { useTheme } from "../hooks/useTheme";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
|
||||
function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
@@ -29,7 +29,7 @@ function DiffWorkerThemeSync({ themeName }: { themeName: DiffThemeName }) {
|
||||
}
|
||||
|
||||
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
|
||||
const { resolvedTheme } = useAppearance();
|
||||
const { resolvedTheme } = useTheme();
|
||||
const diffThemeName = resolveDiffThemeName(resolvedTheme);
|
||||
const workerPoolSize = useMemo(() => {
|
||||
const cores =
|
||||
|
||||
@@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig {
|
||||
installed: true,
|
||||
version: "0.116.0",
|
||||
status: "ready",
|
||||
authStatus: "authenticated",
|
||||
auth: { status: "authenticated" },
|
||||
checkedAt: NOW_ISO,
|
||||
models: [],
|
||||
},
|
||||
@@ -60,9 +60,6 @@ function createBaseServerConfig(): ServerConfig {
|
||||
enableAssistantStreaming: false,
|
||||
defaultThreadEnvMode: "local" as const,
|
||||
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
|
||||
colorMode: "system" as const,
|
||||
activeThemeId: "t3code",
|
||||
accentHue: null,
|
||||
providers: {
|
||||
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
|
||||
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -1,289 +0,0 @@
|
||||
import { CheckIcon } from "lucide-react";
|
||||
import { useCallback, useRef } from "react";
|
||||
import type { ColorMode } from "@t3tools/contracts/settings";
|
||||
import { useAppearance } from "../../hooks/useAppearance";
|
||||
import {
|
||||
ACCENT_PRESETS,
|
||||
BUILT_IN_THEMES,
|
||||
DEFAULT_THEME_ID,
|
||||
type ThemeDefinition,
|
||||
type ThemeTokenMap,
|
||||
} from "../../lib/themes";
|
||||
import { cn } from "../../lib/utils";
|
||||
import { Button } from "../ui/button";
|
||||
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
|
||||
import {
|
||||
SettingResetButton,
|
||||
SettingsPageContainer,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
} from "./SettingsPanels";
|
||||
|
||||
// ── Constants ────────────────────────────────────────────────────
|
||||
|
||||
const COLOR_MODE_OPTIONS = [
|
||||
{ value: "system", label: "System" },
|
||||
{ value: "light", label: "Light" },
|
||||
{ value: "dark", label: "Dark" },
|
||||
] as const;
|
||||
|
||||
// ── Swatch preview ──────────────────────────────────────────────
|
||||
|
||||
const SWATCH_TOKENS: Array<keyof ThemeTokenMap> = [
|
||||
"primary",
|
||||
"destructive",
|
||||
"success",
|
||||
"warning",
|
||||
"info",
|
||||
];
|
||||
|
||||
/** Render 5 small color dots for a theme preview. */
|
||||
function ThemeSwatch({ tokens }: { tokens: ThemeTokenMap }) {
|
||||
return (
|
||||
<div className="flex gap-1.5">
|
||||
{SWATCH_TOKENS.map((token) => {
|
||||
const color = tokens[token];
|
||||
return color ? (
|
||||
<span
|
||||
key={token}
|
||||
className="size-3 rounded-full border border-border/40"
|
||||
style={{ background: color }}
|
||||
/>
|
||||
) : (
|
||||
<span key={token} className="size-3 rounded-full border border-border/40 bg-muted" />
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Theme card ───────────────────────────────────────────────────
|
||||
|
||||
function ThemeCard({
|
||||
theme,
|
||||
isSelected,
|
||||
onSelect,
|
||||
}: {
|
||||
theme: ThemeDefinition;
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={isSelected}
|
||||
className={cn(
|
||||
"flex flex-col items-start gap-2 rounded-xl border p-3 text-left transition-colors",
|
||||
isSelected
|
||||
? "border-primary bg-primary/5 ring-2 ring-primary/30"
|
||||
: "border-border bg-card hover:border-primary/40",
|
||||
)}
|
||||
onClick={onSelect}
|
||||
>
|
||||
<div className="flex w-full items-center justify-between">
|
||||
<span className="text-sm font-medium text-foreground">{theme.name}</span>
|
||||
{isSelected ? <CheckIcon className="size-4 text-primary" /> : null}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{theme.description}</p>
|
||||
<ThemeSwatch tokens={{ ...theme.light, ...theme.dark }} />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Accent preset circle ─────────────────────────────────────────
|
||||
|
||||
function AccentCircle({
|
||||
hue,
|
||||
isSelected,
|
||||
label,
|
||||
onClick,
|
||||
}: {
|
||||
hue: number;
|
||||
isSelected: boolean;
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={isSelected}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className={cn(
|
||||
"flex size-8 shrink-0 items-center justify-center rounded-full border-2 transition-shadow",
|
||||
isSelected
|
||||
? "border-primary ring-2 ring-primary/30"
|
||||
: "border-border hover:border-primary/40",
|
||||
)}
|
||||
style={{ background: `oklch(0.55 0.2 ${hue})` }}
|
||||
onClick={onClick}
|
||||
>
|
||||
{isSelected ? <CheckIcon className="size-3.5 text-white drop-shadow-sm" /> : null}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Main panel ───────────────────────────────────────────────────
|
||||
|
||||
export function AppearanceSettingsPanel() {
|
||||
const { colorMode, activeTheme, accentHue, setColorMode, setThemeId, setAccentHue } =
|
||||
useAppearance();
|
||||
|
||||
const colorInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleCustomAccentChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
// Convert hex to approximate oklch hue via HSL
|
||||
const hex = e.target.value;
|
||||
const hue = hexToApproxHue(hex);
|
||||
setAccentHue(hue);
|
||||
},
|
||||
[setAccentHue],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
{/* Section 1: Color Mode */}
|
||||
<SettingsSection title="Color Mode">
|
||||
<SettingsRow
|
||||
title="Mode"
|
||||
description="Choose how T3 Code looks across the app."
|
||||
resetAction={
|
||||
colorMode !== "system" ? (
|
||||
<SettingResetButton label="color mode" onClick={() => setColorMode("system")} />
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={colorMode}
|
||||
onValueChange={(value) => {
|
||||
if (value === "system" || value === "light" || value === "dark") {
|
||||
setColorMode(value as ColorMode);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Color mode preference">
|
||||
<SelectValue>
|
||||
{COLOR_MODE_OPTIONS.find((o) => o.value === colorMode)?.label ?? "System"}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{COLOR_MODE_OPTIONS.map((option) => (
|
||||
<SelectItem hideIndicator key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
{/* Section 2: Theme */}
|
||||
<SettingsSection title="Theme">
|
||||
<div className="px-4 py-4 sm:px-5">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
{BUILT_IN_THEMES.map((theme) => (
|
||||
<ThemeCard
|
||||
key={theme.id}
|
||||
theme={theme}
|
||||
isSelected={activeTheme.id === theme.id}
|
||||
onSelect={() => setThemeId(theme.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{activeTheme.id !== DEFAULT_THEME_ID ? (
|
||||
<div className="mt-3 flex justify-end">
|
||||
<SettingResetButton
|
||||
label="appearance theme"
|
||||
onClick={() => setThemeId(DEFAULT_THEME_ID)}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</SettingsSection>
|
||||
|
||||
{/* Section 3: Accent Color */}
|
||||
<SettingsSection title="Accent Color">
|
||||
<div className="px-4 py-4 sm:px-5">
|
||||
<p className="mb-3 text-xs text-muted-foreground">
|
||||
Override the primary color across the app.
|
||||
</p>
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
{/* Default pill */}
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={accentHue === null}
|
||||
className={cn(
|
||||
"rounded-full border px-3 py-1 text-xs font-medium transition-colors",
|
||||
accentHue === null
|
||||
? "border-primary bg-primary/10 text-primary"
|
||||
: "border-border text-muted-foreground hover:border-primary/40",
|
||||
)}
|
||||
onClick={() => setAccentHue(null)}
|
||||
>
|
||||
Default
|
||||
</button>
|
||||
|
||||
{/* Preset circles */}
|
||||
{ACCENT_PRESETS.map((preset) => (
|
||||
<AccentCircle
|
||||
key={preset.name}
|
||||
hue={preset.hue}
|
||||
isSelected={accentHue === preset.hue}
|
||||
label={preset.name}
|
||||
onClick={() => setAccentHue(preset.hue)}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Custom color picker */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="xs"
|
||||
className="relative overflow-hidden"
|
||||
onClick={() => colorInputRef.current?.click()}
|
||||
>
|
||||
Custom
|
||||
<input
|
||||
ref={colorInputRef}
|
||||
type="color"
|
||||
className="absolute inset-0 cursor-pointer opacity-0"
|
||||
onChange={handleCustomAccentChange}
|
||||
tabIndex={-1}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{accentHue !== null ? (
|
||||
<div className="mt-3 flex justify-end">
|
||||
<SettingResetButton label="accent color" onClick={() => setAccentHue(null)} />
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Utilities ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Convert a hex color string to an approximate hue (0-360).
|
||||
* Good enough for a color-picker UX — exact oklch conversion isn't needed.
|
||||
*/
|
||||
function hexToApproxHue(hex: string): number {
|
||||
const r = parseInt(hex.slice(1, 3), 16) / 255;
|
||||
const g = parseInt(hex.slice(3, 5), 16) / 255;
|
||||
const b = parseInt(hex.slice(5, 7), 16) / 255;
|
||||
const max = Math.max(r, g, b);
|
||||
const min = Math.min(r, g, b);
|
||||
const delta = max - min;
|
||||
if (delta === 0) return 0;
|
||||
let hue: number;
|
||||
if (max === r) hue = ((g - b) / delta) % 6;
|
||||
else if (max === g) hue = (b - r) / delta + 2;
|
||||
else hue = (r - g) / delta + 4;
|
||||
hue = Math.round(hue * 60);
|
||||
if (hue < 0) hue += 360;
|
||||
return hue;
|
||||
}
|
||||
@@ -33,6 +33,7 @@ import { ProviderModelPicker } from "../chat/ProviderModelPicker";
|
||||
import { TraitsPicker } from "../chat/TraitsPicker";
|
||||
import { resolveAndPersistPreferredEditor } from "../../editorPreferences";
|
||||
import { isElectron } from "../../env";
|
||||
import { useTheme } from "../../hooks/useTheme";
|
||||
import { useSettings, useUpdateSettings } from "../../hooks/useSettings";
|
||||
import { useThreadActions } from "../../hooks/useThreadActions";
|
||||
import {
|
||||
@@ -59,6 +60,21 @@ import { toastManager } from "../ui/toast";
|
||||
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
|
||||
import { ProjectFavicon } from "../ProjectFavicon";
|
||||
|
||||
const THEME_OPTIONS = [
|
||||
{
|
||||
value: "system",
|
||||
label: "System",
|
||||
},
|
||||
{
|
||||
value: "light",
|
||||
label: "Light",
|
||||
},
|
||||
{
|
||||
value: "dark",
|
||||
label: "Dark",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const TIMESTAMP_FORMAT_LABELS = {
|
||||
locale: "System default",
|
||||
"12-hour": "12-hour",
|
||||
@@ -130,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,
|
||||
@@ -197,7 +214,7 @@ function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsSection({
|
||||
function SettingsSection({
|
||||
title,
|
||||
icon,
|
||||
headerAction,
|
||||
@@ -224,7 +241,7 @@ export function SettingsSection({
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsRow({
|
||||
function SettingsRow({
|
||||
title,
|
||||
description,
|
||||
status,
|
||||
@@ -263,7 +280,7 @@ export function SettingsRow({
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
|
||||
function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
@@ -287,7 +304,7 @@ export function SettingResetButton({ label, onClick }: { label: string; onClick:
|
||||
);
|
||||
}
|
||||
|
||||
export function SettingsPageContainer({ children }: { children: ReactNode }) {
|
||||
function SettingsPageContainer({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto p-6">
|
||||
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6">{children}</div>
|
||||
@@ -423,6 +440,7 @@ function AboutVersionSection() {
|
||||
}
|
||||
|
||||
export function useSettingsRestore(onRestored?: () => void) {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { resetSettings } = useUpdateSettings();
|
||||
|
||||
@@ -438,9 +456,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
|
||||
const changedSettingLabels = useMemo(
|
||||
() => [
|
||||
...(settings.colorMode !== "system" ? ["Color mode"] : []),
|
||||
...(settings.activeThemeId !== "t3code" ? ["Appearance theme"] : []),
|
||||
...(settings.accentHue !== null ? ["Accent color"] : []),
|
||||
...(theme !== "system" ? ["Theme"] : []),
|
||||
...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
|
||||
? ["Time format"]
|
||||
: []),
|
||||
@@ -465,15 +481,13 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
[
|
||||
areProviderSettingsDirty,
|
||||
isGitWritingModelDirty,
|
||||
settings.accentHue,
|
||||
settings.activeThemeId,
|
||||
settings.colorMode,
|
||||
settings.confirmThreadArchive,
|
||||
settings.confirmThreadDelete,
|
||||
settings.defaultThreadEnvMode,
|
||||
settings.diffWordWrap,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.timestampFormat,
|
||||
theme,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -487,9 +501,10 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
setTheme("system");
|
||||
resetSettings();
|
||||
onRestored?.();
|
||||
}, [changedSettingLabels, onRestored, resetSettings]);
|
||||
}, [changedSettingLabels, onRestored, resetSettings, setTheme]);
|
||||
|
||||
return {
|
||||
changedSettingLabels,
|
||||
@@ -498,6 +513,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
const { theme, setTheme } = useTheme();
|
||||
const settings = useSettings();
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const serverConfigQuery = useQuery(serverConfigQueryOptions());
|
||||
@@ -723,6 +739,39 @@ export function GeneralSettingsPanel() {
|
||||
return (
|
||||
<SettingsPageContainer>
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow
|
||||
title="Theme"
|
||||
description="Choose how T3 Code looks across the app."
|
||||
resetAction={
|
||||
theme !== "system" ? (
|
||||
<SettingResetButton label="theme" onClick={() => setTheme("system")} />
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Select
|
||||
value={theme}
|
||||
onValueChange={(value) => {
|
||||
if (value === "system" || value === "light" || value === "dark") {
|
||||
setTheme(value);
|
||||
}
|
||||
}}
|
||||
>
|
||||
<SelectTrigger className="w-full sm:w-40" aria-label="Theme preference">
|
||||
<SelectValue>
|
||||
{THEME_OPTIONS.find((option) => option.value === theme)?.label ?? "System"}
|
||||
</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectPopup align="end" alignItemWithTrigger={false}>
|
||||
{THEME_OPTIONS.map((option) => (
|
||||
<SelectItem hideIndicator key={option.value} value={option.value}>
|
||||
{option.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectPopup>
|
||||
</Select>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
title="Time format"
|
||||
description="System default follows your browser or OS clock preference."
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ComponentType } from "react";
|
||||
import { ArchiveIcon, ArrowLeftIcon, PaletteIcon, Settings2Icon } from "lucide-react";
|
||||
import { ArchiveIcon, ArrowLeftIcon, Settings2Icon } from "lucide-react";
|
||||
import { useNavigate } from "@tanstack/react-router";
|
||||
|
||||
import {
|
||||
@@ -12,10 +12,7 @@ import {
|
||||
SidebarSeparator,
|
||||
} from "../ui/sidebar";
|
||||
|
||||
export type SettingsSectionPath =
|
||||
| "/settings/general"
|
||||
| "/settings/appearance"
|
||||
| "/settings/archived";
|
||||
export type SettingsSectionPath = "/settings/general" | "/settings/archived";
|
||||
|
||||
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
label: string;
|
||||
@@ -23,7 +20,6 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
|
||||
icon: ComponentType<{ className?: string }>;
|
||||
}> = [
|
||||
{ label: "General", to: "/settings/general", icon: Settings2Icon },
|
||||
{ label: "Appearance", to: "/settings/appearance", icon: PaletteIcon },
|
||||
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
|
||||
];
|
||||
|
||||
|
||||
@@ -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,167 +0,0 @@
|
||||
/**
|
||||
* Unified appearance hook — replaces `useTheme`.
|
||||
*
|
||||
* All appearance state (colorMode, activeThemeId, accentHue) is
|
||||
* server-authoritative and pushed to every client via `serverConfigUpdated`.
|
||||
*
|
||||
* A localStorage write-through cache prevents FOUC: module-scope code below
|
||||
* reads the cache synchronously and applies the `.dark` class + theme tokens
|
||||
* before React mounts.
|
||||
*/
|
||||
|
||||
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
|
||||
import type { ColorMode } from "@t3tools/contracts/settings";
|
||||
import type { DesktopAppearance } from "@t3tools/contracts";
|
||||
import { applyThemeTokens, findThemeById, BUILT_IN_THEMES } from "~/lib/themes";
|
||||
import { useSettings, useUpdateSettings } from "./useSettings";
|
||||
|
||||
// ── Constants ────────────────────────────────────────────────────
|
||||
|
||||
const APPEARANCE_CACHE_KEY = "t3code:appearance-cache";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────
|
||||
|
||||
function getSystemDark(): boolean {
|
||||
return window.matchMedia(MEDIA_QUERY).matches;
|
||||
}
|
||||
|
||||
function suppressTransitions(fn: () => void) {
|
||||
document.documentElement.classList.add("no-transitions");
|
||||
fn();
|
||||
// Force reflow so the no-transitions class takes effect before removal
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
});
|
||||
}
|
||||
|
||||
// ── Desktop bridge relay ─────────────────────────────────────────
|
||||
|
||||
let lastDesktopAppearance: string | null = null;
|
||||
|
||||
function syncDesktopAppearance(appearance: DesktopAppearance): void {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge) return;
|
||||
|
||||
const key = JSON.stringify(appearance);
|
||||
if (lastDesktopAppearance === key) return;
|
||||
lastDesktopAppearance = key;
|
||||
|
||||
if (typeof bridge.setAppearance === "function") {
|
||||
void bridge.setAppearance(appearance).catch(() => {
|
||||
if (lastDesktopAppearance === key) lastDesktopAppearance = null;
|
||||
});
|
||||
} else {
|
||||
// Fallback for older Electron builds that only expose setTheme
|
||||
void bridge.setTheme(appearance.mode).catch(() => {
|
||||
if (lastDesktopAppearance === key) lastDesktopAppearance = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── FOUC prevention (module scope — runs before React mounts) ───
|
||||
|
||||
try {
|
||||
const cached = JSON.parse(localStorage.getItem(APPEARANCE_CACHE_KEY) ?? "null") as {
|
||||
colorMode?: string;
|
||||
activeThemeId?: string;
|
||||
accentHue?: number | null;
|
||||
} | null;
|
||||
if (cached) {
|
||||
const isDark =
|
||||
cached.colorMode === "dark" || (cached.colorMode === "system" && getSystemDark());
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
const theme = findThemeById(cached.activeThemeId ?? "t3code");
|
||||
if (theme) applyThemeTokens(theme, cached.accentHue ?? null);
|
||||
}
|
||||
} catch {
|
||||
// Cache unreadable — fall through to React reconciliation.
|
||||
}
|
||||
|
||||
// ── System-dark external store (for "system" mode live updates) ──
|
||||
|
||||
let systemDarkListeners: Array<() => void> = [];
|
||||
let cachedSystemDark: boolean | null = null;
|
||||
|
||||
function getSystemDarkSnapshot(): boolean {
|
||||
if (cachedSystemDark === null) cachedSystemDark = getSystemDark();
|
||||
return cachedSystemDark;
|
||||
}
|
||||
|
||||
function subscribeSystemDark(listener: () => void): () => void {
|
||||
systemDarkListeners.push(listener);
|
||||
const mq = window.matchMedia(MEDIA_QUERY);
|
||||
const handler = () => {
|
||||
cachedSystemDark = mq.matches;
|
||||
for (const l of systemDarkListeners) l();
|
||||
};
|
||||
mq.addEventListener("change", handler);
|
||||
return () => {
|
||||
systemDarkListeners = systemDarkListeners.filter((l) => l !== listener);
|
||||
mq.removeEventListener("change", handler);
|
||||
};
|
||||
}
|
||||
|
||||
// ── Hook ─────────────────────────────────────────────────────────
|
||||
|
||||
export function useAppearance() {
|
||||
const { colorMode, activeThemeId, accentHue } = useSettings((s) => ({
|
||||
colorMode: s.colorMode,
|
||||
activeThemeId: s.activeThemeId,
|
||||
accentHue: s.accentHue,
|
||||
}));
|
||||
const { updateSettings } = useUpdateSettings();
|
||||
const activeTheme = findThemeById(activeThemeId) ?? BUILT_IN_THEMES[0]!;
|
||||
|
||||
// Track system dark preference reactively
|
||||
const systemDark = useSyncExternalStore(subscribeSystemDark, getSystemDarkSnapshot);
|
||||
|
||||
const resolvedTheme: "light" | "dark" = useMemo(
|
||||
() => (colorMode === "system" ? (systemDark ? "dark" : "light") : colorMode),
|
||||
[colorMode, systemDark],
|
||||
);
|
||||
|
||||
// Apply .dark class, theme tokens, cache, and relay to Electron
|
||||
useEffect(() => {
|
||||
suppressTransitions(() => {
|
||||
document.documentElement.classList.toggle("dark", resolvedTheme === "dark");
|
||||
applyThemeTokens(activeTheme, accentHue);
|
||||
});
|
||||
|
||||
// Write-through cache for FOUC prevention on next load
|
||||
localStorage.setItem(
|
||||
APPEARANCE_CACHE_KEY,
|
||||
JSON.stringify({ colorMode, activeThemeId, accentHue }),
|
||||
);
|
||||
|
||||
// Sync to Electron
|
||||
syncDesktopAppearance({ mode: colorMode, themeId: activeThemeId, accentHue });
|
||||
}, [resolvedTheme, activeTheme, accentHue, colorMode, activeThemeId]);
|
||||
|
||||
const setColorMode = useCallback(
|
||||
(mode: ColorMode) => updateSettings({ colorMode: mode }),
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
const setThemeId = useCallback(
|
||||
(id: string) => updateSettings({ activeThemeId: id }),
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
const setAccentHue = useCallback(
|
||||
(hue: number | null) => updateSettings({ accentHue: hue }),
|
||||
[updateSettings],
|
||||
);
|
||||
|
||||
return {
|
||||
colorMode,
|
||||
resolvedTheme,
|
||||
activeTheme,
|
||||
accentHue,
|
||||
setColorMode,
|
||||
setThemeId,
|
||||
setAccentHue,
|
||||
} as const;
|
||||
}
|
||||
@@ -70,7 +70,9 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
|
||||
* only re-render when the slice they care about changes.
|
||||
*/
|
||||
|
||||
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
|
||||
export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
|
||||
selector?: (s: UnifiedSettings) => T,
|
||||
): T {
|
||||
const { data: serverConfig } = useQuery(serverConfigQueryOptions());
|
||||
const [clientSettings] = useLocalStorage(
|
||||
CLIENT_SETTINGS_STORAGE_KEY,
|
||||
@@ -235,20 +237,6 @@ export function buildLegacyClientSettingsMigrationPatch(
|
||||
export function migrateLocalSettingsToServer(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
// Migrate old t3code:theme localStorage key to server colorMode.
|
||||
// This runs independently of OLD_SETTINGS_KEY since the old useTheme hook
|
||||
// wrote t3code:theme separately.
|
||||
try {
|
||||
const oldTheme = localStorage.getItem("t3code:theme");
|
||||
if (oldTheme === "light" || oldTheme === "dark" || oldTheme === "system") {
|
||||
const api = ensureNativeApi();
|
||||
void api.server.updateSettings({ colorMode: oldTheme });
|
||||
localStorage.removeItem("t3code:theme");
|
||||
}
|
||||
} catch {
|
||||
// Best-effort — don't block startup
|
||||
}
|
||||
|
||||
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
|
||||
if (!raw) return;
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { useCallback, useEffect, useSyncExternalStore } from "react";
|
||||
|
||||
type Theme = "light" | "dark" | "system";
|
||||
type ThemeSnapshot = {
|
||||
theme: Theme;
|
||||
systemDark: boolean;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "t3code:theme";
|
||||
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
|
||||
|
||||
let listeners: Array<() => void> = [];
|
||||
let lastSnapshot: ThemeSnapshot | null = null;
|
||||
let lastDesktopTheme: Theme | null = null;
|
||||
function emitChange() {
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function getSystemDark(): boolean {
|
||||
return window.matchMedia(MEDIA_QUERY).matches;
|
||||
}
|
||||
|
||||
function getStored(): Theme {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw === "light" || raw === "dark" || raw === "system") return raw;
|
||||
return "system";
|
||||
}
|
||||
|
||||
function applyTheme(theme: Theme, suppressTransitions = false) {
|
||||
if (suppressTransitions) {
|
||||
document.documentElement.classList.add("no-transitions");
|
||||
}
|
||||
const isDark = theme === "dark" || (theme === "system" && getSystemDark());
|
||||
document.documentElement.classList.toggle("dark", isDark);
|
||||
syncDesktopTheme(theme);
|
||||
if (suppressTransitions) {
|
||||
// Force a reflow so the no-transitions class takes effect before removal
|
||||
// oxlint-disable-next-line no-unused-expressions
|
||||
document.documentElement.offsetHeight;
|
||||
requestAnimationFrame(() => {
|
||||
document.documentElement.classList.remove("no-transitions");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function syncDesktopTheme(theme: Theme) {
|
||||
const bridge = window.desktopBridge;
|
||||
if (!bridge || lastDesktopTheme === theme) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastDesktopTheme = theme;
|
||||
void bridge.setTheme(theme).catch(() => {
|
||||
if (lastDesktopTheme === theme) {
|
||||
lastDesktopTheme = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Apply immediately on module load to prevent flash
|
||||
applyTheme(getStored());
|
||||
|
||||
function getSnapshot(): ThemeSnapshot {
|
||||
const theme = getStored();
|
||||
const systemDark = theme === "system" ? getSystemDark() : false;
|
||||
|
||||
if (lastSnapshot && lastSnapshot.theme === theme && lastSnapshot.systemDark === systemDark) {
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
lastSnapshot = { theme, systemDark };
|
||||
return lastSnapshot;
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.push(listener);
|
||||
|
||||
// Listen for system preference changes
|
||||
const mq = window.matchMedia(MEDIA_QUERY);
|
||||
const handleChange = () => {
|
||||
if (getStored() === "system") applyTheme("system", true);
|
||||
emitChange();
|
||||
};
|
||||
mq.addEventListener("change", handleChange);
|
||||
|
||||
// Listen for storage changes from other tabs
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === STORAGE_KEY) {
|
||||
applyTheme(getStored(), true);
|
||||
emitChange();
|
||||
}
|
||||
};
|
||||
window.addEventListener("storage", handleStorage);
|
||||
|
||||
return () => {
|
||||
listeners = listeners.filter((l) => l !== listener);
|
||||
mq.removeEventListener("change", handleChange);
|
||||
window.removeEventListener("storage", handleStorage);
|
||||
};
|
||||
}
|
||||
|
||||
export function useTheme() {
|
||||
const snapshot = useSyncExternalStore(subscribe, getSnapshot);
|
||||
const theme = snapshot.theme;
|
||||
|
||||
const resolvedTheme: "light" | "dark" =
|
||||
theme === "system" ? (snapshot.systemDark ? "dark" : "light") : theme;
|
||||
|
||||
const setTheme = useCallback((next: Theme) => {
|
||||
localStorage.setItem(STORAGE_KEY, next);
|
||||
applyTheme(next, true);
|
||||
emitChange();
|
||||
}, []);
|
||||
|
||||
// Keep DOM in sync on mount/change
|
||||
useEffect(() => {
|
||||
applyTheme(theme);
|
||||
}, [theme]);
|
||||
|
||||
return { theme, setTheme, resolvedTheme } as const;
|
||||
}
|
||||
@@ -1,206 +0,0 @@
|
||||
/**
|
||||
* Theme definitions, CSS injection, and accent color derivation.
|
||||
*
|
||||
* V1 themes override accent/semantic colors only:
|
||||
* primary, primary-foreground, ring,
|
||||
* destructive, destructive-foreground,
|
||||
* info, info-foreground,
|
||||
* success, success-foreground,
|
||||
* warning, warning-foreground
|
||||
*
|
||||
* Background/surface tokens stay controlled by the CSS baseline in index.css.
|
||||
*/
|
||||
|
||||
// ── Token types ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The set of CSS custom-property names a theme may override.
|
||||
* Uses the unprefixed form (e.g. "primary", not "--color-primary").
|
||||
*/
|
||||
export type ThemeToken =
|
||||
| "primary"
|
||||
| "primary-foreground"
|
||||
| "ring"
|
||||
| "destructive"
|
||||
| "destructive-foreground"
|
||||
| "info"
|
||||
| "info-foreground"
|
||||
| "success"
|
||||
| "success-foreground"
|
||||
| "warning"
|
||||
| "warning-foreground";
|
||||
|
||||
export type ThemeTokenMap = Partial<Record<ThemeToken, string>>;
|
||||
|
||||
export interface ThemeDefinition {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
builtIn: boolean;
|
||||
light: ThemeTokenMap;
|
||||
dark: ThemeTokenMap;
|
||||
}
|
||||
|
||||
// ── Built-in themes ──────────────────────────────────────────────
|
||||
|
||||
const T3CODE_THEME: ThemeDefinition = {
|
||||
id: "t3code",
|
||||
name: "T3Code",
|
||||
description: "Default color palette.",
|
||||
builtIn: true,
|
||||
light: {},
|
||||
dark: {},
|
||||
};
|
||||
|
||||
const HIGH_CONTRAST_THEME: ThemeDefinition = {
|
||||
id: "high-contrast",
|
||||
name: "High Contrast",
|
||||
description: "Boosted contrast for WCAG AAA.",
|
||||
builtIn: true,
|
||||
light: {
|
||||
primary: "oklch(0.35 0.25 264)",
|
||||
"primary-foreground": "oklch(1 0 0)",
|
||||
ring: "oklch(0.35 0.25 264)",
|
||||
destructive: "oklch(0.45 0.28 25)",
|
||||
"destructive-foreground": "oklch(0.30 0.22 25)",
|
||||
info: "oklch(0.45 0.22 250)",
|
||||
"info-foreground": "oklch(0.30 0.18 250)",
|
||||
success: "oklch(0.42 0.20 155)",
|
||||
"success-foreground": "oklch(0.28 0.16 155)",
|
||||
warning: "oklch(0.55 0.22 70)",
|
||||
"warning-foreground": "oklch(0.38 0.18 70)",
|
||||
},
|
||||
dark: {
|
||||
primary: "oklch(0.75 0.22 264)",
|
||||
"primary-foreground": "oklch(0.15 0 0)",
|
||||
ring: "oklch(0.75 0.22 264)",
|
||||
destructive: "oklch(0.72 0.26 25)",
|
||||
"destructive-foreground": "oklch(0.82 0.18 25)",
|
||||
info: "oklch(0.72 0.20 250)",
|
||||
"info-foreground": "oklch(0.82 0.14 250)",
|
||||
success: "oklch(0.72 0.20 155)",
|
||||
"success-foreground": "oklch(0.82 0.14 155)",
|
||||
warning: "oklch(0.78 0.20 70)",
|
||||
"warning-foreground": "oklch(0.86 0.14 70)",
|
||||
},
|
||||
};
|
||||
|
||||
const COLOR_BLIND_THEME: ThemeDefinition = {
|
||||
id: "color-blind",
|
||||
name: "Color Blind",
|
||||
description: "Deuteranopia-safe palette.",
|
||||
builtIn: true,
|
||||
light: {
|
||||
success: "oklch(0.65 0.15 195)",
|
||||
"success-foreground": "oklch(0.45 0.12 195)",
|
||||
warning: "oklch(0.75 0.16 65)",
|
||||
"warning-foreground": "oklch(0.50 0.14 65)",
|
||||
destructive: "oklch(0.55 0.22 350)",
|
||||
"destructive-foreground": "oklch(0.40 0.18 350)",
|
||||
},
|
||||
dark: {
|
||||
success: "oklch(0.70 0.14 195)",
|
||||
"success-foreground": "oklch(0.82 0.10 195)",
|
||||
warning: "oklch(0.78 0.15 65)",
|
||||
"warning-foreground": "oklch(0.86 0.10 65)",
|
||||
destructive: "oklch(0.68 0.20 350)",
|
||||
"destructive-foreground": "oklch(0.82 0.14 350)",
|
||||
},
|
||||
};
|
||||
|
||||
export const BUILT_IN_THEMES: readonly ThemeDefinition[] = [
|
||||
T3CODE_THEME,
|
||||
HIGH_CONTRAST_THEME,
|
||||
COLOR_BLIND_THEME,
|
||||
];
|
||||
|
||||
export const DEFAULT_THEME_ID = "t3code";
|
||||
|
||||
// ── Accent presets ───────────────────────────────────────────────
|
||||
|
||||
export interface AccentPreset {
|
||||
name: string;
|
||||
hue: number;
|
||||
}
|
||||
|
||||
export const ACCENT_PRESETS: readonly AccentPreset[] = [
|
||||
{ name: "Red", hue: 25 },
|
||||
{ name: "Orange", hue: 55 },
|
||||
{ name: "Yellow", hue: 85 },
|
||||
{ name: "Green", hue: 145 },
|
||||
{ name: "Teal", hue: 185 },
|
||||
{ name: "Blue", hue: 240 },
|
||||
{ name: "Purple", hue: 290 },
|
||||
{ name: "Pink", hue: 340 },
|
||||
];
|
||||
|
||||
// ── Lookup ───────────────────────────────────────────────────────
|
||||
|
||||
export function findThemeById(id: string): ThemeDefinition | undefined {
|
||||
return BUILT_IN_THEMES.find((t) => t.id === id);
|
||||
}
|
||||
|
||||
// ── Accent derivation (oklch) ────────────────────────────────────
|
||||
|
||||
export function deriveAccentColors(hue: number): { light: ThemeTokenMap; dark: ThemeTokenMap } {
|
||||
return {
|
||||
light: {
|
||||
primary: `oklch(0.488 0.217 ${hue})`,
|
||||
"primary-foreground": "oklch(1 0 0)",
|
||||
ring: `oklch(0.488 0.217 ${hue})`,
|
||||
},
|
||||
dark: {
|
||||
primary: `oklch(0.588 0.217 ${hue})`,
|
||||
"primary-foreground": "oklch(1 0 0)",
|
||||
ring: `oklch(0.588 0.217 ${hue})`,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ── CSS injection ────────────────────────────────────────────────
|
||||
|
||||
const STYLE_ELEMENT_ID = "t3code-theme-tokens";
|
||||
|
||||
function buildCssBlock(selector: string, tokens: ThemeTokenMap): string {
|
||||
const entries = Object.entries(tokens) as [ThemeToken, string][];
|
||||
if (entries.length === 0) return "";
|
||||
const declarations = entries.map(([token, value]) => ` --color-${token}: ${value};`).join("\n");
|
||||
return `${selector} {\n${declarations}\n}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject or replace a `<style>` element with theme overrides.
|
||||
* When the T3Code default is active with no accent, removes the element entirely.
|
||||
*/
|
||||
export function applyThemeTokens(theme: ThemeDefinition, accentHue: number | null): void {
|
||||
const accent = accentHue != null ? deriveAccentColors(accentHue) : null;
|
||||
|
||||
const lightTokens: ThemeTokenMap = { ...theme.light, ...accent?.light };
|
||||
const darkTokens: ThemeTokenMap = { ...theme.dark, ...accent?.dark };
|
||||
|
||||
const hasOverrides = Object.keys(lightTokens).length > 0 || Object.keys(darkTokens).length > 0;
|
||||
|
||||
if (!hasOverrides) {
|
||||
removeThemeTokens();
|
||||
return;
|
||||
}
|
||||
|
||||
const blocks = [
|
||||
buildCssBlock(":root", lightTokens),
|
||||
buildCssBlock(":root:is(.dark, .dark *)", darkTokens),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
|
||||
let style = document.getElementById(STYLE_ELEMENT_ID) as HTMLStyleElement | null;
|
||||
if (!style) {
|
||||
style = document.createElement("style");
|
||||
style.id = STYLE_ELEMENT_ID;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
style.textContent = blocks;
|
||||
}
|
||||
|
||||
export function removeThemeTokens(): void {
|
||||
document.getElementById(STYLE_ELEMENT_ID)?.remove();
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import { Route as ChatRouteImport } from './routes/_chat'
|
||||
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
|
||||
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
|
||||
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
|
||||
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
|
||||
import { Route as ChatThreadIdRouteImport } from './routes/_chat.$threadId'
|
||||
|
||||
const SettingsRoute = SettingsRouteImport.update({
|
||||
@@ -41,11 +40,6 @@ const SettingsArchivedRoute = SettingsArchivedRouteImport.update({
|
||||
path: '/archived',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({
|
||||
id: '/appearance',
|
||||
path: '/appearance',
|
||||
getParentRoute: () => SettingsRoute,
|
||||
} as any)
|
||||
const ChatThreadIdRoute = ChatThreadIdRouteImport.update({
|
||||
id: '/$threadId',
|
||||
path: '/$threadId',
|
||||
@@ -56,14 +50,12 @@ export interface FileRoutesByFullPath {
|
||||
'/': typeof ChatIndexRoute
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/': typeof ChatIndexRoute
|
||||
@@ -73,7 +65,6 @@ export interface FileRoutesById {
|
||||
'/_chat': typeof ChatRouteWithChildren
|
||||
'/settings': typeof SettingsRouteWithChildren
|
||||
'/_chat/$threadId': typeof ChatThreadIdRoute
|
||||
'/settings/appearance': typeof SettingsAppearanceRoute
|
||||
'/settings/archived': typeof SettingsArchivedRoute
|
||||
'/settings/general': typeof SettingsGeneralRoute
|
||||
'/_chat/': typeof ChatIndexRoute
|
||||
@@ -84,14 +75,12 @@ export interface FileRouteTypes {
|
||||
| '/'
|
||||
| '/settings'
|
||||
| '/$threadId'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/general'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to:
|
||||
| '/settings'
|
||||
| '/$threadId'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/general'
|
||||
| '/'
|
||||
@@ -100,7 +89,6 @@ export interface FileRouteTypes {
|
||||
| '/_chat'
|
||||
| '/settings'
|
||||
| '/_chat/$threadId'
|
||||
| '/settings/appearance'
|
||||
| '/settings/archived'
|
||||
| '/settings/general'
|
||||
| '/_chat/'
|
||||
@@ -148,13 +136,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof SettingsArchivedRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/settings/appearance': {
|
||||
id: '/settings/appearance'
|
||||
path: '/appearance'
|
||||
fullPath: '/settings/appearance'
|
||||
preLoaderRoute: typeof SettingsAppearanceRouteImport
|
||||
parentRoute: typeof SettingsRoute
|
||||
}
|
||||
'/_chat/$threadId': {
|
||||
id: '/_chat/$threadId'
|
||||
path: '/$threadId'
|
||||
@@ -178,13 +159,11 @@ const ChatRouteChildren: ChatRouteChildren = {
|
||||
const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)
|
||||
|
||||
interface SettingsRouteChildren {
|
||||
SettingsAppearanceRoute: typeof SettingsAppearanceRoute
|
||||
SettingsArchivedRoute: typeof SettingsArchivedRoute
|
||||
SettingsGeneralRoute: typeof SettingsGeneralRoute
|
||||
}
|
||||
|
||||
const SettingsRouteChildren: SettingsRouteChildren = {
|
||||
SettingsAppearanceRoute: SettingsAppearanceRoute,
|
||||
SettingsArchivedRoute: SettingsArchivedRoute,
|
||||
SettingsGeneralRoute: SettingsGeneralRoute,
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import { useStore } from "../store";
|
||||
import { useTerminalStateStore } from "../terminalStateStore";
|
||||
import { terminalRunningSubprocessFromEvent } from "../terminalActivity";
|
||||
import { onServerConfigUpdated, onServerProvidersUpdated, onServerWelcome } from "../wsNativeApi";
|
||||
import { useAppearance } from "../hooks/useAppearance";
|
||||
import { migrateLocalSettingsToServer } from "../hooks/useSettings";
|
||||
import { providerQueryKeys } from "../lib/providerReactQuery";
|
||||
import { projectQueryKeys } from "../lib/projectReactQuery";
|
||||
@@ -51,10 +50,6 @@ function RootRouteView() {
|
||||
);
|
||||
}
|
||||
|
||||
// Mount appearance system — drives .dark class, theme tokens, and Electron sync.
|
||||
// The import also triggers module-scope FOUC prevention.
|
||||
useAppearance();
|
||||
|
||||
return (
|
||||
<ToastProvider>
|
||||
<AnchoredToastProvider>
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { createFileRoute } from "@tanstack/react-router";
|
||||
|
||||
import { AppearanceSettingsPanel } from "../components/settings/AppearanceSettingsPanel";
|
||||
|
||||
export const Route = createFileRoute("/settings/appearance")({
|
||||
component: AppearanceSettingsPanel,
|
||||
});
|
||||
@@ -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: [],
|
||||
},
|
||||
|
||||
@@ -73,12 +73,6 @@ export type DesktopUpdateStatus =
|
||||
export type DesktopRuntimeArch = "arm64" | "x64" | "other";
|
||||
export type DesktopTheme = "light" | "dark" | "system";
|
||||
|
||||
export type DesktopAppearance = {
|
||||
mode: DesktopTheme;
|
||||
themeId: string;
|
||||
accentHue: number | null;
|
||||
};
|
||||
|
||||
export interface DesktopRuntimeInfo {
|
||||
hostArch: DesktopRuntimeArch;
|
||||
appArch: DesktopRuntimeArch;
|
||||
@@ -116,9 +110,7 @@ export interface DesktopBridge {
|
||||
getWsUrl: () => string | null;
|
||||
pickFolder: () => Promise<string | null>;
|
||||
confirm: (message: string) => Promise<boolean>;
|
||||
/** @deprecated Use `setAppearance` instead. */
|
||||
setTheme: (theme: DesktopTheme) => Promise<void>;
|
||||
setAppearance: (appearance: DesktopAppearance) => Promise<void>;
|
||||
showContextMenu: <T extends string>(
|
||||
items: readonly ContextMenuItem<T>[],
|
||||
position?: { x: number; y: number },
|
||||
@@ -138,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);
|
||||
});
|
||||
});
|
||||
@@ -39,14 +39,6 @@ export type ClientSettings = typeof ClientSettingsSchema.Type;
|
||||
|
||||
export const DEFAULT_CLIENT_SETTINGS: ClientSettings = Schema.decodeSync(ClientSettingsSchema)({});
|
||||
|
||||
// ── Appearance ──────────────────────────────────────────────────
|
||||
|
||||
export const ColorMode = Schema.Literals(["light", "dark", "system"]);
|
||||
export type ColorMode = typeof ColorMode.Type;
|
||||
export const DEFAULT_COLOR_MODE: ColorMode = "system";
|
||||
|
||||
export const DEFAULT_ACTIVE_THEME_ID = "t3code";
|
||||
|
||||
// ── Server Settings (server-authoritative) ────────────────────
|
||||
|
||||
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
|
||||
@@ -91,13 +83,6 @@ export const ServerSettings = Schema.Struct({
|
||||
})),
|
||||
),
|
||||
|
||||
// Appearance
|
||||
colorMode: ColorMode.pipe(
|
||||
Schema.withDecodingDefault(() => "system" as const satisfies ColorMode),
|
||||
),
|
||||
activeThemeId: Schema.String.pipe(Schema.withDecodingDefault(() => DEFAULT_ACTIVE_THEME_ID)),
|
||||
accentHue: Schema.NullOr(Schema.Number).pipe(Schema.withDecodingDefault(() => null)),
|
||||
|
||||
// Provider specific settings
|
||||
providers: Schema.Struct({
|
||||
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
|
||||
@@ -127,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([
|
||||
@@ -159,9 +145,6 @@ export const ServerSettingsPatch = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
|
||||
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
|
||||
colorMode: Schema.optionalKey(ColorMode),
|
||||
activeThemeId: Schema.optionalKey(Schema.String),
|
||||
accentHue: Schema.optionalKey(Schema.NullOr(Schema.Number)),
|
||||
providers: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
codex: Schema.optionalKey(CodexSettingsPatch),
|
||||
|
||||
@@ -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