Compare commits

..
Author SHA1 Message Date
Julius Marminge 88cb025815 Drop translucent sidebar theme setting
- Remove sidebar translucency from theme contracts and presets
- Always render the sidebar opaque in the web app
2026-03-31 00:20:32 -07:00
Julius Marminge adeed26289 Simplify appearance settings layout
- Tighten theme cards, controls, and section spacing
- Remove the import format section and reduce copy in the theme editor
2026-03-31 00:07:17 -07:00
Julius Marminge b907346122 Make sidebar border transparent in built-in themes
- Set built-in theme sidebar borders to `transparent`
- Update token derivation tests to assert the new sidebar border value
2026-03-30 14:14:48 -07:00
Julius Marminge e5de3d0c8c Add customizable appearance themes
- Replace single-theme settings with light and dark theme libraries
- Persist custom theme definitions and add import, copy, duplicate, and reset flows
- Update shared appearance contracts, UI, and tests
2026-03-30 13:31:03 -07:00
Julius Marminge 973ab3232f Refine appearance theme token handling
- Apply theme overrides as inline CSS variables
- Add diff-specific tokens and color-blind diff palette
- Update swatches and diff stats to use new semantic colors
2026-03-29 13:48:29 -07:00
Julius Marminge ed4c9ebd8c Fix theme token overrides and mount appearance early
- Write theme CSS variables at the intermediate token level so Tailwind picks them up
- Call `useAppearance()` before the root route can return early to satisfy Hooks rules
2026-03-29 12:30:28 -07:00
Julius Marminge f4ab7ebe21 Add appearance settings and theme system
- Move theme control into a dedicated appearance settings panel
- Add built-in themes, accent overrides, and desktop IPC sync
- Migrate settings and update components to use unified appearance state
2026-03-29 11:49:29 -07:00
103 changed files with 6014 additions and 9618 deletions

No files matched your search

+4 -28
View File
@@ -2,42 +2,18 @@
T3 Code is a minimal web GUI for coding agents (currently Codex and Claude, more coming soon).
## Installation
## How to use
> [!WARNING]
> 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
> You need to have [Codex CLI](https://github.com/openai/codex) installed and authorized for T3 Code to work.
```bash
npx t3
```
### Desktop app
You can also just install the desktop app. It's cooler.
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
```
Install the [desktop app from the Releases page](https://github.com/pingdotgg/t3code/releases)
## Some notes
+1 -1
View File
@@ -14,7 +14,7 @@ export async function showDesktopConfirmDialog(
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
defaultId: CONFIRM_BUTTON_INDEX,
cancelId: 0,
noLink: true,
message: normalizedMessage,
+11
View File
@@ -50,6 +50,7 @@ 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";
@@ -1160,6 +1161,16 @@ 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 is available for future Electron shell styling work.
});
ipcMain.removeHandler(CONTEXT_MENU_CHANNEL);
ipcMain.handle(
CONTEXT_MENU_CHANNEL,
+2
View File
@@ -4,6 +4,7 @@ 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";
@@ -22,6 +23,7 @@ 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) => {
+1
View File
@@ -29,6 +29,7 @@
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0"
},
"devDependencies": {
+2 -25
View File
@@ -310,7 +310,7 @@ describe("readCodexAccountSnapshot", () => {
});
});
it("disables spark for api key accounts", () => {
it("keeps spark enabled for api key accounts", () => {
expect(
readCodexAccountSnapshot({
type: "apiKey",
@@ -318,20 +318,7 @@ describe("readCodexAccountSnapshot", () => {
).toEqual({
type: "apiKey",
planType: null,
sparkEnabled: false,
});
});
it("disables spark for unknown chatgpt plans", () => {
expect(
readCodexAccountSnapshot({
type: "chatgpt",
email: "[email protected]",
}),
).toEqual({
type: "chatgpt",
planType: "unknown",
sparkEnabled: false,
sparkEnabled: true,
});
});
});
@@ -356,16 +343,6 @@ 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", () => {
+94 -10
View File
@@ -26,15 +26,6 @@ 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;
@@ -105,6 +96,23 @@ 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;
@@ -154,6 +162,50 @@ 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.
@@ -306,13 +358,32 @@ 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 {
killCodexChildProcess(child);
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();
}
export function normalizeCodexModelSlug(
@@ -331,6 +402,19 @@ 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,9 +29,8 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { normalizeClaudeModelOptionsWithCapabilities } from "@t3tools/shared/model";
import { normalizeClaudeModelOptions } from "../../provider/Layers/ClaudeProvider.ts";
import { ServerSettingsService } from "../../serverSettings.ts";
import { getClaudeModelCapabilities } from "../../provider/Layers/ClaudeProvider.ts";
const CLAUDE_TIMEOUT_MS = 180_000;
@@ -85,8 +84,8 @@ const makeClaudeTextGeneration = Effect.gen(function* () {
}): Effect.Effect<S["Type"], TextGenerationError, S["DecodingServices"]> =>
Effect.gen(function* () {
const jsonSchemaStr = JSON.stringify(toJsonSchemaObject(outputSchemaJson));
const normalizedOptions = normalizeClaudeModelOptionsWithCapabilities(
getClaudeModelCapabilities(modelSelection.model),
const normalizedOptions = normalizeClaudeModelOptions(
modelSelection.model,
modelSelection.options,
);
const settings = {
@@ -28,9 +28,8 @@ import {
sanitizeThreadTitle,
toJsonSchemaObject,
} from "../Utils.ts";
import { getCodexModelCapabilities } from "../../provider/Layers/CodexProvider.ts";
import { normalizeCodexModelOptions } 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;
@@ -157,8 +156,8 @@ const makeCodexTextGeneration = Effect.gen(function* () {
).pipe(Effect.catch(() => Effect.undefined));
const runCodexCommand = Effect.gen(function* () {
const normalizedOptions = normalizeCodexModelOptionsWithCapabilities(
getCodexModelCapabilities(modelSelection.model),
const normalizedOptions = normalizeCodexModelOptions(
modelSelection.model,
modelSelection.options,
);
const reasoningEffort =
-2
View File
@@ -51,8 +51,6 @@ const testLayer = Layer.mergeAll(
stopSignal: Effect.void,
} satisfies ServerShape),
Layer.succeed(Open, {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: (_target: string) => Effect.void,
openInEditor: () => Effect.void,
} satisfies OpenShape),
+252 -541
View File
@@ -1,558 +1,269 @@
import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
import * as NodePath from "@effect/platform-node/NodePath";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import { assertSuccess } from "@effect/vitest/utils";
import { FileSystem, Path, Effect } from "effect";
import {
Deferred,
Effect,
Exit,
FileSystem,
Layer,
PlatformError,
Scope,
Sink,
Stream,
} from "effect";
import { ChildProcessSpawner } from "effect/unstable/process";
isCommandAvailable,
launchDetached,
resolveAvailableEditors,
resolveEditorLaunch,
} from "./open";
import { makeOpenLayer, Open } from "./open";
const encoder = new TextEncoder();
interface SpawnCall {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly detached?: boolean | undefined;
readonly shell?: boolean | string | undefined;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
}
function decodePowerShellCommand(encoded: string): string {
return Buffer.from(encoded, "base64").toString("utf16le");
}
function platformSpawnError(message: string) {
return PlatformError.systemError({
_tag: "Unknown",
module: "ChildProcess",
method: "spawn",
description: message,
});
}
function spawnerLayer(
calls: Array<SpawnCall>,
handler: (call: SpawnCall) => {
readonly code?: number;
readonly fail?: string;
readonly awaitExit?: Deferred.Deferred<void>;
readonly onKill?: () => void;
} = () => ({
code: 0,
}),
) {
return Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const standardCommand = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly options: {
readonly detached?: boolean;
readonly shell?: boolean | string;
readonly stdin?: unknown;
readonly stdout?: unknown;
readonly stderr?: unknown;
};
};
const call: SpawnCall = {
command: standardCommand.command,
args: [...standardCommand.args],
detached: standardCommand.options.detached,
shell: standardCommand.options.shell,
stdin: standardCommand.options.stdin,
stdout: standardCommand.options.stdout,
stderr: standardCommand.options.stderr,
};
calls.push(call);
const result = handler(call);
if (result.fail) {
return Effect.fail(platformSpawnError(result.fail));
}
let exited = false;
const exitCode = result.awaitExit
? Deferred.await(result.awaitExit).pipe(
Effect.tap(() =>
Effect.sync(() => {
exited = true;
}),
),
Effect.andThen(Effect.succeed(ChildProcessSpawner.ExitCode(result.code ?? 0))),
)
: Effect.sync(() => {
exited = true;
return ChildProcessSpawner.ExitCode(result.code ?? 0);
});
return Effect.succeed(
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(calls.length),
exitCode,
isRunning: Effect.succeed(false),
kill: () =>
Effect.sync(() => {
if (!exited) {
result.onKill?.();
}
}),
stdin: Sink.drain,
stdout: Stream.make(encoder.encode("")),
stderr: Stream.make(encoder.encode("")),
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
}),
it.layer(NodeServices.layer)("resolveEditorLaunch", (it) => {
it.effect("returns commands for command-based editors", () =>
Effect.gen(function* () {
const antigravityLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "antigravity" },
"darwin",
);
assert.deepEqual(antigravityLaunch, {
command: "agy",
args: ["/tmp/workspace"],
});
const cursorLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "cursor" },
"darwin",
);
assert.deepEqual(cursorLaunch, {
command: "cursor",
args: ["/tmp/workspace"],
});
const vscodeLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLaunch, {
command: "code",
args: ["/tmp/workspace"],
});
const vscodeInsidersLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLaunch, {
command: "code-insiders",
args: ["/tmp/workspace"],
});
const vscodiumLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLaunch, {
command: "codium",
args: ["/tmp/workspace"],
});
const zedLaunch = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLaunch, {
command: "zed",
args: ["/tmp/workspace"],
});
}),
);
}
const provideOpen = (
options: Parameters<typeof makeOpenLayer>[0],
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
) =>
makeOpenLayer(options).pipe(
Layer.provide(Layer.mergeAll(NodeFileSystem.layer, NodePath.layer, spawnLayer)),
it.effect("uses --goto when editor supports line/column suffixes", () =>
Effect.gen(function* () {
const lineOnly = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/AGENTS.md:48", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineOnly, {
command: "cursor",
args: ["--goto", "/tmp/workspace/AGENTS.md:48"],
});
const lineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "cursor" },
"darwin",
);
assert.deepEqual(lineAndColumn, {
command: "cursor",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode" },
"darwin",
);
assert.deepEqual(vscodeLineAndColumn, {
command: "code",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodeInsidersLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscode-insiders" },
"darwin",
);
assert.deepEqual(vscodeInsidersLineAndColumn, {
command: "code-insiders",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const vscodiumLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "vscodium" },
"darwin",
);
assert.deepEqual(vscodiumLineAndColumn, {
command: "codium",
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
});
const zedLineAndColumn = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace/src/open.ts:71:5", editor: "zed" },
"darwin",
);
assert.deepEqual(zedLineAndColumn, {
command: "zed",
args: ["/tmp/workspace/src/open.ts:71:5"],
});
}),
);
const runOpen = <A>(
options: Parameters<typeof makeOpenLayer>[0],
spawnLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner>,
effect: Effect.Effect<A, Error, Open>,
) => effect.pipe(Effect.provide(provideOpen(options, spawnLayer)));
it.effect("maps file-manager editor to OS open commands", () =>
Effect.gen(function* () {
const launch1 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"darwin",
);
assert.deepEqual(launch1, {
command: "open",
args: ["/tmp/workspace"],
});
const readOpen = Effect.service(Open);
const launch2 = yield* resolveEditorLaunch(
{ cwd: "C:\\workspace", editor: "file-manager" },
"win32",
);
assert.deepEqual(launch2, {
command: "explorer",
args: ["C:\\workspace"],
});
const writeExecutable = (filePath: string) =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
yield* fs.writeFileString(filePath, "#!/bin/sh\nexit 0\n");
yield* fs.chmod(filePath, 0o755);
const launch3 = yield* resolveEditorLaunch(
{ cwd: "/tmp/workspace", editor: "file-manager" },
"linux",
);
assert.deepEqual(launch3, {
command: "xdg-open",
args: ["/tmp/workspace"],
});
}),
);
});
it.layer(NodeServices.layer)("launchDetached", (it) => {
it.effect("resolves when command can be spawned", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: process.execPath,
args: ["-e", "process.exit(0)"],
}).pipe(Effect.result);
assertSuccess(result, undefined);
}),
);
it.effect("rejects when command does not exist", () =>
Effect.gen(function* () {
const result = yield* launchDetached({
command: `t3code-no-such-command-${Date.now()}`,
args: [],
}).pipe(Effect.result);
assert.equal(result._tag, "Failure");
}),
);
});
it.layer(NodeServices.layer)("isCommandAvailable", (it) => {
it.effect("resolves win32 commands with PATHEXT", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "code.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
it("returns false when a command is not on PATH", () => {
const env = {
PATH: "",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("definitely-not-installed", { platform: "win32", env }), false);
});
it.effect("getAvailableEditors detects installed editors through the service", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-editors-" });
yield* fs.writeFileString(`${dir}/code-insiders.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/codium.CMD`, "@echo off\r\n");
yield* fs.writeFileString(`${dir}/explorer.CMD`, "@echo off\r\n");
it.effect("does not treat bare files without executable extension as available on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "npm"), "echo nope\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("npm", { platform: "win32", env }), false);
}),
);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
it.effect("appends PATHEXT for commands with non-executable extensions on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(dir, "my.tool.CMD"), "@echo off\r\n");
const env = {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("my.tool", { platform: "win32", env }), true);
}),
);
const editors = yield* open.getAvailableEditors;
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("uses platform-specific PATH delimiter for platform overrides", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const firstDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
const secondDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-test-" });
yield* fs.writeFileString(path.join(firstDir, "code.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(secondDir, "code.CMD"), "MZ");
const env = {
PATH: `${firstDir};${secondDir}`,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
} satisfies NodeJS.ProcessEnv;
assert.equal(isCommandAvailable("code", { platform: "win32", env }), true);
}),
);
});
it.effect("getAvailableEditors does not advertise WSL file-manager from PowerShell alone", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-editors-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
it.layer(NodeServices.layer)("resolveAvailableEditors", (it) => {
it.effect("returns installed editors for command launches", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-editors-" });
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls),
readOpen,
);
const editors = yield* open.getAvailableEditors;
assert.equal(editors.includes("file-manager"), false);
assert.deepEqual(calls, []);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses --goto for editors that support it", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-cursor-" });
yield* writeExecutable(`${dir}/cursor`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace/src/open.ts:71:5",
editor: "cursor",
});
assert.deepEqual(calls, [
{
command: `${dir}/cursor`,
args: ["--goto", "/tmp/workspace/src/open.ts:71:5"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor launches Windows batch shims through cmd.exe without shell mode", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-vscode-win32-" });
yield* fs.writeFileString(`${dir}/code.cmd`, "@echo off\r\n");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "C:\\work\\100% real\\file.ts:12:4",
editor: "vscode",
});
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command, "cmd.exe");
assert.deepEqual(calls[0]?.args.slice(0, 4), ["/d", "/v:off", "/s", "/c"]);
assert.equal(calls[0]?.args[4]?.toLowerCase().includes(`${dir}/code.cmd`.toLowerCase()), true);
assert.equal(calls[0]?.args[4]?.includes('"--goto"'), true);
assert.equal(calls[0]?.args[4]?.includes("100%% real"), true);
assert.equal(calls[0]?.detached, true);
assert.equal(calls[0]?.shell, false);
assert.equal(calls[0]?.stdin, "ignore");
assert.equal(calls[0]?.stdout, "ignore");
assert.equal(calls[0]?.stderr, "ignore");
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor detached launches survive service scope shutdown", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-zed-detached-" });
yield* writeExecutable(`${dir}/zed`);
const calls: Array<SpawnCall> = [];
const exitDeferred = yield* Deferred.make<void>();
let killCount = 0;
yield* Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const runtimeServices = yield* Layer.build(
provideOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls, () => ({
awaitExit: exitDeferred,
onKill: () => {
killCount += 1;
},
})),
),
).pipe(Scope.provide(scope));
const open = yield* readOpen.pipe(Effect.provide(runtimeServices), Scope.provide(scope));
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "zed",
});
}),
(scope) => Scope.close(scope, Exit.void),
);
assert.equal(killCount, 0);
assert.deepEqual(calls, [
{
command: `${dir}/zed`,
args: ["/tmp/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
yield* Deferred.succeed(exitDeferred, void 0);
yield* Effect.yieldNow;
assert.equal(killCount, 0);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses the default opener for file-manager on macOS", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/tmp/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: ["/tmp/workspace"],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses macOS open flags and app arguments", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-macos-" });
yield* writeExecutable(`${dir}/open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: dir },
},
spawnerLayer(calls),
readOpen,
);
yield* open.openBrowser("https://example.com", {
wait: true,
background: true,
newInstance: true,
app: {
name: "google chrome",
arguments: ["--profile-directory=Work"],
},
});
assert.deepEqual(calls, [
{
command: `${dir}/open`,
args: [
"--wait-apps",
"--background",
"--new",
"-a",
"google chrome",
"https://example.com",
"--args",
"--profile-directory=Work",
],
detached: undefined,
shell: false,
stdin: undefined,
stdout: undefined,
stderr: undefined,
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser uses PowerShell on win32", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-win32-" });
yield* fs.writeFileString(`${dir}/powershell.exe`, "MZ");
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "win32",
env: {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
},
spawnerLayer(calls),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls.length, 1);
assert.equal(calls[0]?.command, `${dir}/powershell.exe`);
assert.equal(calls[0]?.args.at(-2), "-EncodedCommand");
assert.equal(
decodePowerShellCommand(calls[0]?.args.at(-1) ?? ""),
"Start 'https://example.com'",
);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openBrowser falls back from WSL PowerShell to xdg-open", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-browser-wsl-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls, (call) =>
call.command.includes("powershell")
? { fail: "powershell unavailable" }
: {
code: 0,
},
),
readOpen,
);
yield* open.openBrowser("https://example.com");
assert.equal(calls[0]?.command.includes("powershell"), true);
assert.equal(calls[1]?.command, `${dir}/xdg-open`);
assert.deepEqual(calls[1]?.args, ["https://example.com"]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor uses xdg-open first for WSL file-manager paths", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-open-wsl-file-manager-" });
yield* fs.makeDirectory(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`, {
recursive: true,
});
yield* writeExecutable(`${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`);
yield* writeExecutable(`${dir}/xdg-open`);
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "linux",
env: {
PATH: `${dir}:${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0`,
WSL_DISTRO_NAME: "Ubuntu",
},
isWsl: true,
isInsideContainer: false,
powerShellCommand: `${dir}/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`,
},
spawnerLayer(calls),
readOpen,
);
yield* open.openInEditor({
cwd: "/home/julius/workspace",
editor: "file-manager",
});
assert.deepEqual(calls, [
{
command: `${dir}/xdg-open`,
args: ["/home/julius/workspace"],
detached: true,
shell: false,
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
]);
}).pipe(Effect.provide(NodeFileSystem.layer)),
);
it.effect("openInEditor fails when the editor command is unavailable", () =>
Effect.gen(function* () {
const calls: Array<SpawnCall> = [];
const open = yield* runOpen(
{
platform: "darwin",
env: { PATH: "" },
},
spawnerLayer(calls),
readOpen,
);
const error = yield* open
.openInEditor({
cwd: "/tmp/workspace",
editor: "cursor",
})
.pipe(Effect.flip);
assert.equal(error._tag, "OpenError");
assert.equal(error.message, "Command not found: cursor");
assert.deepEqual(calls, []);
}),
);
yield* fs.writeFileString(path.join(dir, "code-insiders.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "codium.CMD"), "@echo off\r\n");
yield* fs.writeFileString(path.join(dir, "explorer.CMD"), "MZ");
const editors = resolveAvailableEditors("win32", {
PATH: dir,
PATHEXT: ".COM;.EXE;.BAT;.CMD",
});
assert.deepEqual(editors, ["vscode-insiders", "vscodium", "file-manager"]);
}),
);
});
+170 -574
View File
@@ -1,17 +1,21 @@
/**
* Open - Browser/editor launch service interface.
*
* Owns process launch helpers for opening URLs in a browser, workspace paths in
* a configured editor, and generic external targets through the platform's
* default opener.
* Owns process launch helpers for opening URLs in a browser and workspace
* paths in a configured editor.
*
* @module Open
*/
import os from "node:os";
import { spawn } from "node:child_process";
import { accessSync, constants, statSync } from "node:fs";
import { extname, join } from "node:path";
import { EDITORS, type EditorId } from "@t3tools/contracts";
import { Effect, Exit, FileSystem, Layer, Option, Path, Schema, Scope, ServiceMap } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { ServiceMap, Schema, Effect, Layer } from "effect";
// ==============================
// Definitions
// ==============================
export class OpenError extends Schema.TaggedErrorClass<OpenError>()("OpenError", {
message: Schema.String,
@@ -23,66 +27,33 @@ export interface OpenInEditorInput {
readonly editor: EditorId;
}
export interface OpenApplicationInput {
readonly name: string | ReadonlyArray<string>;
readonly arguments?: ReadonlyArray<string>;
}
export interface OpenExternalInput {
readonly target: string;
readonly wait?: boolean;
readonly background?: boolean;
readonly newInstance?: boolean;
readonly allowNonzeroExitCode?: boolean;
readonly app?: OpenApplicationInput | ReadonlyArray<OpenApplicationInput>;
}
export interface OpenRuntimeOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
readonly isWsl?: boolean;
readonly isInsideContainer?: boolean;
readonly powerShellCommand?: string;
}
interface OpenRuntime {
readonly platform: NodeJS.Platform;
readonly env: NodeJS.ProcessEnv;
readonly isWsl: boolean;
readonly isInsideContainer: boolean;
readonly powerShellCandidates: ReadonlyArray<string>;
readonly windowsPathExtensions: ReadonlyArray<string>;
}
interface LaunchPlan {
interface EditorLaunch {
readonly command: string;
readonly args: ReadonlyArray<string>;
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
}
interface ResolvedCommand {
readonly path: string;
readonly usesCmdWrapper: boolean;
interface CommandAvailabilityOptions {
readonly platform?: NodeJS.Platform;
readonly env?: NodeJS.ProcessEnv;
}
const LINE_COLUMN_SUFFIX_PATTERN = /:\d+(?::\d+)?$/;
const WINDOWS_POWERSHELL_CANDIDATES = ["powershell.exe", "powershell", "pwsh.exe", "pwsh"] as const;
const WSL_POWERSHELL_CANDIDATES = [
"/mnt/c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe",
"/mnt/c/Program Files/PowerShell/7/pwsh.exe",
"powershell.exe",
"pwsh.exe",
] as const;
const WINDOWS_BATCH_EXTENSIONS = [".CMD", ".BAT"] as const;
function shouldUseGotoFlag(editor: (typeof EDITORS)[number], target: string): boolean {
return editor.supportsGoto && LINE_COLUMN_SUFFIX_PATTERN.test(target);
}
function fileManagerCommandForPlatform(platform: NodeJS.Platform): string {
switch (platform) {
case "darwin":
return "open";
case "win32":
return "explorer";
default:
return "xdg-open";
}
}
function stripWrappingQuotes(value: string): string {
return value.replace(/^"+|"+$/g, "");
}
@@ -101,24 +72,19 @@ function resolveWindowsPathExtensions(env: NodeJS.ProcessEnv): ReadonlyArray<str
.map((entry) => entry.trim())
.filter((entry) => entry.length > 0)
.map((entry) => (entry.startsWith(".") ? entry.toUpperCase() : `.${entry.toUpperCase()}`));
return parsed.length > 0 ? Array.from(new Set(parsed)) : fallback;
}
function resolveWindowsCommandShell(env: NodeJS.ProcessEnv): string {
return env.ComSpec ?? env.COMSPEC ?? "cmd.exe";
}
function resolveCommandCandidates(
command: string,
runtime: OpenRuntime,
pathService: Path.Path,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): ReadonlyArray<string> {
if (runtime.platform !== "win32") return [command];
const extension = pathService.extname(command);
if (platform !== "win32") return [command];
const extension = extname(command);
const normalizedExtension = extension.toUpperCase();
if (extension.length > 0 && runtime.windowsPathExtensions.includes(normalizedExtension)) {
if (extension.length > 0 && windowsPathExtensions.includes(normalizedExtension)) {
const commandWithoutExtension = command.slice(0, -extension.length);
return Array.from(
new Set([
@@ -130,549 +96,179 @@ function resolveCommandCandidates(
}
const candidates: string[] = [];
for (const extensionName of runtime.windowsPathExtensions) {
candidates.push(`${command}${extensionName}`);
candidates.push(`${command}${extensionName.toLowerCase()}`);
for (const extension of windowsPathExtensions) {
candidates.push(`${command}${extension}`);
candidates.push(`${command}${extension.toLowerCase()}`);
}
return Array.from(new Set(candidates));
}
function isExecutableFile(
filePath: string,
platform: NodeJS.Platform,
windowsPathExtensions: ReadonlyArray<string>,
): boolean {
try {
const stat = statSync(filePath);
if (!stat.isFile()) return false;
if (platform === "win32") {
const extension = extname(filePath);
if (extension.length === 0) return false;
return windowsPathExtensions.includes(extension.toUpperCase());
}
accessSync(filePath, constants.X_OK);
return true;
} catch {
return false;
}
}
function resolvePathDelimiter(platform: NodeJS.Platform): string {
return platform === "win32" ? ";" : ":";
}
function detectWsl(platform: NodeJS.Platform, env: NodeJS.ProcessEnv): boolean {
if (platform !== "linux") return false;
if (typeof env.WSL_DISTRO_NAME === "string" || typeof env.WSL_INTEROP === "string") {
return true;
}
return os.release().toLowerCase().includes("microsoft");
}
function quotePowerShellValue(value: string): string {
return `'${value.replaceAll("'", "''")}'`;
}
function encodePowerShellCommand(command: string): string {
return Buffer.from(command, "utf16le").toString("base64");
}
function normalizeAppCandidates(
app: OpenExternalInput["app"],
): ReadonlyArray<{ readonly name: string; readonly arguments: ReadonlyArray<string> } | undefined> {
if (!app) return [undefined];
const apps = Array.isArray(app) ? app : [app];
const candidates: Array<{ readonly name: string; readonly arguments: ReadonlyArray<string> }> =
[];
for (const appDef of apps) {
const names = Array.isArray(appDef.name) ? appDef.name : [appDef.name];
for (const name of names) {
candidates.push({ name, arguments: appDef.arguments ?? [] });
}
}
return candidates;
}
function isUriLikeTarget(target: string): boolean {
return /^[A-Za-z][A-Za-z\d+.-]*:/.test(target);
}
function shouldPreferWindowsOpenerOnWsl(input: OpenExternalInput, runtime: OpenRuntime): boolean {
return runtime.isWsl && !runtime.isInsideContainer && isUriLikeTarget(input.target);
}
function makeLaunchPlan(
export function isCommandAvailable(
command: string,
args: ReadonlyArray<string>,
options: {
readonly wait: boolean;
readonly allowNonzeroExitCode: boolean;
readonly detached?: boolean;
readonly shell?: boolean;
readonly stdio?: "ignore";
},
): LaunchPlan {
return {
command,
args,
wait: options.wait,
allowNonzeroExitCode: options.allowNonzeroExitCode,
shell: options.shell ?? false,
...(options.detached !== undefined ? { detached: options.detached } : {}),
...(options.stdio !== undefined ? { stdio: options.stdio } : {}),
};
}
options: CommandAvailabilityOptions = {},
): boolean {
const platform = options.platform ?? process.platform;
const env = options.env ?? process.env;
const windowsPathExtensions = platform === "win32" ? resolveWindowsPathExtensions(env) : [];
const commandCandidates = resolveCommandCandidates(command, platform, windowsPathExtensions);
function makeDarwinDefaultPlan(input: OpenExternalInput): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push(input.target);
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function makeDarwinApplicationPlan(
input: OpenExternalInput,
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
): LaunchPlan {
const args: string[] = [];
const wait = input.wait ?? false;
if (wait) args.push("--wait-apps");
if (input.background) args.push("--background");
if (input.newInstance) args.push("--new");
args.push("-a", app.name);
args.push(input.target);
if (app.arguments.length > 0) {
args.push("--args", ...app.arguments);
if (command.includes("/") || command.includes("\\")) {
return commandCandidates.some((candidate) =>
isExecutableFile(candidate, platform, windowsPathExtensions),
);
}
return makeLaunchPlan("open", args, {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
const pathValue = resolvePathEnvironmentVariable(env);
if (pathValue.length === 0) return false;
const pathEntries = pathValue
.split(resolvePathDelimiter(platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
function makePowerShellPlan(input: OpenExternalInput, powerShellCommand: string): LaunchPlan {
const encodedParts = ["Start"];
const wait = input.wait ?? false;
if (wait) encodedParts.push("-Wait");
encodedParts.push(quotePowerShellValue(input.target));
return makeLaunchPlan(
powerShellCommand,
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-EncodedCommand",
encodePowerShellCommand(encodedParts.join(" ")),
],
{
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
},
);
}
function makeLinuxDefaultPlan(input: OpenExternalInput): LaunchPlan {
const wait = input.wait ?? false;
return makeLaunchPlan("xdg-open", [input.target], {
wait,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
detached: !wait,
...(wait ? {} : { stdio: "ignore" as const }),
shell: false,
});
}
function makeWindowsExplorerPlan(input: OpenExternalInput): LaunchPlan {
return makeLaunchPlan("explorer", [input.target], {
wait: false,
allowNonzeroExitCode: false,
shell: false,
});
}
function makeDirectApplicationPlan(
input: OpenExternalInput,
app: { readonly name: string; readonly arguments: ReadonlyArray<string> },
): LaunchPlan {
return makeLaunchPlan(app.name, [...app.arguments, input.target], {
wait: input.wait ?? false,
allowNonzeroExitCode: input.allowNonzeroExitCode ?? false,
shell: false,
});
}
function resolveExternalPlans(
input: OpenExternalInput,
runtime: OpenRuntime,
): ReadonlyArray<LaunchPlan> {
const appCandidates = normalizeAppCandidates(input.app);
const plans: LaunchPlan[] = [];
const preferWindowsOpenerOnWsl = shouldPreferWindowsOpenerOnWsl(input, runtime);
for (const app of appCandidates) {
if (app) {
if (runtime.platform === "darwin") {
plans.push(makeDarwinApplicationPlan(input, app));
} else {
plans.push(makeDirectApplicationPlan(input, app));
}
continue;
}
if (runtime.platform === "darwin") {
plans.push(makeDarwinDefaultPlan(input));
continue;
}
if (runtime.platform === "win32" || preferWindowsOpenerOnWsl) {
for (const powerShellCommand of runtime.powerShellCandidates) {
plans.push(makePowerShellPlan(input, powerShellCommand));
for (const pathEntry of pathEntries) {
for (const candidate of commandCandidates) {
if (isExecutableFile(join(pathEntry, candidate), platform, windowsPathExtensions)) {
return true;
}
}
}
return false;
}
if (runtime.platform === "win32") {
if (!(input.wait ?? false)) {
plans.push(makeWindowsExplorerPlan(input));
}
continue;
export function resolveAvailableEditors(
platform: NodeJS.Platform = process.platform,
env: NodeJS.ProcessEnv = process.env,
): ReadonlyArray<EditorId> {
const available: EditorId[] = [];
for (const editor of EDITORS) {
const command = editor.command ?? fileManagerCommandForPlatform(platform);
if (isCommandAvailable(command, { platform, env })) {
available.push(editor.id);
}
plans.push(makeLinuxDefaultPlan(input));
}
return plans;
}
function toOpenError(message: string, cause: unknown): OpenError {
return new OpenError({ message, cause });
}
function isWindowsBatchShim(pathService: Path.Path, filePath: string): boolean {
return WINDOWS_BATCH_EXTENSIONS.includes(pathService.extname(filePath).toUpperCase() as never);
}
function quoteForWindowsCmd(value: string): string {
return `"${value.replaceAll("%", "%%").replaceAll('"', '""')}"`;
}
function makeWindowsCmdCommandLine(commandPath: string, args: ReadonlyArray<string>): string {
return `"${[commandPath, ...args].map(quoteForWindowsCmd).join(" ")}"`;
return available;
}
/**
* OpenShape - Service API for browser and editor launch actions.
*/
export interface OpenShape {
readonly getAvailableEditors: Effect.Effect<ReadonlyArray<EditorId>, OpenError>;
readonly openExternal: (input: OpenExternalInput) => Effect.Effect<void, OpenError>;
readonly openBrowser: (
target: string,
options?: Omit<OpenExternalInput, "target">,
) => Effect.Effect<void, OpenError>;
/**
* Open a URL target in the default browser.
*/
readonly openBrowser: (target: string) => Effect.Effect<void, OpenError>;
/**
* Open a workspace path in a selected editor integration.
*
* Launches the editor as a detached process so server startup is not blocked.
*/
readonly openInEditor: (input: OpenInEditorInput) => Effect.Effect<void, OpenError>;
}
/**
* Open - Service tag for browser/editor launch operations.
*/
export class Open extends ServiceMap.Service<Open, OpenShape>()("t3/open") {}
const makeOpen = (options: OpenRuntimeOptions = {}) =>
// ==============================
// Implementations
// ==============================
export const resolveEditorLaunch = Effect.fnUntraced(function* (
input: OpenInEditorInput,
platform: NodeJS.Platform = process.platform,
): Effect.fn.Return<EditorLaunch, OpenError> {
const editorDef = EDITORS.find((editor) => editor.id === input.editor);
if (!editorDef) {
return yield* new OpenError({ message: `Unknown editor: ${input.editor}` });
}
if (editorDef.command) {
return shouldUseGotoFlag(editorDef, input.cwd)
? { command: editorDef.command, args: ["--goto", input.cwd] }
: { command: editorDef.command, args: [input.cwd] };
}
if (editorDef.id !== "file-manager") {
return yield* new OpenError({ message: `Unsupported editor: ${input.editor}` });
}
return { command: fileManagerCommandForPlatform(platform), args: [input.cwd] };
});
export const launchDetached = (launch: EditorLaunch) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const pathService = yield* Path.Path;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
if (!isCommandAvailable(launch.command)) {
return yield* new OpenError({ message: `Editor command not found: ${launch.command}` });
}
const isInsideContainer =
options.isInsideContainer ??
(typeof options.env?.CONTAINER === "string" ||
typeof options.env?.container === "string" ||
typeof options.env?.KUBERNETES_SERVICE_HOST === "string"
? true
: yield* fileSystem.exists("/.dockerenv").pipe(Effect.catch(() => Effect.succeed(false))));
const runtime: OpenRuntime = {
platform: options.platform ?? process.platform,
env: options.env ?? process.env,
isWsl:
options.isWsl ??
detectWsl(options.platform ?? process.platform, options.env ?? process.env),
isInsideContainer,
powerShellCandidates:
options.powerShellCommand !== undefined
? [options.powerShellCommand]
: (options.isWsl ??
detectWsl(options.platform ?? process.platform, options.env ?? process.env))
? WSL_POWERSHELL_CANDIDATES
: WINDOWS_POWERSHELL_CANDIDATES,
windowsPathExtensions: resolveWindowsPathExtensions(options.env ?? process.env),
};
const resolveCommand = Effect.fn(function* (
command: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
const candidates = resolveCommandCandidates(command, runtime, pathService);
const resolveExecutableFile = Effect.fn(function* (
filePath: string,
): Effect.fn.Return<Option.Option<ResolvedCommand>, never> {
const info = yield* fileSystem.stat(filePath).pipe(Effect.option);
if (Option.isNone(info) || info.value.type !== "File") return Option.none();
if (runtime.platform === "win32") {
const extension = pathService.extname(filePath);
if (
extension.length === 0 ||
!runtime.windowsPathExtensions.includes(extension.toUpperCase())
) {
return Option.none();
}
return Option.some({
path: filePath,
usesCmdWrapper: isWindowsBatchShim(pathService, filePath),
} satisfies ResolvedCommand);
}
return (info.value.mode & 0o111) !== 0
? Option.some({
path: filePath,
usesCmdWrapper: false,
} satisfies ResolvedCommand)
: Option.none();
});
if (command.includes("/") || command.includes("\\")) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(candidate);
if (Option.isSome(resolved)) return resolved;
}
return Option.none();
yield* Effect.callback<void, OpenError>((resume) => {
let child;
try {
child = spawn(launch.command, [...launch.args], {
detached: true,
stdio: "ignore",
shell: process.platform === "win32",
});
} catch (error) {
return resume(
Effect.fail(new OpenError({ message: "failed to spawn detached process", cause: error })),
);
}
const pathValue = resolvePathEnvironmentVariable(runtime.env);
if (pathValue.length === 0) return Option.none();
const handleSpawn = () => {
child.unref();
resume(Effect.void);
};
const pathEntries = pathValue
.split(resolvePathDelimiter(runtime.platform))
.map((entry) => stripWrappingQuotes(entry.trim()))
.filter((entry) => entry.length > 0);
for (const pathEntry of pathEntries) {
for (const candidate of candidates) {
const resolved = yield* resolveExecutableFile(pathService.join(pathEntry, candidate));
if (Option.isSome(resolved)) {
return resolved;
}
}
}
return Option.none();
child.once("spawn", handleSpawn);
child.once("error", (cause) =>
resume(Effect.fail(new OpenError({ message: "failed to spawn detached process", cause }))),
);
});
const commandAvailable = (command: string) =>
resolveCommand(command).pipe(Effect.map(Option.isSome));
const fileManagerAvailable = Effect.gen(function* () {
const candidates =
runtime.platform === "darwin"
? ["open"]
: runtime.platform === "win32"
? [...runtime.powerShellCandidates, "explorer"]
: ["xdg-open"];
for (const candidate of candidates) {
if (yield* commandAvailable(candidate)) {
return true;
}
}
return false;
});
const getAvailableEditors = Effect.gen(function* () {
const available: EditorId[] = [];
for (const editor of EDITORS) {
if (editor.id === "file-manager") {
if (yield* fileManagerAvailable) {
available.push(editor.id);
}
continue;
}
if (editor.command && (yield* commandAvailable(editor.command))) {
available.push(editor.id);
}
}
return available as ReadonlyArray<EditorId>;
}).pipe(Effect.mapError((cause) => toOpenError("Failed to resolve available editors", cause)));
const spawnPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
spawner
.spawn(
ChildProcess.make(
resolvedCommand.usesCmdWrapper
? resolveWindowsCommandShell(runtime.env)
: resolvedCommand.path,
resolvedCommand.usesCmdWrapper
? [
"/d",
"/v:off",
"/s",
"/c",
makeWindowsCmdCommandLine(resolvedCommand.path, plan.args),
]
: [...plan.args],
{
detached: plan.detached,
shell: plan.shell,
...(plan.stdio === "ignore"
? {
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
}
: {}),
},
),
)
.pipe(Effect.mapError((cause) => toOpenError(failureMessage, cause)));
const waitForExit = (
plan: LaunchPlan,
failureMessage: string,
handle: ChildProcessSpawner.ChildProcessHandle,
) =>
handle.exitCode.pipe(
Effect.flatMap((exitCode) =>
!plan.allowNonzeroExitCode && (exitCode as number) !== 0
? Effect.fail(
new OpenError({
message: `${failureMessage} (code=${exitCode as number})`,
}),
)
: Effect.void,
),
Effect.mapError((cause) => toOpenError(failureMessage, cause)),
);
const runWaitedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
Effect.acquireUseRelease(
Scope.make("sequential"),
(scope) =>
Effect.gen(function* () {
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
Scope.provide(scope),
);
yield* waitForExit(plan, failureMessage, handle);
}),
(scope) => Scope.close(scope, Exit.void),
);
const runDetachedPlan = (
plan: LaunchPlan,
resolvedCommand: ResolvedCommand,
failureMessage: string,
) =>
Effect.gen(function* () {
const childScope = yield* Scope.make("sequential");
const handle = yield* spawnPlan(plan, resolvedCommand, failureMessage).pipe(
Scope.provide(childScope),
Effect.catch((error) =>
Scope.close(childScope, Exit.void).pipe(Effect.andThen(Effect.fail(error))),
),
);
const releaseOnExit: Effect.Effect<void, never> = handle.exitCode.pipe(
Effect.ignoreCause,
Effect.ensuring(Scope.close(childScope, Exit.void)),
);
yield* Effect.forkDetach(releaseOnExit);
});
const runPlan = (plan: LaunchPlan, resolvedCommand: ResolvedCommand, failureMessage: string) =>
plan.wait
? runWaitedPlan(plan, resolvedCommand, failureMessage)
: runDetachedPlan(plan, resolvedCommand, failureMessage);
const runFirstAvailablePlan = (
plans: ReadonlyArray<LaunchPlan>,
failureMessage: string,
): Effect.Effect<void, OpenError> => {
const [first, ...rest] = plans;
if (!first) {
return Effect.fail(new OpenError({ message: failureMessage }));
}
return resolveCommand(first.command).pipe(
Effect.flatMap((resolvedCommand) => {
if (Option.isNone(resolvedCommand)) {
return rest.length === 0
? Effect.fail(new OpenError({ message: `Command not found: ${first.command}` }))
: runFirstAvailablePlan(rest, failureMessage);
}
return runPlan(first, resolvedCommand.value, failureMessage).pipe(
Effect.catch((error) =>
rest.length === 0 ? Effect.fail(error) : runFirstAvailablePlan(rest, failureMessage),
),
);
}),
);
};
const openExternal = (input: OpenExternalInput) => {
if (input.target.trim().length === 0) {
return Effect.fail(new OpenError({ message: "Open target must not be empty" }));
}
return runFirstAvailablePlan(
resolveExternalPlans(input, runtime),
`Failed to open ${input.target}`,
);
};
const openInEditor = (input: OpenInEditorInput) => {
const editor = EDITORS.find((candidate) => candidate.id === input.editor);
if (!editor) {
return Effect.fail(new OpenError({ message: `Unknown editor: ${input.editor}` }));
}
if (editor.command) {
return runFirstAvailablePlan(
[
makeLaunchPlan(
editor.command,
shouldUseGotoFlag(editor, input.cwd) ? ["--goto", input.cwd] : [input.cwd],
{
wait: false,
allowNonzeroExitCode: false,
detached: true,
stdio: "ignore",
shell: false,
},
),
],
`Failed to open ${input.cwd} in ${input.editor}`,
);
}
return openExternal({ target: input.cwd });
};
return {
getAvailableEditors,
openExternal,
openBrowser: (target, openOptions = {}) => openExternal({ ...openOptions, target }),
openInEditor,
} satisfies OpenShape;
});
export const makeOpenLayer = (options: OpenRuntimeOptions = {}) =>
Layer.effect(Open, makeOpen(options));
const make = Effect.gen(function* () {
const open = yield* Effect.tryPromise({
try: () => import("open"),
catch: (cause) => new OpenError({ message: "failed to load browser opener", cause }),
});
export const OpenLive = makeOpenLayer();
return {
openBrowser: (target) =>
Effect.tryPromise({
try: () => open.default(target),
catch: (cause) => new OpenError({ message: "Browser auto-open failed", cause }),
}),
openInEditor: (input) => Effect.flatMap(resolveEditorLaunch(input), launchDetached),
} satisfies OpenShape;
});
export const OpenLive = Layer.effect(Open, make);
+174 -436
View File
@@ -1,15 +1,15 @@
import type {
ClaudeSettings,
ClaudeModelOptions,
ModelCapabilities,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import { Cache, Duration, Effect, Equal, Layer, Option, Result, Schema, Stream } from "effect";
import { Effect, Equal, Layer, Option, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
import { query as claudeQuery } from "@anthropic-ai/claude-agent-sdk";
import { resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -43,8 +43,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -63,8 +63,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
{ value: "200k", label: "200k" },
{ value: "1m", label: "1M", isDefault: true },
],
promptInjectedEffortLevels: ["ultrathink"],
} satisfies ModelCapabilities,
@@ -96,9 +96,28 @@ 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 auth: Pick<ServerProviderAuth, "status">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -110,7 +129,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Claude Agent authentication status command is unavailable in this version of Claude.",
};
@@ -125,7 +144,7 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
@@ -146,286 +165,37 @@ export function parseClaudeAuthStatusFromOutput(result: CommandResult): {
})();
if (parsedAuth.auth === true) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Claude is not authenticated. Run `claude auth login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Could not verify Claude authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "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(
@@ -438,81 +208,144 @@ const runClaudeCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(claudeSettings.binaryPath, command);
});
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);
export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
ChildProcessSpawner.ChildProcessSpawner | ServerSettingsService
> {
const claudeSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.claudeAgent),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
claudeSettings.customModels,
);
if (!claudeSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "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",
authStatus: "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",
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 (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Claude Agent CLI (`claude`) is not installed or not on PATH."
: `Failed to execute Claude Agent CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "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",
authStatus: "unknown",
message:
"Claude Agent CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
const version = versionProbe.success.value;
const parsedVersion = parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Claude Agent CLI is installed but failed to run. ${detail}`
: "Claude Agent CLI is installed but failed to run.",
},
});
}
const authProbe = yield* runClaudeCommand(["auth", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Claude authentication status: ${error.message}.`
: "Could not verify Claude authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
"Could not verify Claude authentication status. Timed out while running command.",
},
});
}
const parsed = parseClaudeAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: claudeSettings.enabled,
@@ -521,99 +354,13 @@ export const checkClaudeProviderStatus = Effect.fn("checkClaudeProviderStatus")(
probe: {
installed: true,
version: parsedVersion,
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.",
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
}
// ── 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,
@@ -621,16 +368,7 @@ export const ClaudeProviderLive = Layer.effect(
const serverSettings = yield* ServerSettingsService;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
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(
const checkProvider = checkClaudeProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
);
+202 -242
View File
@@ -1,25 +1,16 @@
import * as OS from "node:os";
import type {
ModelCapabilities,
CodexModelOptions,
CodexSettings,
ServerProvider,
ServerProviderModel,
ServerProviderAuth,
ServerProviderAuthStatus,
ServerProviderState,
} from "@t3tools/contracts";
import {
Cache,
Duration,
Effect,
Equal,
FileSystem,
Layer,
Option,
Path,
Result,
Stream,
} from "effect";
import { Effect, Equal, FileSystem, Layer, Option, Path, Result, Stream } from "effect";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { resolveEffort } from "@t3tools/shared/model";
import {
buildServerProvider,
@@ -38,13 +29,6 @@ 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";
@@ -168,9 +152,25 @@ 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 auth: Pick<ServerProviderAuth, "status">;
readonly authStatus: ServerProviderAuthStatus;
readonly message?: string;
} {
const lowerOutput = `${result.stdout}\n${result.stderr}`.toLowerCase();
@@ -182,7 +182,7 @@ export function parseAuthStatusFromOutput(result: CommandResult): {
) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "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",
auth: { status: "unauthenticated" },
authStatus: "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", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
if (parsedAuth.auth === false) {
return {
status: "error",
auth: { status: "unauthenticated" },
authStatus: "unauthenticated",
message: "Codex CLI is not authenticated. Run `codex login` and try again.",
};
}
if (parsedAuth.attemptedJsonParse) {
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message:
"Could not verify Codex authentication status from JSON output (missing auth marker).",
};
}
if (result.code === 0) {
return { status: "ready", auth: { status: "authenticated" } };
return { status: "ready", authStatus: "authenticated" };
}
const detail = detailFromResult(result);
return {
status: "warning",
auth: { status: "unknown" },
authStatus: "unknown",
message: detail
? `Could not verify Codex authentication status. ${detail}`
: "Could not verify Codex authentication status.",
@@ -290,21 +290,6 @@ 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;
@@ -321,88 +306,179 @@ const runCodexCommand = (args: ReadonlyArray<string>) =>
return yield* spawnAndCollect(codexSettings.binaryPath, command);
});
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);
export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(
function* (): Effect.fn.Return<
ServerProvider,
ServerSettingsError,
| ChildProcessSpawner.ChildProcessSpawner
| FileSystem.FileSystem
| Path.Path
| ServerSettingsService
> {
const codexSettings = yield* Effect.service(ServerSettingsService).pipe(
Effect.flatMap((service) => service.getSettings),
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
);
if (!codexSettings.enabled) {
return buildServerProvider({
provider: PROVIDER,
enabled: false,
checkedAt,
models,
probe: {
installed: false,
version: null,
status: "warning",
auth: { status: "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",
authStatus: "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",
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 (Result.isFailure(versionProbe)) {
const error = versionProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: !isCommandMissingCause(error),
version: null,
status: "error",
authStatus: "unknown",
message: isCommandMissingCause(error)
? "Codex CLI (`codex`) is not installed or not on PATH."
: `Failed to execute Codex CLI health check: ${error instanceof Error ? error.message : String(error)}.`,
},
});
}
if (Option.isNone(versionProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: null,
status: "error",
auth: { status: "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",
authStatus: "unknown",
message: "Codex CLI is installed but failed to run. Timed out while running command.",
},
});
}
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
const version = versionProbe.success.value;
const parsedVersion =
parseCodexCliVersion(`${version.stdout}\n${version.stderr}`) ??
parseGenericCliVersion(`${version.stdout}\n${version.stderr}`);
if (version.code !== 0) {
const detail = detailFromResult(version);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
},
});
}
if (parsedVersion && !isCodexCliVersionSupported(parsedVersion)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "error",
authStatus: "unknown",
message: formatCodexCliUpgradeMessage(parsedVersion),
},
});
}
if (yield* hasCustomModelProvider) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "ready",
authStatus: "unknown",
message: "Using a custom Codex model provider; OpenAI login check skipped.",
},
});
}
const authProbe = yield* runCodexCommand(["login", "status"]).pipe(
Effect.timeoutOption(DEFAULT_TIMEOUT_MS),
Effect.result,
);
if (Result.isFailure(authProbe)) {
const error = authProbe.failure;
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message:
error instanceof Error
? `Could not verify Codex authentication status: ${error.message}.`
: "Could not verify Codex authentication status.",
},
});
}
if (Option.isNone(authProbe.success)) {
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
checkedAt,
models,
probe: {
installed: true,
version: parsedVersion,
status: "warning",
authStatus: "unknown",
message: "Could not verify Codex authentication status. Timed out while running command.",
},
});
}
const parsed = parseAuthStatusFromOutput(authProbe.success.value);
return buildServerProvider({
provider: PROVIDER,
enabled: codexSettings.enabled,
@@ -411,116 +487,13 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
probe: {
installed: true,
version: parsedVersion,
status: "error",
auth: { status: "unknown" },
message: detail
? `Codex CLI is installed but failed to run. ${detail}`
: "Codex CLI is installed but failed to run.",
status: parsed.status,
authStatus: parsed.authStatus,
...(parsed.message ? { message: parsed.message } : {}),
},
});
}
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,
@@ -529,21 +502,8 @@ 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((input) =>
Cache.get(accountProbeCache, JSON.stringify([input.binaryPath, input.homePath])),
).pipe(
const checkProvider = checkCodexProviderStatus().pipe(
Effect.provideService(ServerSettingsService, serverSettings),
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(Path.Path, path),
@@ -173,133 +173,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.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,
);
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -361,7 +235,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.auth.status, "authenticated");
assert.strictEqual(status.authStatus, "authenticated");
} finally {
process.env.PATH = previousPath;
}
@@ -375,7 +249,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.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI (`codex`) is not installed or not on PATH.",
@@ -390,7 +264,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.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI v0.36.0 is too old for T3 Code. Upgrade to v0.37.0 or newer and restart T3 Code.",
@@ -413,7 +287,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.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -439,7 +313,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.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Codex CLI is not authenticated. Run `codex login` and try again.",
@@ -464,7 +338,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.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Codex CLI authentication status command is unavailable in this Codex version.",
@@ -492,7 +366,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "ready",
enabled: true,
installed: true,
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -502,7 +376,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
status: "warning",
enabled: true,
installed: true,
auth: { status: "unknown" },
authStatus: "unknown",
checkedAt: "2026-03-25T00:00:00.000Z",
version: "1.0.0",
models: [],
@@ -620,7 +494,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.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Using a custom Codex model provider; OpenAI login check skipped.",
@@ -663,7 +537,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.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -684,7 +558,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.auth.status, "authenticated");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with authenticated=false is unauthenticated", () => {
@@ -694,7 +568,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.auth.status, "unauthenticated");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -704,7 +578,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.auth.status, "unknown");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
@@ -841,7 +715,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.auth.status, "authenticated");
assert.strictEqual(status.authStatus, "authenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -859,63 +733,13 @@ 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.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent CLI (`claude`) is not installed or not on PATH.",
@@ -947,7 +771,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.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
assert.strictEqual(
status.message,
"Claude is not authenticated. Run `claude auth login` and try again.",
@@ -975,7 +799,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.auth.status, "unauthenticated");
assert.strictEqual(status.authStatus, "unauthenticated");
}).pipe(
Effect.provide(
mockSpawnerLayer((args) => {
@@ -995,7 +819,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.auth.status, "unknown");
assert.strictEqual(status.authStatus, "unknown");
assert.strictEqual(
status.message,
"Claude Agent authentication status command is unavailable in this version of Claude.",
@@ -1020,7 +844,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.auth.status, "authenticated");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=true is authenticated", () => {
@@ -1030,7 +854,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "ready");
assert.strictEqual(parsed.auth.status, "authenticated");
assert.strictEqual(parsed.authStatus, "authenticated");
});
it("JSON with loggedIn=false is unauthenticated", () => {
@@ -1040,7 +864,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "error");
assert.strictEqual(parsed.auth.status, "unauthenticated");
assert.strictEqual(parsed.authStatus, "unauthenticated");
});
it("JSON without auth marker is warning", () => {
@@ -1050,7 +874,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
code: 0,
});
assert.strictEqual(parsed.status, "warning");
assert.strictEqual(parsed.auth.status, "unknown");
assert.strictEqual(parsed.authStatus, "unknown");
});
});
},
-123
View File
@@ -1,123 +0,0 @@
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;
}
-154
View File
@@ -1,154 +0,0 @@
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(),
});
});
}
+3 -3
View File
@@ -1,6 +1,6 @@
import type {
ServerProvider,
ServerProviderAuth,
ServerProviderAuthStatus,
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 auth: ServerProviderAuth;
readonly authStatus: ServerProviderAuthStatus;
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",
auth: input.probe.auth,
authStatus: input.probe.authStatus,
checkedAt: input.checkedAt,
...(input.probe.message ? { message: input.probe.message } : {}),
models: input.models,
+87 -37
View File
@@ -104,43 +104,6 @@ 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;
@@ -216,4 +179,91 @@ it.layer(NodeServices.layer)("server settings", (it) => {
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
it.effect("persists custom themes as part of server-authoritative appearance settings", () =>
Effect.gen(function* () {
const serverSettings = yield* ServerSettingsService;
const serverConfig = yield* ServerConfig;
const fileSystem = yield* FileSystem.FileSystem;
const next = yield* serverSettings.updateSettings({
activeLightThemeId: "custom-codex-light",
activeDarkThemeId: "custom-codex-dark",
customThemes: [
{
id: "custom-codex-light",
name: "Custom Codex Light",
version: 1,
origin: "custom",
mode: "light",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#ffffff",
foreground: "#0d0d0d",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 46,
},
{
id: "custom-codex-dark",
name: "Custom Codex Dark",
version: 1,
origin: "custom",
mode: "dark",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#111111",
foreground: "#fcfcfc",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 41,
},
],
});
assert.equal(next.activeLightThemeId, "custom-codex-light");
assert.equal(next.activeDarkThemeId, "custom-codex-dark");
assert.equal(next.customThemes.length, 2);
const raw = yield* fileSystem.readFileString(serverConfig.settingsPath);
assert.deepEqual(JSON.parse(raw), {
activeLightThemeId: "custom-codex-light",
activeDarkThemeId: "custom-codex-dark",
customThemes: [
{
id: "custom-codex-light",
name: "Custom Codex Light",
version: 1,
origin: "custom",
mode: "light",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#ffffff",
foreground: "#0d0d0d",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 46,
},
{
id: "custom-codex-dark",
name: "Custom Codex Dark",
version: 1,
origin: "custom",
mode: "dark",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#111111",
foreground: "#fcfcfc",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 41,
},
],
});
}).pipe(Effect.provide(makeServerSettingsLayer())),
);
});
+4 -14
View File
@@ -27,7 +27,6 @@ import {
FileSystem,
Layer,
Path,
Equal,
PubSub,
Ref,
Schema,
@@ -131,12 +130,9 @@ 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 Equal.equals(current, defaults) ? undefined : current;
return JSON.stringify(current) === JSON.stringify(defaults) ? undefined : current;
}
if (
@@ -150,15 +146,9 @@ function stripDefaultServerSettings(current: unknown, defaults: unknown): unknow
const next: Record<string, unknown> = {};
for (const key of Object.keys(currentRecord)) {
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;
}
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
+38 -71
View File
@@ -14,81 +14,47 @@ import {
TerminalResizeInput,
TerminalRestartInput,
TerminalSessionSnapshot,
TerminalSessionStatus,
TerminalWriteInput,
} from "@t3tools/contracts";
import { PtyProcess } from "./PTY";
import { Effect, Schema, ServiceMap } from "effect";
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 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 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 ShellCandidate {
shell: string;
args?: string[];
}
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 interface TerminalStartInput extends TerminalOpenInput {
cols: number;
rows: number;
}
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.
*/
@@ -135,13 +101,14 @@ export interface TerminalManagerShape {
readonly close: (input: TerminalCloseInput) => Effect.Effect<void, TerminalError>;
/**
* Subscribe to terminal runtime events with a direct callback.
*
* Returns an unsubscribe function.
* Subscribe to terminal runtime events.
*/
readonly subscribe: (
listener: (event: TerminalEvent) => Effect.Effect<void>,
) => Effect.Effect<() => void>;
readonly subscribe: (listener: (event: TerminalEvent) => void) => Effect.Effect<() => void>;
/**
* Dispose all managed terminal resources.
*/
readonly dispose: Effect.Effect<void>;
}
/**
+15 -28
View File
@@ -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, Fiber, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { Effect, Exit, Layer, PlatformError, PubSub, Scope, Stream } from "effect";
import { describe, expect, it, afterEach, vi } from "vitest";
import { createServer } from "./wsServer";
import WebSocket from "ws";
@@ -63,8 +63,6 @@ const asThreadId = (value: string): ThreadId => ThreadId.makeUnsafe(value);
const asTurnId = (value: string): TurnId => TurnId.makeUnsafe(value);
const defaultOpenService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: () => Effect.void,
};
@@ -76,7 +74,7 @@ const defaultProviderStatuses: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
@@ -92,19 +90,20 @@ const defaultServerSettings = DEFAULT_SERVER_SETTINGS;
class MockTerminalManager implements TerminalManagerShape {
private readonly sessions = new Map<string, TerminalSessionSnapshot>();
private readonly eventPubSub = Effect.runSync(PubSub.unbounded<TerminalEvent>());
private activeSubscriptions = 0;
private readonly listeners = new Set<(event: TerminalEvent) => void>();
private key(threadId: string, terminalId: string): string {
return `${threadId}\u0000${terminalId}`;
}
emitEvent(event: TerminalEvent): void {
Effect.runSync(PubSub.publish(this.eventPubSub, event));
for (const listener of this.listeners) {
listener(event);
}
}
subscriptionCount(): number {
return this.activeSubscriptions;
return this.listeners.size;
}
readonly open: TerminalManagerShape["open"] = (input: TerminalOpenInput) =>
@@ -211,15 +210,13 @@ class MockTerminalManager implements TerminalManagerShape {
readonly subscribe: TerminalManagerShape["subscribe"] = (listener) =>
Effect.sync(() => {
this.activeSubscriptions += 1;
const fiber = Effect.runFork(
Stream.runForEach(Stream.fromPubSub(this.eventPubSub), (event) => listener(event)),
);
this.listeners.add(listener);
return () => {
this.activeSubscriptions -= 1;
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.ignore));
this.listeners.delete(listener);
};
});
readonly dispose: TerminalManagerShape["dispose"] = Effect.void;
}
// ---------------------------------------------------------------------------
@@ -1032,8 +1029,6 @@ describe("WebSocket Server", () => {
it("routes shell.openInEditor through the injected open service", async () => {
const openCalls: Array<{ cwd: string; editor: string }> = [];
const openService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: (input) => {
openCalls.push({ cwd: input.cwd, editor: input.editor });
@@ -1459,25 +1454,19 @@ describe("WebSocket Server", () => {
expect(push.channel).toBe(WS_CHANNELS.terminalEvent);
});
it("shuts down cleanly for injected terminal managers", async () => {
it("detaches terminal event listener on stop for injected manager", async () => {
const terminalManager = new MockTerminalManager();
server = await createTestServer({
cwd: "/test",
terminalManager,
});
expect(terminalManager.subscriptionCount()).toBe(1);
await closeTestServer();
server = null;
expect(() =>
terminalManager.emitEvent({
type: "output",
threadId: "thread-1",
terminalId: DEFAULT_TERMINAL_ID,
createdAt: new Date().toISOString(),
data: "after shutdown\n",
}),
).not.toThrow();
expect(terminalManager.subscriptionCount()).toBe(0);
});
it("returns validation errors for invalid terminal open params", async () => {
@@ -1535,8 +1524,6 @@ describe("WebSocket Server", () => {
process.on("unhandledRejection", onUnhandledRejection);
const brokenOpenService: OpenShape = {
getAvailableEditors: Effect.succeed([]),
openExternal: () => Effect.void,
openBrowser: () => Effect.void,
openInEditor: () =>
Effect.sync(() => BigInt(1)).pipe(Effect.map((result) => result as unknown as void)),
+5 -8
View File
@@ -58,7 +58,7 @@ import { ProviderService } from "./provider/Services/ProviderService";
import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
import { clamp } from "effect/Number";
import { Open } from "./open";
import { Open, resolveAvailableEditors } from "./open";
import { ServerConfig } from "./config";
import { GitCore } from "./git/Services/GitCore.ts";
import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
@@ -250,10 +250,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
logWebSocketEvents,
autoBootstrapProjectFromCwd,
} = serverConfig;
const open = yield* Open;
const availableEditors = yield* open.getAvailableEditors.pipe(
Effect.mapError((cause) => new ServerLifecycleError({ operation: "availableEditors", cause })),
);
const availableEditors = resolveAvailableEditors();
const runtimeServices = yield* Effect.services<
ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
@@ -618,7 +615,7 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
const checkpointDiffQuery = yield* CheckpointDiffQuery;
const orchestrationReactor = yield* OrchestrationReactor;
const { openInEditor } = open;
const { openInEditor } = yield* Open;
const subscriptionsScope = yield* Scope.make("sequential");
yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
@@ -722,9 +719,9 @@ export const createServer = Effect.fn(function* (): Effect.fn.Return<
}
const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
runPromise(pushBus.publishAll(WS_CHANNELS.terminalEvent, event)),
);
yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
yield* readiness.markTerminalSubscriptionsReady;
yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
@@ -397,6 +397,7 @@ export function BranchToolbarBranchSelector({
key={itemValue}
index={index}
value={itemValue}
className={itemValue === resolvedActiveBranch ? "bg-accent text-foreground" : undefined}
style={style}
onClick={() => selectBranch(branch)}
>
+2 -2
View File
@@ -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 { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
import { resolveMarkdownFileLinkTarget } from "../markdown-links";
import { readNativeApi } from "../nativeApi";
@@ -236,7 +236,7 @@ function SuspenseShikiCodeBlock({
}
function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
const { resolvedTheme } = useTheme();
const { resolvedTheme } = useAppearance();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const markdownComponents = useMemo<Components>(
() => ({
+16 -183
View File
@@ -2,11 +2,8 @@
import "../index.css";
import {
EventId,
ORCHESTRATION_WS_METHODS,
ORCHESTRATION_WS_CHANNELS,
type MessageId,
type OrchestrationEvent,
type OrchestrationReadModel,
type ProjectId,
type ServerConfig,
@@ -60,8 +57,6 @@ interface TestFixture {
let fixture: TestFixture;
const wsRequests: WsRequestEnvelope["body"][] = [];
let customWsRpcResolver: ((body: WsRequestEnvelope["body"]) => unknown | undefined) | null = null;
let wsClient: { send: (message: string) => void } | null = null;
let pushSequence = 1;
const wsLink = ws.link(/ws(s)?:\/\/.*/);
interface ViewportSpec {
@@ -122,7 +117,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: NOW_ISO,
models: [],
},
@@ -341,79 +336,6 @@ function addThreadToSnapshot(
};
}
function createThreadCreatedEvent(threadId: ThreadId, sequence: number): OrchestrationEvent {
return {
sequence,
eventId: EventId.makeUnsafe(`event-thread-created-${sequence}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: NOW_ISO,
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type: "thread.created",
payload: {
threadId,
projectId: PROJECT_ID,
title: "New thread",
modelSelection: {
provider: "codex",
model: "gpt-5",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt: NOW_ISO,
updatedAt: NOW_ISO,
},
};
}
function sendOrchestrationDomainEvent(event: OrchestrationEvent): void {
if (!wsClient) {
throw new Error("WebSocket client not connected");
}
wsClient.send(
JSON.stringify({
type: "push",
sequence: pushSequence++,
channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
data: event,
}),
);
}
async function waitForWsClient(): Promise<{ send: (message: string) => void }> {
let client: { send: (message: string) => void } | null = null;
await vi.waitFor(
() => {
client = wsClient;
expect(client).toBeTruthy();
},
{ timeout: 8_000, interval: 16 },
);
if (!client) {
throw new Error("WebSocket client not connected");
}
return client;
}
async function promoteDraftThreadViaDomainEvent(threadId: ThreadId): Promise<void> {
await waitForWsClient();
fixture.snapshot = addThreadToSnapshot(fixture.snapshot, threadId);
sendOrchestrationDomainEvent(
createThreadCreatedEvent(threadId, fixture.snapshot.snapshotSequence),
);
await vi.waitFor(
() => {
expect(useComposerDraftStore.getState().draftThreadsByThreadId[threadId]).toBeUndefined();
},
{ timeout: 8_000, interval: 16 },
);
}
function createDraftOnlySnapshot(): OrchestrationReadModel {
const snapshot = createSnapshotForTargetUser({
targetMessageId: "msg-user-draft-target" as MessageId,
@@ -578,12 +500,10 @@ function resolveWsRpc(body: WsRequestEnvelope["body"]): unknown {
const worker = setupWorker(
wsLink.addEventListener("connection", ({ client }) => {
wsClient = client;
pushSequence = 1;
client.send(
JSON.stringify({
type: "push",
sequence: pushSequence++,
sequence: 1,
channel: WS_CHANNELS.serverWelcome,
data: fixture.welcome,
}),
@@ -955,7 +875,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
useStore.setState({
projects: [],
threads: [],
bootstrapComplete: false,
threadsHydrated: false,
});
});
@@ -1121,19 +1041,6 @@ 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();
@@ -1853,87 +1760,6 @@ 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,
@@ -1961,16 +1787,21 @@ describe("ChatView timeline estimator parity (full app)", () => {
// The composer editor should be present for the new draft thread.
await waitForComposerEditor();
// Simulate the steady-state promotion path: the server emits
// `thread.created`, the client materializes the thread incrementally,
// and the draft is cleared by live batch effects.
await promoteDraftThreadViaDomainEvent(newThreadId);
// Simulate the snapshot sync arriving from the server after the draft
// thread has been promoted to a server thread (thread.create + turn.start
// succeeded). The snapshot now includes the new thread, and the sync
// should clear the draft without disrupting the route.
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, newThreadId));
// Clear the draft now that the server thread exists (mirrors EventRouter behavior).
useComposerDraftStore.getState().clearDraftThread(newThreadId);
// The route should still be on the new thread — not redirected away.
await waitForURL(
mounted.router,
(path) => path === newThreadPath,
"New thread should remain selected after server thread promotion clears the draft.",
"New thread should remain selected after snapshot sync clears the draft.",
);
// The empty thread view and composer should still be visible.
@@ -2292,7 +2123,9 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
const promotedThreadId = promotedThreadPath.slice(1) as ThreadId;
await promoteDraftThreadViaDomainEvent(promotedThreadId);
const { syncServerReadModel } = useStore.getState();
syncServerReadModel(addThreadToSnapshot(fixture.snapshot, promotedThreadId));
useComposerDraftStore.getState().clearDraftThread(promotedThreadId);
const freshThreadPath = await triggerChatNewShortcutUntilPath(
mounted.router,
+3 -297
View File
@@ -1,14 +1,7 @@
import { ProjectId, ThreadId, TurnId } from "@t3tools/contracts";
import { afterEach, describe, expect, it, vi } from "vitest";
import { useStore } from "../store";
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
buildExpiredTerminalContextToastCopy,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
waitForStartedServerThread,
} from "./ChatView.logic";
import { buildExpiredTerminalContextToastCopy, deriveComposerSendState } from "./ChatView.logic";
describe("deriveComposerSendState", () => {
it("treats expired terminal pills as non-sendable content", () => {
@@ -74,290 +67,3 @@ describe("buildExpiredTerminalContextToastCopy", () => {
});
});
});
const makeThread = (input?: {
id?: ThreadId;
latestTurn?: {
turnId: TurnId;
state: "running" | "completed";
requestedAt: string;
startedAt: string | null;
completedAt: string | null;
} | null;
}) => ({
id: input?.id ?? ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Thread",
modelSelection: { provider: "codex" as const, model: "gpt-5.4" },
runtimeMode: "full-access" as const,
interactionMode: "default" as const,
session: null,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:00.000Z",
latestTurn: input?.latestTurn
? {
...input.latestTurn,
assistantMessageId: null,
}
: null,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
useStore.setState((state) => ({
...state,
projects: [],
threads: [],
bootstrapComplete: true,
}));
});
describe("waitForStartedServerThread", () => {
it("resolves immediately when the thread is already started", async () => {
const threadId = ThreadId.makeUnsafe("thread-started");
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
await expect(waitForStartedServerThread(threadId)).resolves.toBe(true);
});
it("waits for the thread to start via subscription updates", async () => {
const threadId = ThreadId.makeUnsafe("thread-wait");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const promise = waitForStartedServerThread(threadId, 500);
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-started"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
await expect(promise).resolves.toBe(true);
});
it("handles the thread starting between the initial read and subscription setup", async () => {
const threadId = ThreadId.makeUnsafe("thread-race");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const originalSubscribe = useStore.subscribe.bind(useStore);
let raced = false;
vi.spyOn(useStore, "subscribe").mockImplementation((listener) => {
if (!raced) {
raced = true;
useStore.setState((state) => ({
...state,
threads: [
makeThread({
id: threadId,
latestTurn: {
turnId: TurnId.makeUnsafe("turn-race"),
state: "running",
requestedAt: "2026-03-29T00:00:01.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: null,
},
}),
],
}));
}
return originalSubscribe(listener);
});
await expect(waitForStartedServerThread(threadId, 500)).resolves.toBe(true);
});
it("returns false after the timeout when the thread never starts", async () => {
vi.useFakeTimers();
const threadId = ThreadId.makeUnsafe("thread-timeout");
useStore.setState((state) => ({
...state,
threads: [makeThread({ id: threadId })],
}));
const promise = waitForStartedServerThread(threadId, 500);
await vi.advanceTimersByTimeAsync(500);
await expect(promise).resolves.toBe(false);
});
});
describe("hasServerAcknowledgedLocalDispatch", () => {
const projectId = ProjectId.makeUnsafe("project-1");
const previousLatestTurn = {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed" as const,
requestedAt: "2026-03-29T00:00:00.000Z",
startedAt: "2026-03-29T00:00:01.000Z",
completedAt: "2026-03-29T00:00:10.000Z",
assistantMessageId: null,
};
const previousSession = {
provider: "codex" as const,
status: "ready" as const,
createdAt: "2026-03-29T00:00:00.000Z",
updatedAt: "2026-03-29T00:00:10.000Z",
orchestrationStatus: "idle" as const,
};
it("does not clear local dispatch before server state changes", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: previousLatestTurn,
session: previousSession,
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(false);
});
it("clears local dispatch when a new turn is already settled", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: {
...previousLatestTurn,
turnId: TurnId.makeUnsafe("turn-2"),
requestedAt: "2026-03-29T00:01:00.000Z",
startedAt: "2026-03-29T00:01:01.000Z",
completedAt: "2026-03-29T00:01:30.000Z",
},
session: {
...previousSession,
updatedAt: "2026-03-29T00:01:30.000Z",
},
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(true);
});
it("clears local dispatch when the session changes without an observed running phase", () => {
const localDispatch = createLocalDispatchSnapshot({
id: ThreadId.makeUnsafe("thread-1"),
codexThreadId: null,
projectId,
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
session: previousSession,
messages: [],
proposedPlans: [],
error: null,
createdAt: "2026-03-29T00:00:00.000Z",
archivedAt: null,
updatedAt: "2026-03-29T00:00:10.000Z",
latestTurn: previousLatestTurn,
branch: null,
worktreePath: null,
turnDiffSummaries: [],
activities: [],
});
expect(
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: "ready",
latestTurn: previousLatestTurn,
session: {
...previousSession,
updatedAt: "2026-03-29T00:00:11.000Z",
},
hasPendingApproval: false,
hasPendingUserInput: false,
threadError: null,
}),
).toBe(true);
});
});
+5 -116
View File
@@ -1,9 +1,8 @@
import { ProjectId, type ModelSelection, type ThreadId, type TurnId } from "@t3tools/contracts";
import { type ChatMessage, type SessionPhase, type Thread, type ThreadSession } from "../types";
import { ProjectId, type ModelSelection, type ThreadId } from "@t3tools/contracts";
import { type ChatMessage, type Thread } from "../types";
import { randomUUID } from "~/lib/utils";
import { type ComposerImageAttachment, type DraftThreadState } from "../composerDraftStore";
import { Schema } from "effect";
import { useStore } from "../store";
import {
filterTerminalContextsWithText,
stripInlineTerminalContextPlaceholders,
@@ -35,6 +34,7 @@ export function buildLocalDraftThread(
createdAt: draftThread.createdAt,
archivedAt: null,
latestTurn: null,
lastVisitedAt: draftThread.createdAt,
branch: draftThread.branch,
worktreePath: draftThread.worktreePath,
turnDiffSummaries: [],
@@ -75,6 +75,8 @@ export function collectUserMessageBlobPreviewUrls(message: ChatMessage): string[
return previewUrls;
}
export type SendPhase = "idle" | "preparing-worktree" | "sending-turn";
export interface PullRequestDialogState {
initialReference: string | null;
key: number;
@@ -159,116 +161,3 @@ export function buildExpiredTerminalContextToastCopy(
description: "Re-add it if you want that terminal output included.",
};
}
export function threadHasStarted(thread: Thread | null | undefined): boolean {
return Boolean(
thread && (thread.latestTurn !== null || thread.messages.length > 0 || thread.session !== null),
);
}
export async function waitForStartedServerThread(
threadId: ThreadId,
timeoutMs = 1_000,
): Promise<boolean> {
const getThread = () => useStore.getState().threads.find((thread) => thread.id === threadId);
const thread = getThread();
if (threadHasStarted(thread)) {
return true;
}
return await new Promise<boolean>((resolve) => {
let settled = false;
let timeoutId: ReturnType<typeof globalThis.setTimeout> | null = null;
const finish = (result: boolean) => {
if (settled) {
return;
}
settled = true;
if (timeoutId !== null) {
globalThis.clearTimeout(timeoutId);
}
unsubscribe();
resolve(result);
};
const unsubscribe = useStore.subscribe((state) => {
if (!threadHasStarted(state.threads.find((thread) => thread.id === threadId))) {
return;
}
finish(true);
});
if (threadHasStarted(getThread())) {
finish(true);
return;
}
timeoutId = globalThis.setTimeout(() => {
finish(false);
}, timeoutMs);
});
}
export interface LocalDispatchSnapshot {
startedAt: string;
preparingWorktree: boolean;
latestTurnTurnId: TurnId | null;
latestTurnRequestedAt: string | null;
latestTurnStartedAt: string | null;
latestTurnCompletedAt: string | null;
sessionOrchestrationStatus: ThreadSession["orchestrationStatus"] | null;
sessionUpdatedAt: string | null;
}
export function createLocalDispatchSnapshot(
activeThread: Thread | undefined,
options?: { preparingWorktree?: boolean },
): LocalDispatchSnapshot {
const latestTurn = activeThread?.latestTurn ?? null;
const session = activeThread?.session ?? null;
return {
startedAt: new Date().toISOString(),
preparingWorktree: Boolean(options?.preparingWorktree),
latestTurnTurnId: latestTurn?.turnId ?? null,
latestTurnRequestedAt: latestTurn?.requestedAt ?? null,
latestTurnStartedAt: latestTurn?.startedAt ?? null,
latestTurnCompletedAt: latestTurn?.completedAt ?? null,
sessionOrchestrationStatus: session?.orchestrationStatus ?? null,
sessionUpdatedAt: session?.updatedAt ?? null,
};
}
export function hasServerAcknowledgedLocalDispatch(input: {
localDispatch: LocalDispatchSnapshot | null;
phase: SessionPhase;
latestTurn: Thread["latestTurn"] | null;
session: Thread["session"] | null;
hasPendingApproval: boolean;
hasPendingUserInput: boolean;
threadError: string | null | undefined;
}): boolean {
if (!input.localDispatch) {
return false;
}
if (
input.phase === "running" ||
input.hasPendingApproval ||
input.hasPendingUserInput ||
Boolean(input.threadError)
) {
return true;
}
const latestTurn = input.latestTurn ?? null;
const session = input.session ?? null;
return (
input.localDispatch.latestTurnTurnId !== (latestTurn?.turnId ?? null) ||
input.localDispatch.latestTurnRequestedAt !== (latestTurn?.requestedAt ?? null) ||
input.localDispatch.latestTurnStartedAt !== (latestTurn?.startedAt ?? null) ||
input.localDispatch.latestTurnCompletedAt !== (latestTurn?.completedAt ?? null) ||
input.localDispatch.sessionOrchestrationStatus !== (session?.orchestrationStatus ?? null) ||
input.localDispatch.sessionUpdatedAt !== (session?.updatedAt ?? null)
);
}
+121 -229
View File
@@ -20,7 +20,6 @@ import {
OrchestrationThreadActivity,
ProviderInteractionMode,
RuntimeMode,
TerminalOpenInput,
} from "@t3tools/contracts";
import { applyClaudePromptEffortPrefix, normalizeModelSlug } from "@t3tools/shared/model";
import { truncate } from "@t3tools/shared/String";
@@ -43,7 +42,6 @@ import {
replaceTextRange,
} from "../composer-logic";
import {
deriveCompletionDividerBeforeEntryId,
derivePendingApprovals,
derivePendingUserInputs,
derivePhase,
@@ -66,8 +64,6 @@ import {
type PendingUserInputDraftAnswer,
} from "../pendingUserInput";
import { useStore } from "../store";
import { useProjectById, useThreadById } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
import {
buildPlanImplementationThreadTitle,
buildPlanImplementationPrompt,
@@ -80,14 +76,10 @@ import {
DEFAULT_THREAD_TERMINAL_ID,
MAX_TERMINALS_PER_GROUP,
type ChatMessage,
type SessionPhase,
type Thread,
type TurnDiffSummary,
} from "../types";
import { LRUCache } from "../lib/lruCache";
import { basenameOfPath } from "../vscode-icons";
import { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import BranchToolbar from "./BranchToolbar";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
@@ -176,18 +168,14 @@ import {
buildTemporaryWorktreeBranchName,
cloneComposerImageForRetry,
collectUserMessageBlobPreviewUrls,
createLocalDispatchSnapshot,
deriveComposerSendState,
hasServerAcknowledgedLocalDispatch,
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
LastInvokedScriptByProjectSchema,
type LocalDispatchSnapshot,
PullRequestDialogState,
readFileAsDataUrl,
revokeBlobPreviewUrl,
revokeUserMessagePreviewUrls,
threadHasStarted,
waitForStartedServerThread,
SendPhase,
} from "./ChatView.logic";
import { useLocalStorage } from "~/hooks/useLocalStorage";
@@ -202,81 +190,6 @@ const EMPTY_AVAILABLE_EDITORS: EditorId[] = [];
const EMPTY_PROVIDERS: ServerProvider[] = [];
const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};
type ThreadPlanCatalogEntry = Pick<Thread, "id" | "proposedPlans">;
const MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES = 500;
const MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES = 512 * 1024;
const threadPlanCatalogCache = new LRUCache<{
proposedPlans: Thread["proposedPlans"];
entry: ThreadPlanCatalogEntry;
}>(MAX_THREAD_PLAN_CATALOG_CACHE_ENTRIES, MAX_THREAD_PLAN_CATALOG_CACHE_MEMORY_BYTES);
function estimateThreadPlanCatalogEntrySize(thread: Thread): number {
return Math.max(
64,
thread.id.length +
thread.proposedPlans.reduce(
(total, plan) =>
total +
plan.id.length +
plan.planMarkdown.length +
plan.updatedAt.length +
(plan.turnId?.length ?? 0),
0,
),
);
}
function toThreadPlanCatalogEntry(thread: Thread): ThreadPlanCatalogEntry {
const cached = threadPlanCatalogCache.get(thread.id);
if (cached && cached.proposedPlans === thread.proposedPlans) {
return cached.entry;
}
const entry: ThreadPlanCatalogEntry = {
id: thread.id,
proposedPlans: thread.proposedPlans,
};
threadPlanCatalogCache.set(
thread.id,
{
proposedPlans: thread.proposedPlans,
entry,
},
estimateThreadPlanCatalogEntrySize(thread),
);
return entry;
}
function useThreadPlanCatalog(threadIds: readonly ThreadId[]): ThreadPlanCatalogEntry[] {
const selector = useMemo(() => {
let previousThreads: Array<Thread | undefined> | null = null;
let previousEntries: ThreadPlanCatalogEntry[] = [];
return (state: { threads: Thread[] }): ThreadPlanCatalogEntry[] => {
const nextThreads = threadIds.map((threadId) =>
state.threads.find((thread) => thread.id === threadId),
);
const cachedThreads = previousThreads;
if (
cachedThreads &&
nextThreads.length === cachedThreads.length &&
nextThreads.every((thread, index) => thread === cachedThreads[index])
) {
return previousEntries;
}
previousThreads = nextThreads;
previousEntries = nextThreads.flatMap((thread) =>
thread ? [toThreadPlanCatalogEntry(thread)] : [],
);
return previousEntries;
};
}, [threadIds]);
return useStore(selector);
}
function formatOutgoingPrompt(params: {
provider: ProviderKind;
model: string | null;
@@ -332,81 +245,13 @@ interface PendingPullRequestSetupRequest {
scriptId: string;
}
function useLocalDispatchState(input: {
activeThread: Thread | undefined;
activeLatestTurn: Thread["latestTurn"] | null;
phase: SessionPhase;
activePendingApproval: ApprovalRequestId | null;
activePendingUserInput: ApprovalRequestId | null;
threadError: string | null | undefined;
}) {
const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);
const beginLocalDispatch = useCallback(
(options?: { preparingWorktree?: boolean }) => {
const preparingWorktree = Boolean(options?.preparingWorktree);
setLocalDispatch((current) => {
if (current) {
return current.preparingWorktree === preparingWorktree
? current
: { ...current, preparingWorktree };
}
return createLocalDispatchSnapshot(input.activeThread, options);
});
},
[input.activeThread],
);
const resetLocalDispatch = useCallback(() => {
setLocalDispatch(null);
}, []);
const serverAcknowledgedLocalDispatch = useMemo(
() =>
hasServerAcknowledgedLocalDispatch({
localDispatch,
phase: input.phase,
latestTurn: input.activeLatestTurn,
session: input.activeThread?.session ?? null,
hasPendingApproval: input.activePendingApproval !== null,
hasPendingUserInput: input.activePendingUserInput !== null,
threadError: input.threadError,
}),
[
input.activeLatestTurn,
input.activePendingApproval,
input.activePendingUserInput,
input.activeThread?.session,
input.phase,
input.threadError,
localDispatch,
],
);
useEffect(() => {
if (!serverAcknowledgedLocalDispatch) {
return;
}
resetLocalDispatch();
}, [resetLocalDispatch, serverAcknowledgedLocalDispatch]);
return {
beginLocalDispatch,
resetLocalDispatch,
localDispatchStartedAt: localDispatch?.startedAt ?? null,
isPreparingWorktree: localDispatch?.preparingWorktree ?? false,
isSendBusy: localDispatch !== null && !serverAcknowledgedLocalDispatch,
};
}
export default function ChatView({ threadId }: ChatViewProps) {
const serverThread = useThreadById(threadId);
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const markThreadVisited = useStore((store) => store.markThreadVisited);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setStoreThreadError = useStore((store) => store.setError);
const setStoreThreadBranch = useStore((store) => store.setThreadBranch);
const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);
const activeThreadLastVisitedAt = useUiStateStore(
(store) => store.threadLastVisitedAtById[threadId],
);
const settings = useSettings();
const setStickyComposerModelSelection = useComposerDraftStore(
(store) => store.setStickyModelSelection,
@@ -417,7 +262,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
strict: false,
select: (params) => parseDiffRouteSearch(params),
});
const { resolvedTheme } = useTheme();
const { resolvedTheme } = useAppearance();
const queryClient = useQueryClient();
const createWorktreeMutation = useMutation(gitCreateWorktreeMutationOptions({ queryClient }));
const composerDraft = useComposerThreadDraft(threadId);
@@ -485,6 +330,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
const [localDraftErrorsByThreadId, setLocalDraftErrorsByThreadId] = useState<
Record<ThreadId, string | null>
>({});
const [sendPhase, setSendPhase] = useState<SendPhase>("idle");
const [sendStartedAt, setSendStartedAt] = useState<string | null>(null);
const [isConnecting, _setIsConnecting] = useState(false);
const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);
const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);
@@ -619,7 +466,8 @@ export default function ChatView({ threadId }: ChatViewProps) {
[composerTerminalContexts, removeComposerDraftTerminalContext, setPrompt, threadId],
);
const fallbackDraftProject = useProjectById(draftThread?.projectId);
const serverThread = threads.find((t) => t.id === threadId);
const fallbackDraftProject = projects.find((project) => project.id === draftThread?.projectId);
const localDraftError = serverThread ? null : (localDraftErrorsByThreadId[threadId] ?? null);
const localDraftThread = useMemo(
() =>
@@ -647,25 +495,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const diffOpen = rawSearch.diff === "1";
const activeThreadId = activeThread?.id ?? null;
const activeLatestTurn = activeThread?.latestTurn ?? null;
const threadPlanCatalog = useThreadPlanCatalog(
useMemo(() => {
const threadIds: ThreadId[] = [];
if (activeThread?.id) {
threadIds.push(activeThread.id);
}
const sourceThreadId = activeLatestTurn?.sourceProposedPlan?.threadId;
if (sourceThreadId && sourceThreadId !== activeThread?.id) {
threadIds.push(sourceThreadId);
}
return threadIds;
}, [activeLatestTurn?.sourceProposedPlan?.threadId, activeThread?.id]),
);
const activeContextWindow = useMemo(
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
[activeThread?.activities],
);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProject = useProjectById(activeThread?.projectId);
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
const openPullRequestDialog = useCallback(
(reference?: string) => {
@@ -760,28 +595,33 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
useEffect(() => {
if (!serverThread?.id) return;
if (!activeThread?.id) return;
if (!latestTurnSettled) return;
if (!activeLatestTurn?.completedAt) return;
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnCompletedAt)) return;
const lastVisitedAt = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;
const lastVisitedAt = activeThread.lastVisitedAt ? Date.parse(activeThread.lastVisitedAt) : NaN;
if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= turnCompletedAt) return;
markThreadVisited(serverThread.id);
markThreadVisited(activeThread.id);
}, [
activeThread?.id,
activeThread?.lastVisitedAt,
activeLatestTurn?.completedAt,
activeThreadLastVisitedAt,
latestTurnSettled,
markThreadVisited,
serverThread?.id,
]);
const sessionProvider = activeThread?.session?.provider ?? null;
const selectedProviderByThreadId = composerDraft.activeProvider ?? null;
const threadProvider =
activeThread?.modelSelection.provider ?? activeProject?.defaultModelSelection?.provider ?? null;
const hasThreadStarted = threadHasStarted(activeThread);
const hasThreadStarted = Boolean(
activeThread &&
(activeThread.latestTurn !== null ||
activeThread.messages.length > 0 ||
activeThread.session !== null),
);
const lockedProvider: ProviderKind | null = hasThreadStarted
? (sessionProvider ?? threadProvider ?? selectedProviderByThreadId ?? null)
: null;
@@ -824,6 +664,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const selectedModelForPicker = selectedModel;
const phase = derivePhase(activeThread?.session ?? null);
const isSendBusy = sendPhase !== "idle";
const isPreparingWorktree = sendPhase === "preparing-worktree";
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
sendStartedAt,
);
const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;
const workLogEntries = useMemo(
() => deriveWorkLogEntries(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -886,12 +735,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
const sidebarProposedPlan = useMemo(
() =>
findSidebarProposedPlan({
threads: threadPlanCatalog,
threads,
latestTurn: activeLatestTurn,
latestTurnSettled,
threadId: activeThread?.id ?? null,
}),
[activeLatestTurn, activeThread?.id, latestTurnSettled, threadPlanCatalog],
[activeLatestTurn, activeThread?.id, latestTurnSettled, threads],
);
const activePlan = useMemo(
() => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),
@@ -903,27 +752,6 @@ export default function ChatView({ threadId }: ChatViewProps) {
latestTurnSettled &&
hasActionableProposedPlan(activeProposedPlan);
const activePendingApproval = pendingApprovals[0] ?? null;
const {
beginLocalDispatch,
resetLocalDispatch,
localDispatchStartedAt,
isPreparingWorktree,
isSendBusy,
} = useLocalDispatchState({
activeThread,
activeLatestTurn,
phase,
activePendingApproval: activePendingApproval?.requestId ?? null,
activePendingUserInput: activePendingUserInput?.requestId ?? null,
threadError: activeThread?.error,
});
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
const nowIso = new Date(nowTick).toISOString();
const activeWorkStartedAt = deriveActiveWorkStartedAt(
activeLatestTurn,
activeThread?.session ?? null,
localDispatchStartedAt,
);
const isComposerApprovalState = activePendingApproval !== null;
const hasComposerHeader =
isComposerApprovalState ||
@@ -1152,9 +980,35 @@ export default function ChatView({ threadId }: ChatViewProps) {
]);
const completionDividerBeforeEntryId = useMemo(() => {
if (!latestTurnSettled) return null;
if (!activeLatestTurn?.startedAt) return null;
if (!activeLatestTurn.completedAt) return null;
if (!completionSummary) return null;
return deriveCompletionDividerBeforeEntryId(timelineEntries, activeLatestTurn);
}, [activeLatestTurn, completionSummary, latestTurnSettled, timelineEntries]);
const turnStartedAt = Date.parse(activeLatestTurn.startedAt);
const turnCompletedAt = Date.parse(activeLatestTurn.completedAt);
if (Number.isNaN(turnStartedAt)) return null;
if (Number.isNaN(turnCompletedAt)) return null;
let inRangeMatch: string | null = null;
let fallbackMatch: string | null = null;
for (const timelineEntry of timelineEntries) {
if (timelineEntry.kind !== "message") continue;
if (timelineEntry.message.role !== "assistant") continue;
const messageAt = Date.parse(timelineEntry.message.createdAt);
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) continue;
fallbackMatch = timelineEntry.id;
if (messageAt <= turnCompletedAt) {
inRangeMatch = timelineEntry.id;
}
}
return inRangeMatch ?? fallbackMatch;
}, [
activeLatestTurn?.completedAt,
activeLatestTurn?.startedAt,
completionSummary,
latestTurnSettled,
timelineEntries,
]);
const gitCwd = activeProject
? projectScriptCwd({
project: { cwd: activeProject.cwd },
@@ -1376,7 +1230,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
const setThreadError = useCallback(
(targetThreadId: ThreadId | null, error: string | null) => {
if (!targetThreadId) return;
if (useStore.getState().threads.some((thread) => thread.id === targetThreadId)) {
if (threads.some((thread) => thread.id === targetThreadId)) {
setStoreThreadError(targetThreadId, error);
return;
}
@@ -1390,7 +1244,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
});
},
[setStoreThreadError],
[setStoreThreadError, threads],
);
const focusComposer = useCallback(() => {
@@ -1557,7 +1411,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
worktreePath: options?.worktreePath ?? activeThread.worktreePath ?? null,
...(options?.env ? { extraEnv: options.env } : {}),
});
const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal
const openTerminalInput: Parameters<typeof api.terminal.open>[0] = shouldCreateNewTerminal
? {
threadId: activeThreadId,
terminalId: targetTerminalId,
@@ -2166,14 +2020,15 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
return [];
});
resetLocalDispatch();
setSendPhase("idle");
setSendStartedAt(null);
setComposerHighlightedItemId(null);
setComposerCursor(collapseExpandedComposerCursor(promptRef.current, promptRef.current.length));
setComposerTrigger(detectComposerTrigger(promptRef.current, promptRef.current.length));
dragDepthRef.current = 0;
setIsDragOverComposer(false);
setExpandedImage(null);
}, [resetLocalDispatch, threadId]);
}, [threadId]);
useEffect(() => {
let cancelled = false;
@@ -2306,6 +2161,37 @@ export default function ChatView({ threadId }: ChatViewProps) {
};
}, [phase]);
const beginSendPhase = useCallback((nextPhase: Exclude<SendPhase, "idle">) => {
setSendStartedAt((current) => current ?? new Date().toISOString());
setSendPhase(nextPhase);
}, []);
const resetSendPhase = useCallback(() => {
setSendPhase("idle");
setSendStartedAt(null);
}, []);
useEffect(() => {
if (sendPhase === "idle") {
return;
}
if (
phase === "running" ||
activePendingApproval !== null ||
activePendingUserInput !== null ||
activeThread?.error
) {
resetSendPhase();
}
}, [
activePendingApproval,
activePendingUserInput,
activeThread?.error,
phase,
resetSendPhase,
sendPhase,
]);
useEffect(() => {
if (!activeThreadId) return;
const previous = terminalOpenByThreadRef.current[activeThreadId] ?? false;
@@ -2643,7 +2529,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: Boolean(baseBranchForWorktree) });
beginSendPhase(baseBranchForWorktree ? "preparing-worktree" : "sending-turn");
const composerImagesSnapshot = [...composerImages];
const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];
@@ -2717,7 +2603,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
await (async () => {
// On first message: lock in branch + create worktree if needed.
if (baseBranchForWorktree) {
beginLocalDispatch({ preparingWorktree: true });
beginSendPhase("preparing-worktree");
const newBranch = buildTemporaryWorktreeBranchName();
const result = await createWorktreeMutation.mutateAsync({
cwd: activeProject.cwd,
@@ -2829,7 +2715,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
}
beginLocalDispatch({ preparingWorktree: false });
beginSendPhase("sending-turn");
const turnAttachments = await turnAttachmentsPromise;
await api.orchestration.dispatchCommand({
type: "thread.turn.start",
@@ -2886,7 +2772,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = false;
if (!turnStartSucceeded) {
resetLocalDispatch();
resetSendPhase();
}
};
@@ -3085,7 +2971,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
});
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: false });
beginSendPhase("sending-turn");
setThreadError(threadIdForSend, null);
setOptimisticUserMessages((existing) => [
...existing,
@@ -3154,19 +3040,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
err instanceof Error ? err.message : "Failed to send plan follow-up.",
);
sendInFlightRef.current = false;
resetLocalDispatch();
resetSendPhase();
}
},
[
activeThread,
activeProposedPlan,
beginLocalDispatch,
beginSendPhase,
forceStickToBottom,
isConnecting,
isSendBusy,
isServerThread,
persistThreadSettingsForNextTurn,
resetLocalDispatch,
resetSendPhase,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
@@ -3208,10 +3094,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
const nextThreadModelSelection: ModelSelection = selectedModelSelection;
sendInFlightRef.current = true;
beginLocalDispatch({ preparingWorktree: false });
beginSendPhase("sending-turn");
const finish = () => {
sendInFlightRef.current = false;
resetLocalDispatch();
resetSendPhase();
};
await api.orchestration
@@ -3246,10 +3132,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
createdAt,
});
})
.then(() => {
return waitForStartedServerThread(nextThreadId);
})
.then(() => {
.then(() => api.orchestration.getSnapshot())
.then((snapshot) => {
syncServerReadModel(snapshot);
// Signal that the plan sidebar should open on the new thread.
planSidebarOpenOnNextThreadRef.current = true;
return navigate({
@@ -3265,6 +3150,12 @@ export default function ChatView({ threadId }: ChatViewProps) {
threadId: nextThreadId,
})
.catch(() => undefined);
await api.orchestration
.getSnapshot()
.then((snapshot) => {
syncServerReadModel(snapshot);
})
.catch(() => undefined);
toastManager.add({
type: "error",
title: "Could not start implementation thread",
@@ -3277,17 +3168,18 @@ export default function ChatView({ threadId }: ChatViewProps) {
activeProject,
activeProposedPlan,
activeThread,
beginLocalDispatch,
beginSendPhase,
isConnecting,
isSendBusy,
isServerThread,
navigate,
resetLocalDispatch,
resetSendPhase,
runtimeMode,
selectedPromptEffort,
selectedModelSelection,
selectedProvider,
selectedProviderModels,
syncServerReadModel,
selectedModel,
]);
+12 -10
View File
@@ -25,7 +25,7 @@ import { cn } from "~/lib/utils";
import { readNativeApi } from "../nativeApi";
import { resolvePathLinkTarget } from "../terminal-links";
import { parseDiffRouteSearch, stripDiffSearchParams } from "../diffRouteSearch";
import { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { resolveDiffThemeName } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
@@ -55,18 +55,20 @@ const DIFF_PANEL_UNSAFE_CSS = `
--diffs-bg-separator-override: color-mix(in srgb, var(--background) 95%, var(--foreground));
--diffs-bg-buffer-override: color-mix(in srgb, var(--background) 90%, var(--foreground));
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--success));
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--success));
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--success));
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--success));
--diffs-addition-color-override: var(--diff-addition);
--diffs-bg-addition-override: color-mix(in srgb, var(--background) 92%, var(--diff-addition));
--diffs-bg-addition-number-override: color-mix(in srgb, var(--background) 88%, var(--diff-addition));
--diffs-bg-addition-hover-override: color-mix(in srgb, var(--background) 85%, var(--diff-addition));
--diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--background) 80%, var(--diff-addition));
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--destructive));
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--destructive));
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--destructive));
--diffs-deletion-color-override: var(--diff-deletion);
--diffs-bg-deletion-override: color-mix(in srgb, var(--background) 92%, var(--diff-deletion));
--diffs-bg-deletion-number-override: color-mix(in srgb, var(--background) 88%, var(--diff-deletion));
--diffs-bg-deletion-hover-override: color-mix(in srgb, var(--background) 85%, var(--diff-deletion));
--diffs-bg-deletion-emphasis-override: color-mix(
in srgb,
var(--background) 80%,
var(--destructive)
var(--diff-deletion)
);
background-color: var(--diffs-bg) !important;
@@ -165,7 +167,7 @@ export { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";
export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const navigate = useNavigate();
const { resolvedTheme } = useTheme();
const { resolvedTheme } = useAppearance();
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 { useTheme } from "../hooks/useTheme";
import { useAppearance } from "../hooks/useAppearance";
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 } = useTheme();
const { resolvedTheme } = useAppearance();
const diffThemeName = resolveDiffThemeName(resolvedTheme);
const workerPoolSize = useMemo(() => {
const cores =
@@ -970,9 +970,9 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
<span className="text-muted-foreground">Excluded</span>
) : (
<>
<span className="text-success">+{file.insertions}</span>
<span className="text-diff-addition">+{file.insertions}</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">-{file.deletions}</span>
<span className="text-diff-deletion">-{file.deletions}</span>
</>
)}
</span>
@@ -983,11 +983,11 @@ export default function GitActionsControl({ gitCwd, activeThreadId }: GitActions
</div>
</ScrollArea>
<div className="flex justify-end font-mono">
<span className="text-success">
<span className="text-diff-addition">
+{selectedFiles.reduce((sum, f) => sum + f.insertions, 0)}
</span>
<span className="text-muted-foreground"> / </span>
<span className="text-destructive">
<span className="text-diff-deletion">
-{selectedFiles.reduce((sum, f) => sum + f.deletions, 0)}
</span>
</div>
@@ -50,7 +50,7 @@ function createBaseServerConfig(): ServerConfig {
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: NOW_ISO,
models: [],
},
@@ -60,6 +60,10 @@ function createBaseServerConfig(): ServerConfig {
enableAssistantStreaming: false,
defaultThreadEnvMode: "local" as const,
textGenerationModelSelection: { provider: "codex" as const, model: "gpt-5.4-mini" },
colorMode: "system" as const,
activeLightThemeId: "t3code-light",
activeDarkThemeId: "t3code-dark",
customThemes: [],
providers: {
codex: { enabled: true, binaryPath: "", homePath: "", customModels: [] },
claudeAgent: { enabled: true, binaryPath: "", customModels: [] },
@@ -323,7 +327,7 @@ describe("Keybindings update toast", () => {
useStore.setState({
projects: [],
threads: [],
bootstrapComplete: false,
threadsHydrated: false,
});
});
+4 -137
View File
@@ -1,7 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { describe, expect, it } from "vitest";
import {
createThreadJumpHintVisibilityController,
getVisibleSidebarThreadIds,
resolveAdjacentThreadId,
getFallbackThreadIdAfterDelete,
@@ -9,7 +8,6 @@ import {
getProjectSortTimestamp,
hasUnseenCompletion,
isContextMenuPointerDown,
orderItemsByPreferredIds,
resolveProjectStatusIndicator,
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
@@ -17,9 +15,8 @@ import {
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
THREAD_JUMP_HINT_SHOW_DELAY_MS,
} from "./Sidebar.logic";
import { OrchestrationLatestTurn, ProjectId, ThreadId } from "@t3tools/contracts";
import { ProjectId, ThreadId } from "@t3tools/contracts";
import {
DEFAULT_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
@@ -30,7 +27,7 @@ import {
function makeLatestTurn(overrides?: {
completedAt?: string | null;
startedAt?: string | null;
}): OrchestrationLatestTurn {
}): Parameters<typeof hasUnseenCompletion>[0]["latestTurn"] {
return {
turnId: "turn-1" as never,
state: "completed",
@@ -55,68 +52,6 @@ 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 = {
@@ -164,50 +99,6 @@ describe("resolveSidebarNewThreadEnvMode", () => {
});
});
describe("orderItemsByPreferredIds", () => {
it("keeps preferred ids first, skips stale ids, and preserves the relative order of remaining items", () => {
const ordered = orderItemsByPreferredIds({
items: [
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
{ id: ProjectId.makeUnsafe("project-3"), name: "Three" },
],
preferredIds: [
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-missing"),
ProjectId.makeUnsafe("project-1"),
],
getId: (project) => project.id,
});
expect(ordered.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-3"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
]);
});
it("does not duplicate items when preferred ids repeat", () => {
const ordered = orderItemsByPreferredIds({
items: [
{ id: ProjectId.makeUnsafe("project-1"), name: "One" },
{ id: ProjectId.makeUnsafe("project-2"), name: "Two" },
],
preferredIds: [
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
ProjectId.makeUnsafe("project-2"),
],
getId: (project) => project.id,
});
expect(ordered.map((project) => project.id)).toEqual([
ProjectId.makeUnsafe("project-2"),
ProjectId.makeUnsafe("project-1"),
]);
});
});
describe("resolveAdjacentThreadId", () => {
it("resolves adjacent thread ids in ordered sidebar traversal", () => {
const threads = [
@@ -280,27 +171,6 @@ 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", () => {
@@ -559,9 +429,6 @@ 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", () => {
@@ -582,7 +449,6 @@ describe("getVisibleThreadsForProject", () => {
expect(result.visibleThreads.map((thread) => thread.id)).toEqual(
threads.map((thread) => thread.id),
);
expect(result.hiddenThreads).toEqual([]);
});
});
@@ -597,6 +463,7 @@ function makeProject(overrides: Partial<Project> = {}): Project {
model: "gpt-5.4",
...defaultModelSelection,
},
expanded: true,
createdAt: "2026-03-09T10:00:00.000Z",
updatedAt: "2026-03-09T10:00:00.000Z",
scripts: [],
+12 -147
View File
@@ -1,4 +1,3 @@
import * as React from "react";
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
import type { Thread } from "../types";
import { cn } from "../lib/utils";
@@ -9,7 +8,6 @@ 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;
@@ -17,10 +15,7 @@ type SidebarProject = {
createdAt?: string | undefined;
updatedAt?: string | undefined;
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt"> & {
latestUserMessageAt?: string | null;
messages?: Pick<Thread["messages"][number], "createdAt" | "role">[];
};
type SidebarThreadSortInput = Pick<Thread, "createdAt" | "updatedAt" | "messages">;
export type ThreadTraversalDirection = "previous" | "next";
@@ -48,95 +43,8 @@ const THREAD_STATUS_PRIORITY: Record<ThreadStatusPill["label"], number> = {
type ThreadStatusInput = Pick<
Thread,
"interactionMode" | "latestTurn" | "proposedPlans" | "session"
> & {
lastVisitedAt?: string | undefined;
};
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,
};
}
"interactionMode" | "latestTurn" | "lastVisitedAt" | "proposedPlans" | "session"
>;
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestTurn?.completedAt) return false;
@@ -161,46 +69,15 @@ export function resolveSidebarNewThreadEnvMode(input: {
return input.requestedEnvMode ?? input.defaultEnvMode;
}
export function orderItemsByPreferredIds<TItem, TId>(input: {
items: readonly TItem[];
preferredIds: readonly TId[];
getId: (item: TItem) => TId;
}): TItem[] {
const { getId, items, preferredIds } = input;
if (preferredIds.length === 0) {
return [...items];
}
const itemsById = new Map(items.map((item) => [getId(item), item] as const));
const preferredIdSet = new Set(preferredIds);
const emittedPreferredIds = new Set<TId>();
const ordered = preferredIds.flatMap((id) => {
if (emittedPreferredIds.has(id)) {
return [];
}
const item = itemsById.get(id);
if (!item) {
return [];
}
emittedPreferredIds.add(id);
return [item];
});
const remaining = items.filter((item) => !preferredIdSet.has(getId(item)));
return [...ordered, ...remaining];
}
export function getVisibleSidebarThreadIds<TThreadId>(
renderedProjects: readonly {
shouldShowThreadPanel?: boolean;
renderedThreads: readonly {
id: TThreadId;
}[];
}[],
): TThreadId[] {
return renderedProjects.flatMap((renderedProject) =>
renderedProject.shouldShowThreadPanel === false
? []
: renderedProject.renderedThreads.map((thread) => thread.id),
renderedProject.renderedThreads.map((thread) => thread.id),
);
}
@@ -360,15 +237,14 @@ export function resolveProjectStatusIndicator(
return highestPriorityStatus;
}
export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input: {
threads: readonly T[];
activeThreadId: T["id"] | undefined;
export function getVisibleThreadsForProject(input: {
threads: readonly Thread[];
activeThreadId: Thread["id"] | undefined;
isThreadListExpanded: boolean;
previewLimit: number;
}): {
hasHiddenThreads: boolean;
visibleThreads: T[];
hiddenThreads: T[];
visibleThreads: Thread[];
} {
const { activeThreadId, isThreadListExpanded, previewLimit, threads } = input;
const hasHiddenThreads = threads.length > previewLimit;
@@ -376,7 +252,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
if (!hasHiddenThreads || isThreadListExpanded) {
return {
hasHiddenThreads,
hiddenThreads: [],
visibleThreads: [...threads],
};
}
@@ -385,7 +260,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
if (!activeThreadId || previewThreads.some((thread) => thread.id === activeThreadId)) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -394,7 +268,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
if (!activeThread) {
return {
hasHiddenThreads: true,
hiddenThreads: threads.slice(previewLimit),
visibleThreads: previewThreads,
};
}
@@ -403,7 +276,6 @@ export function getVisibleThreadsForProject<T extends Pick<Thread, "id">>(input:
return {
hasHiddenThreads: true,
hiddenThreads: threads.filter((thread) => !visibleThreadIds.has(thread.id)),
visibleThreads: threads.filter((thread) => visibleThreadIds.has(thread.id)),
};
}
@@ -415,13 +287,9 @@ function toSortableTimestamp(iso: string | undefined): number | null {
}
function getLatestUserMessageTimestamp(thread: SidebarThreadSortInput): number {
if (thread.latestUserMessageAt) {
return toSortableTimestamp(thread.latestUserMessageAt) ?? Number.NEGATIVE_INFINITY;
}
let latestUserMessageTimestamp: number | null = null;
for (const message of thread.messages ?? []) {
for (const message of thread.messages) {
if (message.role !== "user") continue;
const messageTimestamp = toSortableTimestamp(message.createdAt);
if (messageTimestamp === null) continue;
@@ -449,7 +317,7 @@ function getThreadSortTimestamp(
}
export function sortThreadsForSidebar<
T extends Pick<Thread, "id" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
T extends Pick<Thread, "id" | "createdAt" | "updatedAt" | "messages">,
>(threads: readonly T[], sortOrder: SidebarThreadSortOrder): T[] {
return threads.toSorted((left, right) => {
const rightTimestamp = getThreadSortTimestamp(right, sortOrder);
@@ -462,7 +330,7 @@ export function sortThreadsForSidebar<
}
export function getFallbackThreadIdAfterDelete<
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
T extends Pick<Thread, "id" | "projectId" | "createdAt" | "updatedAt" | "messages">,
>(input: {
threads: readonly T[];
deletedThreadId: T["id"];
@@ -506,10 +374,7 @@ export function getProjectSortTimestamp(
return toSortableTimestamp(project.updatedAt ?? project.createdAt) ?? Number.NEGATIVE_INFINITY;
}
export function sortProjectsForSidebar<
TProject extends SidebarProject,
TThread extends Pick<Thread, "projectId" | "createdAt" | "updatedAt"> & SidebarThreadSortInput,
>(
export function sortProjectsForSidebar<TProject extends SidebarProject, TThread extends Thread>(
projects: readonly TProject[],
threads: readonly TThread[],
sortOrder: SidebarProjectSortOrder,
+139 -311
View File
@@ -21,7 +21,6 @@ import {
type MouseEvent,
type PointerEvent,
} from "react";
import { useShallow } from "zustand/react/shallow";
import {
DndContext,
type DragCancelEvent,
@@ -56,7 +55,6 @@ import { APP_STAGE_LABEL, APP_VERSION } from "../branding";
import { isTerminalFocused } from "../lib/terminalFocus";
import { isLinuxPlatform, isMacPlatform, newCommandId, newProjectId } from "../lib/utils";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
import {
resolveShortcutCommand,
shortcutLabelForCommand,
@@ -71,7 +69,6 @@ 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,16 +113,13 @@ import {
resolveSidebarNewThreadEnvMode,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
shouldClearThreadSelectionOnMouseDown,
sortProjectsForSidebar,
sortThreadsForSidebar,
useThreadJumpHintVisibility,
} from "./Sidebar.logic";
import { SidebarUpdatePill } from "./sidebar/SidebarUpdatePill";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useSettings, useUpdateSettings } from "~/hooks/useSettings";
import type { Project, Thread } from "../types";
const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
const THREAD_PREVIEW_LIMIT = 6;
@@ -142,80 +136,6 @@ const SIDEBAR_LIST_ANIMATION_OPTIONS = {
duration: 180,
easing: "ease-out",
} as const;
type SidebarThreadSnapshot = Pick<
Thread,
| "activities"
| "archivedAt"
| "branch"
| "createdAt"
| "id"
| "interactionMode"
| "latestTurn"
| "projectId"
| "proposedPlans"
| "session"
| "title"
| "updatedAt"
| "worktreePath"
> & {
lastVisitedAt?: string | undefined;
latestUserMessageAt: string | null;
};
type SidebarProjectSnapshot = Project & {
expanded: boolean;
};
const sidebarThreadSnapshotCache = new WeakMap<
Thread,
{ lastVisitedAt?: string | undefined; snapshot: SidebarThreadSnapshot }
>();
function getLatestUserMessageAt(thread: Thread): string | null {
let latestUserMessageAt: string | null = null;
for (const message of thread.messages) {
if (message.role !== "user") {
continue;
}
if (latestUserMessageAt === null || message.createdAt > latestUserMessageAt) {
latestUserMessageAt = message.createdAt;
}
}
return latestUserMessageAt;
}
function toSidebarThreadSnapshot(
thread: Thread,
lastVisitedAt: string | undefined,
): SidebarThreadSnapshot {
const cached = sidebarThreadSnapshotCache.get(thread);
if (cached && cached.lastVisitedAt === lastVisitedAt) {
return cached.snapshot;
}
const snapshot: SidebarThreadSnapshot = {
id: thread.id,
projectId: thread.projectId,
title: thread.title,
interactionMode: thread.interactionMode,
session: thread.session,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
archivedAt: thread.archivedAt,
latestTurn: thread.latestTurn,
lastVisitedAt,
branch: thread.branch,
worktreePath: thread.worktreePath,
activities: thread.activities,
proposedPlans: thread.proposedPlans,
latestUserMessageAt: getLatestUserMessageAt(thread),
};
sidebarThreadSnapshotCache.set(thread, { lastVisitedAt, snapshot });
return snapshot;
}
interface TerminalStatusIndicator {
label: "Terminal process running";
colorClass: string;
@@ -231,44 +151,6 @@ 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 {
@@ -439,17 +321,10 @@ function SortableProjectItem({
export default function Sidebar() {
const projects = useStore((store) => store.projects);
const serverThreads = useStore((store) => store.threads);
const { projectExpandedById, projectOrder, threadLastVisitedAtById } = useUiStateStore(
useShallow((store) => ({
projectExpandedById: store.projectExpandedById,
projectOrder: store.projectOrder,
threadLastVisitedAtById: store.threadLastVisitedAtById,
})),
);
const markThreadUnread = useUiStateStore((store) => store.markThreadUnread);
const toggleProject = useUiStateStore((store) => store.toggleProject);
const reorderProjects = useUiStateStore((store) => store.reorderProjects);
const threads = useStore((store) => store.threads);
const markThreadUnread = useStore((store) => store.markThreadUnread);
const toggleProject = useStore((store) => store.toggleProject);
const reorderProjects = useStore((store) => store.reorderProjects);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const getDraftThreadByProjectId = useComposerDraftStore(
(store) => store.getDraftThreadByProjectId,
@@ -481,14 +356,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, updateThreadJumpHintsVisibility } = useThreadJumpHintVisibility();
const [showThreadJumpHints, setShowThreadJumpHints] = useState(false);
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);
@@ -503,28 +378,6 @@ export default function Sidebar() {
const platform = navigator.platform;
const shouldBrowseForProjectImmediately = isElectron && !isLinuxDesktop;
const shouldShowProjectPathEntry = addingProject && !shouldBrowseForProjectImmediately;
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projects,
preferredIds: projectOrder,
getId: (project) => project.id,
});
}, [projectOrder, projects]);
const sidebarProjects = useMemo<SidebarProjectSnapshot[]>(
() =>
orderedProjects.map((project) => ({
...project,
expanded: projectExpandedById[project.id] ?? true,
})),
[orderedProjects, projectExpandedById],
);
const threads = useMemo(
() =>
serverThreads.map((thread) =>
toSidebarThreadSnapshot(thread, threadLastVisitedAtById[thread.id]),
),
[serverThreads, threadLastVisitedAtById],
);
const projectCwdById = useMemo(
() => new Map(projects.map((project) => [project.id, project.cwd] as const)),
[projects],
@@ -859,7 +712,7 @@ export default function Sidebar() {
}
if (clicked === "mark-unread") {
markThreadUnread(threadId, thread.latestTurn?.completedAt);
markThreadUnread(threadId);
return;
}
if (clicked === "copy-path") {
@@ -921,8 +774,7 @@ export default function Sidebar() {
if (clicked === "mark-unread") {
for (const id of ids) {
const thread = threads.find((candidate) => candidate.id === id);
markThreadUnread(id, thread?.latestTurn?.completedAt);
markThreadUnread(id);
}
clearSelection();
return;
@@ -953,7 +805,6 @@ export default function Sidebar() {
markThreadUnread,
removeFromSelection,
selectedThreadIds,
threads,
],
);
@@ -1096,12 +947,12 @@ export default function Sidebar() {
dragInProgressRef.current = false;
const { active, over } = event;
if (!over || active.id === over.id) return;
const activeProject = sidebarProjects.find((project) => project.id === active.id);
const overProject = sidebarProjects.find((project) => project.id === over.id);
const activeProject = projects.find((project) => project.id === active.id);
const overProject = projects.find((project) => project.id === over.id);
if (!activeProject || !overProject) return;
reorderProjects(activeProject.id, overProject.id);
},
[appSettings.sidebarProjectSortOrder, reorderProjects, sidebarProjects],
[appSettings.sidebarProjectSortOrder, projects, reorderProjects],
);
const handleProjectDragStart = useCallback(
@@ -1161,9 +1012,8 @@ export default function Sidebar() {
[threads],
);
const sortedProjects = useMemo(
() =>
sortProjectsForSidebar(sidebarProjects, visibleThreads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, sidebarProjects, visibleThreads],
() => sortProjectsForSidebar(projects, visibleThreads, appSettings.sidebarProjectSortOrder),
[appSettings.sidebarProjectSortOrder, projects, visibleThreads],
);
const isManualProjectSorting = appSettings.sidebarProjectSortOrder === "manual";
const renderedProjects = useMemo(
@@ -1173,18 +1023,14 @@ export default function Sidebar() {
visibleThreads.filter((thread) => thread.projectId === project.id),
appSettings.sidebarThreadSortOrder,
);
const threadStatuses = new Map(
projectThreads.map((thread) => [
thread.id,
const projectStatus = resolveProjectStatusIndicator(
projectThreads.map((thread) =>
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);
@@ -1193,35 +1039,25 @@ export default function Sidebar() {
? (projectThreads.find((thread) => thread.id === activeThreadId) ?? null)
: null;
const shouldShowThreadPanel = project.expanded || pinnedCollapsedThread !== null;
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 { hasHiddenThreads, visibleThreads: visibleProjectThreads } =
getVisibleThreadsForProject({
threads: projectThreads,
activeThreadId,
isThreadListExpanded,
previewLimit: THREAD_PREVIEW_LIMIT,
});
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,
};
@@ -1234,22 +1070,23 @@ export default function Sidebar() {
visibleThreads,
],
);
const visibleSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
const threadJumpCommandById = useMemo(() => {
const mapping = new Map<ThreadId, NonNullable<ReturnType<typeof threadJumpCommandForIndex>>>();
for (const [visibleThreadIndex, threadId] of visibleSidebarThreadIds.entries()) {
const jumpCommand = threadJumpCommandForIndex(visibleThreadIndex);
if (!jumpCommand) {
return mapping;
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;
}
mapping.set(threadId, jumpCommand);
}
return mapping;
}, [visibleSidebarThreadIds]);
}, [renderedProjects]);
const threadJumpThreadIds = useMemo(
() => [...threadJumpCommandById.keys()],
[threadJumpCommandById],
@@ -1264,7 +1101,10 @@ export default function Sidebar() {
}
return mapping;
}, [keybindings, sidebarShortcutLabelOptions, threadJumpCommandById]);
const orderedSidebarThreadIds = visibleSidebarThreadIds;
const orderedSidebarThreadIds = useMemo(
() => getVisibleSidebarThreadIds(renderedProjects),
[renderedProjects],
);
useEffect(() => {
const getShortcutContext = () => ({
@@ -1273,7 +1113,7 @@ export default function Sidebar() {
});
const onWindowKeyDown = (event: KeyboardEvent) => {
updateThreadJumpHintsVisibility(
setShowThreadJumpHints(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1321,7 +1161,7 @@ export default function Sidebar() {
};
const onWindowKeyUp = (event: KeyboardEvent) => {
updateThreadJumpHintsVisibility(
setShowThreadJumpHints(
shouldShowThreadJumpHints(event, keybindings, {
platform,
context: getShortcutContext(),
@@ -1330,7 +1170,7 @@ export default function Sidebar() {
};
const onWindowBlur = () => {
updateThreadJumpHintsVisibility(false);
setShowThreadJumpHints(false);
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -1350,7 +1190,6 @@ export default function Sidebar() {
routeTerminalOpen,
routeThreadId,
threadJumpThreadIds,
updateThreadJumpHintsVisibility,
]);
function renderProjectItem(
@@ -1359,14 +1198,11 @@ export default function Sidebar() {
) {
const {
hasHiddenThreads,
hiddenThreadStatus,
orderedProjectThreadIds,
project,
projectStatus,
projectThreads,
threadStatuses,
renderedThreads,
showEmptyThreadState,
shouldShowThreadPanel,
isThreadListExpanded,
} = renderedProject;
@@ -1377,45 +1213,37 @@ export default function Sidebar() {
const jumpLabel = threadJumpLabelById.get(thread.id) ?? null;
const isThreadRunning =
thread.session?.status === "running" && thread.session.activeTurnId != null;
const threadStatus = threadStatuses.get(thread.id) ?? null;
const threadStatus = resolveThreadStatusPill({
thread,
hasPendingApprovals: derivePendingApprovals(thread.activities).length > 0,
hasPendingUserInput: derivePendingUserInputs(thread.activities).length > 0,
});
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
onMouseLeave={() => {
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
onMouseEnter={() => {
setHoveredThreadId(thread.id);
}}
onBlurCapture={(event) => {
const currentTarget = event.currentTarget;
requestAnimationFrame(() => {
if (currentTarget.contains(document.activeElement)) {
return;
}
setConfirmingArchiveThreadId((current) => (current === thread.id ? null : current));
});
onMouseLeave={() => {
setHoveredThreadId((current) => (current === thread.id ? null : current));
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 isolate`}
})} relative`}
onClick={(event) => {
handleThreadClick(event, thread.id, orderedProjectThreadIds);
}}
@@ -1426,6 +1254,7 @@ 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,
@@ -1462,7 +1291,18 @@ export default function Sidebar() {
<TooltipPopup side="top">{prStatus.tooltip}</TooltipPopup>
</Tooltip>
)}
{threadStatus && <ThreadStatusLabel status={threadStatus} />}
{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>
)}
{renamingThreadId === thread.id ? (
<input
ref={(el) => {
@@ -1512,18 +1352,10 @@ export default function Sidebar() {
</span>
)}
<div className="flex min-w-12 justify-end">
{isConfirmingArchive ? (
{confirmingArchiveThreadId === thread.id && !isThreadRunning ? (
<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) => {
@@ -1535,84 +1367,80 @@ export default function Sidebar() {
setConfirmingArchiveThreadId((current) =>
current === thread.id ? null : current,
);
setHoveredThreadId((current) => (current === thread.id ? null : current));
void attemptArchiveThread(thread.id);
}}
>
Confirm
</button>
) : !isThreadRunning ? (
) : hoveredThreadId === thread.id && !isThreadRunning ? (
appSettings.confirmThreadArchive ? (
<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>
<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>
) : (
<Tooltip>
<TooltipTrigger
render={
<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>
<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>
}
/>
<TooltipPopup side="top">Archive</TooltipPopup>
</Tooltip>
)
) : 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>
) : (
<>
{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>
)}
</>
)}
</div>
</div>
</SidebarMenuSubButton>
@@ -1707,16 +1535,6 @@ 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 && (
@@ -1730,10 +1548,7 @@ export default function Sidebar() {
expandThreadListForProject(project.id);
}}
>
<span className="flex min-w-0 flex-1 items-center gap-2">
{hiddenThreadStatus && <ThreadStatusLabel status={hiddenThreadStatus} compact />}
<span>Show more</span>
</span>
<span>Show more</span>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
)}
@@ -2044,6 +1859,7 @@ export default function Sidebar() {
</Tooltip>
</div>
</div>
{shouldShowProjectPathEntry && (
<div className="mb-2 px-1">
{isElectron && (
@@ -2094,6 +1910,18 @@ export default function Sidebar() {
{addProjectError}
</p>
)}
<div className="mt-1.5 px-0.5">
<button
type="button"
className="text-[11px] text-muted-foreground/50 transition-colors hover:text-muted-foreground"
onClick={() => {
setAddingProject(false);
setAddProjectError(null);
}}
>
Cancel
</button>
</div>
</div>
)}
@@ -50,7 +50,6 @@ 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, useLayoutEffect, useRef } from "react";
import { memo } from "react";
import { type ComposerSlashCommand, type ComposerTriggerKind } from "../../composer-logic";
import { BotIcon } from "lucide-react";
import { cn } from "~/lib/utils";
@@ -41,19 +41,8 @@ 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(
@@ -61,10 +50,7 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
);
}}
>
<div
ref={listRef}
className="relative overflow-hidden rounded-xl border border-border/80 bg-popover/96 shadow-lg/8 backdrop-blur-xs"
>
<div 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
@@ -72,7 +58,6 @@ export const ComposerCommandMenu = memo(function ComposerCommandMenu(props: {
item={item}
resolvedTheme={props.resolvedTheme}
isActive={props.activeItemId === item.id}
onHighlight={props.onHighlightedItemChange}
onSelect={props.onSelect}
/>
))}
@@ -95,20 +80,15 @@ 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 hover:bg-transparent hover:text-inherit data-highlighted:bg-transparent data-highlighted:text-inherit",
props.isActive && "bg-accent! text-accent-foreground!",
"cursor-pointer select-none gap-2",
props.isActive && "bg-accent text-accent-foreground",
)}
onMouseMove={() => {
if (!props.isActive) props.onHighlight(props.item.id);
}}
onMouseDown={(event) => {
event.preventDefault();
}}
@@ -13,9 +13,9 @@ export const DiffStatLabel = memo(function DiffStatLabel(props: {
return (
<>
{showParentheses && <span className="text-muted-foreground/70">(</span>}
<span className="text-success">+{additions}</span>
<span className="text-diff-addition">+{additions}</span>
<span className="mx-0.5 text-muted-foreground/70">/</span>
<span className="text-destructive">-{deletions}</span>
<span className="text-diff-deletion">-{deletions}</span>
{showParentheses && <span className="text-muted-foreground/70">)</span>}
</>
);
@@ -264,14 +264,9 @@ 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;
};
@@ -488,7 +483,6 @@ 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",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: new Date().toISOString(),
models: [
{
@@ -57,7 +57,7 @@ const TEST_PROVIDERS: ReadonlyArray<ServerProvider> = [
installed: true,
version: "1.0.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: new Date().toISOString(),
models: [
{
@@ -110,19 +110,6 @@ 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;
@@ -254,93 +241,6 @@ 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",
auth: { status: "authenticated" },
authStatus: "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",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [
{
@@ -71,41 +71,6 @@ 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({
@@ -191,7 +156,6 @@ describe("getComposerProviderState", () => {
promptEffort: "high",
modelOptionsForDispatch: {
reasoningEffort: "high",
fastMode: false,
},
});
});
@@ -304,116 +268,7 @@ 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 "@t3tools/shared/model";
} from "../../providerModels";
import { TraitsMenuContent, TraitsPicker } from "./TraitsPicker";
export type ComposerProviderStateInput = {
provider: ProviderKind;
@@ -0,0 +1,677 @@
import {
ChevronDownIcon,
CopyIcon,
MonitorIcon,
MoonIcon,
RotateCcwIcon,
SunIcon,
Trash2Icon,
UploadIcon,
} from "lucide-react";
import { Schema, SchemaIssue } from "effect";
import { type ChangeEvent, useCallback, useMemo, useRef, useState } from "react";
import {
ThemeDocumentSchema,
type ColorMode,
type ThemeDerivedOverrides,
type ThemeDocument,
type ThemeMode,
} from "@t3tools/contracts";
import {
BUILTIN_THEME_PRESETS,
canonicalizeThemeDocument,
getDefaultThemeId,
getThemeDocumentsForMode,
serializeThemeDocument,
} from "@t3tools/shared/appearance/registry";
import { cn } from "../../lib/utils";
import { useAppearance } from "../../hooks/useAppearance";
import { useUpdateSettings } from "../../hooks/useSettings";
import { toastManager } from "../ui/toast";
import { Button } from "../ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "../ui/collapsible";
import { Input } from "../ui/input";
import { SettingsPageContainer, SettingsSection } from "./SettingsPanels";
import {
createDuplicateTheme,
normalizeImportedThemeDocument,
replaceCustomTheme,
updateThemeDocument,
} from "./appearance.logic";
const COLOR_MODE_OPTIONS = [
{ value: "system", label: "System", icon: MonitorIcon },
{ value: "light", label: "Light", icon: SunIcon },
{ value: "dark", label: "Dark", icon: MoonIcon },
] as const satisfies ReadonlyArray<{
value: ColorMode;
label: string;
icon: typeof MonitorIcon;
}>;
const MODE_COPY = {
light: {
label: "Light Theme",
modeLabel: "Light",
importTitle: "Import Light Theme",
emptyDescription: "Imported or duplicated light theme.",
},
dark: {
label: "Dark Theme",
modeLabel: "Dark",
importTitle: "Import Dark Theme",
emptyDescription: "Imported or duplicated dark theme.",
},
} as const satisfies Record<
ThemeMode,
{
label: string;
modeLabel: string;
importTitle: string;
emptyDescription: string;
}
>;
const OVERRIDE_FIELDS: ReadonlyArray<{
key: keyof ThemeDerivedOverrides;
label: string;
placeholder: string;
}> = [
{ key: "background", label: "Background", placeholder: "Auto" },
{ key: "foreground", label: "Foreground", placeholder: "Auto" },
{ key: "card", label: "Card", placeholder: "Auto" },
{ key: "cardForeground", label: "Card text", placeholder: "Auto" },
{ key: "popover", label: "Popover", placeholder: "Auto" },
{ key: "popoverForeground", label: "Popover text", placeholder: "Auto" },
{ key: "primary", label: "Primary", placeholder: "Auto" },
{ key: "primaryForeground", label: "Primary text", placeholder: "Auto" },
{ key: "secondary", label: "Secondary", placeholder: "Auto" },
{ key: "secondaryForeground", label: "Secondary text", placeholder: "Auto" },
{ key: "muted", label: "Muted", placeholder: "Auto" },
{ key: "mutedForeground", label: "Muted text", placeholder: "Auto" },
{ key: "accentSurface", label: "Accent surface", placeholder: "Auto" },
{ key: "accentForeground", label: "Accent text", placeholder: "Auto" },
{ key: "border", label: "Border", placeholder: "Auto" },
{ key: "input", label: "Input", placeholder: "Auto" },
{ key: "ring", label: "Ring", placeholder: "Auto" },
{ key: "destructive", label: "Destructive", placeholder: "Auto" },
{ key: "destructiveForeground", label: "Destructive text", placeholder: "Auto" },
{ key: "info", label: "Info", placeholder: "Auto" },
{ key: "infoForeground", label: "Info text", placeholder: "Auto" },
{ key: "success", label: "Success", placeholder: "Auto" },
{ key: "successForeground", label: "Success text", placeholder: "Auto" },
{ key: "warning", label: "Warning", placeholder: "Auto" },
{ key: "warningForeground", label: "Warning text", placeholder: "Auto" },
{ key: "diffAddition", label: "Diff addition", placeholder: "Auto" },
{ key: "diffDeletion", label: "Diff deletion", placeholder: "Auto" },
{ key: "sidebar", label: "Sidebar", placeholder: "Auto" },
{ key: "sidebarForeground", label: "Sidebar text", placeholder: "Auto" },
{ key: "sidebarAccent", label: "Sidebar accent", placeholder: "Auto" },
{ key: "sidebarAccentForeground", label: "Sidebar accent text", placeholder: "Auto" },
{ key: "sidebarBorder", label: "Sidebar border", placeholder: "Auto" },
];
function ThemeCard({
theme,
isSelected,
onSelect,
}: {
theme: ThemeDocument;
isSelected: boolean;
onSelect: () => void;
}) {
return (
<button
type="button"
onClick={onSelect}
className={cn(
"group relative flex items-center gap-3 overflow-hidden rounded-xl border p-2.5 text-left transition-all",
isSelected
? "border-primary bg-primary/6"
: "border-border bg-card hover:border-primary/40 hover:bg-accent/40",
)}
>
<div
className="h-9 w-12 shrink-0 rounded-lg border border-black/8"
style={{
background: `linear-gradient(135deg, ${theme.background}, ${theme.accent})`,
}}
/>
<div className="min-w-0 flex-1">
<p className="truncate text-xs font-medium text-foreground">{theme.name}</p>
<p className="mt-0.5 text-[11px] text-muted-foreground">
{theme.origin === "custom" ? "Custom" : "Builtin"}
</p>
</div>
{isSelected ? <span className="size-1.5 shrink-0 rounded-full bg-primary" /> : null}
</button>
);
}
function ColorField({
label,
value,
onChange,
}: {
label: string;
value: string;
onChange: (value: string) => void;
}) {
return (
<label className="flex items-center gap-2">
<input
type="color"
value={value}
onChange={(event) => onChange(event.target.value)}
className="h-7 w-8 cursor-pointer rounded border-0 bg-transparent p-0"
/>
<div className="min-w-0">
<span className="block text-[11px] font-medium text-muted-foreground">{label}</span>
<code className="block text-[11px] text-foreground/70">{value}</code>
</div>
</label>
);
}
function ThemeEditor({
theme,
onChange,
}: {
theme: ThemeDocument;
onChange: (updater: (theme: ThemeDocument) => ThemeDocument) => void;
}) {
return (
<div className="space-y-3">
{/* Colors row */}
<div className="flex flex-wrap items-center gap-x-5 gap-y-2">
<ColorField
label="Accent"
value={theme.accent}
onChange={(accent) => onChange((currentTheme) => ({ ...currentTheme, accent }))}
/>
<ColorField
label="Background"
value={theme.background}
onChange={(background) => onChange((currentTheme) => ({ ...currentTheme, background }))}
/>
<ColorField
label="Foreground"
value={theme.foreground}
onChange={(foreground) => onChange((currentTheme) => ({ ...currentTheme, foreground }))}
/>
</div>
{/* Scale + typography */}
<div className="grid gap-2.5 sm:grid-cols-2 lg:grid-cols-4">
<label className="grid gap-1">
<span className="text-[11px] font-medium text-muted-foreground">Radius</span>
<Input
value={theme.radius}
onChange={(event) =>
onChange((currentTheme) => ({ ...currentTheme, radius: event.target.value }))
}
placeholder="0.625rem"
/>
</label>
<label className="grid gap-1">
<span className="text-[11px] font-medium text-muted-foreground">Font size</span>
<Input
value={theme.fontSize}
onChange={(event) =>
onChange((currentTheme) => ({ ...currentTheme, fontSize: event.target.value }))
}
placeholder="16px"
/>
</label>
<label className="grid gap-1">
<span className="text-[11px] font-medium text-muted-foreground">UI font</span>
<Input
value={theme.uiFontFamily}
onChange={(event) =>
onChange((currentTheme) => ({ ...currentTheme, uiFontFamily: event.target.value }))
}
placeholder="font-family stack"
/>
</label>
<label className="grid gap-1">
<span className="text-[11px] font-medium text-muted-foreground">Code font</span>
<Input
value={theme.codeFontFamily}
onChange={(event) =>
onChange((currentTheme) => ({ ...currentTheme, codeFontFamily: event.target.value }))
}
placeholder="font-family stack"
/>
</label>
</div>
{/* Contrast */}
<label className="flex items-center gap-3">
<span className="text-[11px] font-medium text-muted-foreground">Contrast</span>
<input
type="range"
min={0}
max={100}
step={1}
value={theme.contrast}
onChange={(event) =>
onChange((currentTheme) => ({
...currentTheme,
contrast: Number.parseInt(event.target.value, 10),
}))
}
className="h-1.5 min-w-24 flex-1 cursor-pointer accent-primary"
/>
<code className="text-[11px] tabular-nums text-muted-foreground">{theme.contrast}</code>
</label>
{/* Advanced overrides */}
<Collapsible defaultOpen={false}>
<CollapsibleTrigger className="flex items-center gap-1.5 text-left">
<ChevronDownIcon className="size-3.5 text-muted-foreground" />
<span className="text-[11px] font-medium text-muted-foreground">
Advanced token overrides
</span>
</CollapsibleTrigger>
<CollapsibleContent className="pt-2.5">
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{OVERRIDE_FIELDS.map((field) => (
<label key={field.key} className="grid gap-1">
<span className="text-[11px] text-muted-foreground">{field.label}</span>
<Input
value={theme.overrides?.[field.key] ?? ""}
placeholder={field.placeholder}
onChange={(event) =>
onChange((currentTheme) => {
const value = event.target.value.trim();
const nextOverrides = {
...currentTheme.overrides,
[field.key]: value || undefined,
} satisfies ThemeDerivedOverrides;
const hasOverrides = Object.values(nextOverrides).some(Boolean);
if (hasOverrides) {
return {
...currentTheme,
overrides: nextOverrides,
};
}
const { overrides: _overrides, ...nextTheme } = currentTheme;
return nextTheme;
})
}
/>
</label>
))}
</div>
</CollapsibleContent>
</Collapsible>
</div>
);
}
export function AppearanceSettingsPanel() {
const { colorMode, activeLightTheme, activeDarkTheme, customThemes, setColorMode, setThemeId } =
useAppearance();
const { updateSettings } = useUpdateSettings();
const lightImportInputRef = useRef<HTMLInputElement>(null);
const darkImportInputRef = useRef<HTMLInputElement>(null);
const [importErrors, setImportErrors] = useState<Record<ThemeMode, string | null>>({
light: null,
dark: null,
});
const themeLibraryByMode = useMemo(
() => ({
light: getThemeDocumentsForMode("light", customThemes).map((theme) => ({
theme,
description:
BUILTIN_THEME_PRESETS.find((preset) => preset.theme.id === theme.id)?.description ??
MODE_COPY.light.emptyDescription,
})),
dark: getThemeDocumentsForMode("dark", customThemes).map((theme) => ({
theme,
description:
BUILTIN_THEME_PRESETS.find((preset) => preset.theme.id === theme.id)?.description ??
MODE_COPY.dark.emptyDescription,
})),
}),
[customThemes],
);
const activeThemeByMode = useMemo(
() =>
({
light: activeLightTheme,
dark: activeDarkTheme,
}) as const satisfies Record<ThemeMode, ThemeDocument>,
[activeLightTheme, activeDarkTheme],
);
const updateModeSelection = useCallback(
(mode: ThemeMode, themeId: string) => {
setThemeId(mode, themeId);
},
[setThemeId],
);
const saveTheme = useCallback(
(themeDocument: ThemeDocument) => {
updateSettings({
...(themeDocument.mode === "dark"
? { activeDarkThemeId: themeDocument.id }
: { activeLightThemeId: themeDocument.id }),
customThemes: replaceCustomTheme(
customThemes,
canonicalizeThemeDocument(themeDocument, "custom"),
),
});
},
[customThemes, updateSettings],
);
const getEditableTheme = useCallback(
(mode: ThemeMode, announceDuplicate: boolean): ThemeDocument => {
const activeTheme = activeThemeByMode[mode];
if (activeTheme.origin === "custom") {
return activeTheme;
}
const duplicate = createDuplicateTheme(activeTheme, customThemes);
if (announceDuplicate) {
toastManager.add({
type: "info",
title: "Created editable copy",
description: `${activeTheme.name} was duplicated into ${duplicate.name}.`,
});
}
return duplicate;
},
[activeThemeByMode, customThemes],
);
const handleThemeChange = useCallback(
(mode: ThemeMode, updater: (themeDocument: ThemeDocument) => ThemeDocument) => {
const baseTheme = getEditableTheme(mode, true);
const nextTheme = updateThemeDocument(baseTheme, updater);
saveTheme(nextTheme);
},
[getEditableTheme, saveTheme],
);
const handleDuplicateTheme = useCallback(
(mode: ThemeMode) => {
const duplicate = createDuplicateTheme(activeThemeByMode[mode], customThemes);
updateSettings({
...(mode === "dark"
? { activeDarkThemeId: duplicate.id }
: { activeLightThemeId: duplicate.id }),
customThemes: [...customThemes, duplicate],
});
toastManager.add({
type: "success",
title: "Theme duplicated",
description: `${duplicate.name} is now selected and editable.`,
});
},
[activeThemeByMode, customThemes, updateSettings],
);
const handleDeleteTheme = useCallback(
(mode: ThemeMode) => {
const activeTheme = activeThemeByMode[mode];
if (activeTheme.origin !== "custom") return;
updateSettings({
...(mode === "dark"
? { activeDarkThemeId: getDefaultThemeId("dark") }
: { activeLightThemeId: getDefaultThemeId("light") }),
customThemes: customThemes.filter((theme) => theme.id !== activeTheme.id),
});
toastManager.add({
type: "success",
title: "Custom theme deleted",
description: `${activeTheme.name} was removed from your library.`,
});
},
[activeThemeByMode, customThemes, updateSettings],
);
const handleResetCurrent = useCallback(
(mode: ThemeMode) => {
const activeTheme = activeThemeByMode[mode];
if (activeTheme.origin === "builtin") {
updateModeSelection(mode, getDefaultThemeId(mode));
return;
}
const builtinDefault = BUILTIN_THEME_PRESETS.find(
(preset) => preset.theme.id === getDefaultThemeId(mode),
)!.theme;
const resetTheme = canonicalizeThemeDocument(
{
...builtinDefault,
id: activeTheme.id,
name: activeTheme.name,
origin: "custom",
},
"custom",
);
saveTheme(resetTheme);
toastManager.add({
type: "success",
title: "Theme reset",
description: `${activeTheme.name} now matches the default ${MODE_COPY[mode].modeLabel.toLowerCase()} preset.`,
});
},
[activeThemeByMode, saveTheme, updateModeSelection],
);
const handleCopyTheme = useCallback(
async (mode: ThemeMode) => {
const activeTheme = activeThemeByMode[mode];
try {
await navigator.clipboard.writeText(serializeThemeDocument(activeTheme));
toastManager.add({
type: "success",
title: "Theme JSON copied",
description: `${activeTheme.name} is ready to paste or share.`,
});
} catch (error) {
toastManager.add({
type: "error",
title: "Could not copy theme JSON",
description: error instanceof Error ? error.message : "Clipboard access failed.",
});
}
},
[activeThemeByMode],
);
const handleImportTheme = useCallback(
(mode: ThemeMode) => async (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
event.target.value = "";
if (!file) return;
setImportErrors((current) => ({ ...current, [mode]: null }));
let rawJson: unknown;
try {
rawJson = JSON.parse(await file.text());
} catch (error) {
const message = error instanceof Error ? error.message : "Invalid JSON.";
setImportErrors((current) => ({ ...current, [mode]: message }));
return;
}
let decoded: ThemeDocument;
try {
decoded = Schema.decodeUnknownSync(ThemeDocumentSchema)(rawJson);
} catch (error) {
const message =
typeof error === "object" && error !== null && "issue" in error
? SchemaIssue.makeFormatterDefault()((error as { issue: never }).issue)
: error instanceof Error
? error.message
: "Invalid theme document.";
setImportErrors((current) => ({ ...current, [mode]: message }));
return;
}
if (decoded.mode !== mode) {
setImportErrors((current) => ({
...current,
[mode]: `Imported theme mode mismatch. Expected ${mode}, received ${decoded.mode}.`,
}));
return;
}
const existingIds = new Set([
...BUILTIN_THEME_PRESETS.map((preset) => preset.theme.id),
...customThemes.map((theme) => theme.id),
]);
const normalized = normalizeImportedThemeDocument(decoded, existingIds);
updateSettings({
...(mode === "dark"
? { activeDarkThemeId: normalized.id }
: { activeLightThemeId: normalized.id }),
customThemes: [...customThemes, normalized],
});
toastManager.add({
type: "success",
title: MODE_COPY[mode].importTitle,
description:
normalized.id === decoded.id
? `${normalized.name} is now available in your custom ${mode} theme library.`
: `${normalized.name} was imported as ${normalized.id} to avoid an id conflict.`,
});
},
[customThemes, updateSettings],
);
return (
<SettingsPageContainer>
<SettingsSection title="Color Mode">
<div className="grid gap-2 px-4 py-3 sm:grid-cols-3 sm:px-5">
{COLOR_MODE_OPTIONS.map((option) => {
const Icon = option.icon;
const selected = colorMode === option.value;
return (
<button
key={option.value}
type="button"
onClick={() => setColorMode(option.value)}
className={cn(
"flex items-center gap-2.5 rounded-xl border px-3 py-2.5 text-left transition-colors",
selected
? "border-primary bg-primary/6 text-foreground"
: "border-border bg-card/60 text-muted-foreground hover:border-primary/40 hover:text-foreground",
)}
>
<span
className={cn(
"flex size-8 items-center justify-center rounded-lg",
selected ? "bg-primary text-primary-foreground" : "bg-accent text-foreground",
)}
>
<Icon className="size-3.5" />
</span>
<span>
<span className="block text-xs font-medium">{option.label}</span>
<span className="block text-[11px] text-muted-foreground">
{option.value === "system"
? "Follow OS preference"
: option.value === "light"
? "Always light"
: "Always dark"}
</span>
</span>
</button>
);
})}
</div>
</SettingsSection>
{(["light", "dark"] as const satisfies ReadonlyArray<ThemeMode>).map((mode) => {
const activeTheme = activeThemeByMode[mode];
const importInputRef = mode === "light" ? lightImportInputRef : darkImportInputRef;
return (
<SettingsSection
key={mode}
title={MODE_COPY[mode].label}
headerAction={
<div className="flex items-center gap-1.5">
<Button size="xs" variant="outline" onClick={() => importInputRef.current?.click()}>
<UploadIcon className="size-3" />
Import
</Button>
<Button size="xs" variant="outline" onClick={() => handleCopyTheme(mode)}>
<CopyIcon className="size-3" />
Copy
</Button>
<Button size="xs" variant="outline" onClick={() => handleDuplicateTheme(mode)}>
Duplicate
</Button>
<Button size="xs" variant="outline" onClick={() => handleResetCurrent(mode)}>
<RotateCcwIcon className="size-3" />
Reset
</Button>
{activeTheme.origin === "custom" ? (
<Button
size="xs"
variant="destructive-outline"
onClick={() => handleDeleteTheme(mode)}
>
<Trash2Icon className="size-3" />
Delete
</Button>
) : null}
</div>
}
>
<div className="px-4 py-3 sm:px-5">
{/* Theme grid */}
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4">
{themeLibraryByMode[mode].map((entry) => (
<ThemeCard
key={entry.theme.id}
theme={entry.theme}
isSelected={activeTheme.id === entry.theme.id}
onSelect={() => updateModeSelection(mode, entry.theme.id)}
/>
))}
</div>
<input
ref={importInputRef}
type="file"
accept="application/json,.json"
className="hidden"
onChange={handleImportTheme(mode)}
/>
{importErrors[mode] ? (
<div className="mt-3 rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2 text-xs text-destructive-foreground">
<p className="font-medium">Import failed</p>
<p className="mt-0.5 whitespace-pre-wrap">{importErrors[mode]}</p>
</div>
) : null}
{/* Inline editor */}
<div className="mt-3 border-t border-border pt-3">
<ThemeEditor
theme={activeTheme}
onChange={(updater) => handleThemeChange(mode, updater)}
/>
</div>
</div>
</SettingsSection>
);
})}
</SettingsPageContainer>
);
}
@@ -33,7 +33,6 @@ 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 {
@@ -60,21 +59,6 @@ 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",
@@ -146,14 +130,13 @@ function getProviderSummary(provider: ServerProvider | undefined) {
detail: provider.message ?? "CLI not detected on PATH.",
};
}
if (provider.auth.status === "authenticated") {
const authLabel = provider.auth.label ?? provider.auth.type;
if (provider.authStatus === "authenticated") {
return {
headline: authLabel ? `Authenticated · ${authLabel}` : "Authenticated",
headline: "Authenticated",
detail: provider.message ?? null,
};
}
if (provider.auth.status === "unauthenticated") {
if (provider.authStatus === "unauthenticated") {
return {
headline: "Not authenticated",
detail: provider.message ?? null,
@@ -214,7 +197,7 @@ function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }
);
}
function SettingsSection({
export function SettingsSection({
title,
icon,
headerAction,
@@ -241,7 +224,7 @@ function SettingsSection({
);
}
function SettingsRow({
export function SettingsRow({
title,
description,
status,
@@ -280,7 +263,7 @@ function SettingsRow({
);
}
function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
export function SettingResetButton({ label, onClick }: { label: string; onClick: () => void }) {
return (
<Tooltip>
<TooltipTrigger
@@ -304,7 +287,7 @@ function SettingResetButton({ label, onClick }: { label: string; onClick: () =>
);
}
function SettingsPageContainer({ children }: { children: ReactNode }) {
export 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>
@@ -440,9 +423,8 @@ function AboutVersionSection() {
}
export function useSettingsRestore(onRestored?: () => void) {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { resetSettings } = useUpdateSettings();
const { updateSettings, resetSettings } = useUpdateSettings();
const isGitWritingModelDirty = !Equal.equals(
settings.textGenerationModelSelection ?? null,
@@ -456,7 +438,10 @@ export function useSettingsRestore(onRestored?: () => void) {
const changedSettingLabels = useMemo(
() => [
...(theme !== "system" ? ["Theme"] : []),
...(settings.colorMode !== "system" ? ["Color mode"] : []),
...(settings.activeLightThemeId !== "t3code-light" ? ["Light appearance theme"] : []),
...(settings.activeDarkThemeId !== "t3code-dark" ? ["Dark appearance theme"] : []),
...(settings.customThemes.length > 0 ? ["Custom themes"] : []),
...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat
? ["Time format"]
: []),
@@ -481,13 +466,16 @@ export function useSettingsRestore(onRestored?: () => void) {
[
areProviderSettingsDirty,
isGitWritingModelDirty,
settings.activeLightThemeId,
settings.activeDarkThemeId,
settings.colorMode,
settings.confirmThreadArchive,
settings.confirmThreadDelete,
settings.customThemes.length,
settings.defaultThreadEnvMode,
settings.diffWordWrap,
settings.enableAssistantStreaming,
settings.timestampFormat,
theme,
],
);
@@ -501,10 +489,15 @@ export function useSettingsRestore(onRestored?: () => void) {
);
if (!confirmed) return;
setTheme("system");
updateSettings({
colorMode: "system",
activeLightThemeId: "t3code-light",
activeDarkThemeId: "t3code-dark",
customThemes: [],
});
resetSettings();
onRestored?.();
}, [changedSettingLabels, onRestored, resetSettings, setTheme]);
}, [changedSettingLabels, onRestored, resetSettings, updateSettings]);
return {
changedSettingLabels,
@@ -513,7 +506,6 @@ export function useSettingsRestore(onRestored?: () => void) {
}
export function GeneralSettingsPanel() {
const { theme, setTheme } = useTheme();
const settings = useSettings();
const { updateSettings } = useUpdateSettings();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
@@ -739,39 +731,6 @@ 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, Settings2Icon } from "lucide-react";
import { ArchiveIcon, ArrowLeftIcon, PaletteIcon, Settings2Icon } from "lucide-react";
import { useNavigate } from "@tanstack/react-router";
import {
@@ -12,7 +12,10 @@ import {
SidebarSeparator,
} from "../ui/sidebar";
export type SettingsSectionPath = "/settings/general" | "/settings/archived";
export type SettingsSectionPath =
| "/settings/general"
| "/settings/appearance"
| "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
label: string;
@@ -20,6 +23,7 @@ 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 },
];
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { BUILTIN_THEME_DOCUMENTS } from "@t3tools/shared/appearance/registry";
import {
createDuplicateTheme,
ensureUniqueThemeId,
normalizeImportedThemeDocument,
updateThemeDocument,
} from "./appearance.logic";
describe("appearance.logic", () => {
it("deduplicates conflicting theme ids", () => {
expect(ensureUniqueThemeId("codex", new Set(["codex", "codex-2"]))).toBe("codex-3");
});
it("normalizes imported themes into custom documents with unique ids", () => {
const imported = normalizeImportedThemeDocument(
BUILTIN_THEME_DOCUMENTS[0]!,
new Set(["t3code-light"]),
);
expect(imported.origin).toBe("custom");
expect(imported.id).toBe("t3code-light-2");
});
it("duplicates builtin themes before editing", () => {
const duplicate = createDuplicateTheme(BUILTIN_THEME_DOCUMENTS[0]!, []);
expect(duplicate.origin).toBe("custom");
expect(duplicate.id).toBe("t3code-light-copy");
expect(duplicate.radius).toBe(BUILTIN_THEME_DOCUMENTS[0]!.radius);
expect(duplicate.fontSize).toBe(BUILTIN_THEME_DOCUMENTS[0]!.fontSize);
});
it("updates flat theme documents", () => {
const updated = updateThemeDocument(BUILTIN_THEME_DOCUMENTS[0]!, (themeDocument) => ({
...themeDocument,
contrast: 99,
}));
expect(updated.contrast).toBe(99);
expect(updated.mode).toBe(BUILTIN_THEME_DOCUMENTS[0]!.mode);
});
});
@@ -0,0 +1,80 @@
import type { ThemeDocument } from "@t3tools/contracts";
import {
canonicalizeThemeDocument,
duplicateThemeDocument,
getReservedThemeIds,
} from "@t3tools/shared/appearance/registry";
function toKebabCase(value: string): string {
return value
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
}
export function slugifyThemeId(value: string): string {
return toKebabCase(value) || "custom-theme";
}
export function ensureUniqueThemeId(baseId: string, existingIds: ReadonlySet<string>): string {
if (!existingIds.has(baseId)) {
return baseId;
}
let index = 2;
while (existingIds.has(`${baseId}-${index}`)) {
index += 1;
}
return `${baseId}-${index}`;
}
export function normalizeImportedThemeDocument(
themeDocument: ThemeDocument,
existingThemeIds: ReadonlySet<string>,
): ThemeDocument {
const baseId = slugifyThemeId(themeDocument.id || themeDocument.name);
const uniqueId = ensureUniqueThemeId(baseId, existingThemeIds);
return canonicalizeThemeDocument(
{
...themeDocument,
id: uniqueId,
origin: "custom",
},
"custom",
);
}
export function createDuplicateTheme(
themeDocument: ThemeDocument,
customThemes: ReadonlyArray<ThemeDocument>,
) {
const existingThemeIds = new Set<string>([
...getReservedThemeIds(),
...customThemes.map((theme) => theme.id),
]);
const baseId = slugifyThemeId(`${themeDocument.id}-copy`);
const nextId = ensureUniqueThemeId(baseId, existingThemeIds);
const nextName =
nextId === `${themeDocument.id}-copy`
? `${themeDocument.name} Copy`
: `${themeDocument.name} Copy ${nextId.split("-").at(-1)}`;
return duplicateThemeDocument(themeDocument, nextId, nextName);
}
export function replaceCustomTheme(
customThemes: ReadonlyArray<ThemeDocument>,
nextTheme: ThemeDocument,
): Array<ThemeDocument> {
const next = customThemes.filter((theme) => theme.id !== nextTheme.id);
next.push(canonicalizeThemeDocument(nextTheme, "custom"));
return next;
}
export function updateThemeDocument(
themeDocument: ThemeDocument,
updater: (themeDocument: ThemeDocument) => ThemeDocument,
): ThemeDocument {
return updater(themeDocument);
}
+1 -1
View File
@@ -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 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",
"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",
className,
)}
data-slot="autocomplete-item"
+1 -1
View File
@@ -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 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",
"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",
className,
)}
data-slot="combobox-item"
-53
View File
@@ -9,8 +9,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
COMPOSER_DRAFT_STORAGE_KEY,
clearPromotedDraftThread,
clearPromotedDraftThreads,
type ComposerImageAttachment,
useComposerDraftStore,
} from "./composerDraftStore";
@@ -551,57 +549,6 @@ describe("composerDraftStore project draft thread mapping", () => {
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("clears a promoted draft by thread id", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "promote me");
clearPromotedDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThreadByProjectId(projectId)).toBeNull();
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
});
it("does not clear composer drafts for existing server threads during promotion cleanup", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadId, "keep me");
clearPromotedDraftThread(threadId);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("clears promoted drafts from an iterable of server thread ids", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId);
store.setPrompt(threadId, "promote me");
store.setProjectDraftThreadId(otherProjectId, otherThreadId);
store.setPrompt(otherThreadId, "keep me");
clearPromotedDraftThreads([threadId]);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]).toBeUndefined();
expect(
useComposerDraftStore.getState().getDraftThreadByProjectId(otherProjectId)?.threadId,
).toBe(otherThreadId);
expect(useComposerDraftStore.getState().draftsByThreadId[otherThreadId]?.prompt).toBe(
"keep me",
);
});
it("keeps existing server-thread composer drafts during iterable promotion cleanup", () => {
const store = useComposerDraftStore.getState();
store.setPrompt(threadId, "keep me");
clearPromotedDraftThreads([threadId]);
expect(useComposerDraftStore.getState().getDraftThread(threadId)).toBeNull();
expect(useComposerDraftStore.getState().draftsByThreadId[threadId]?.prompt).toBe("keep me");
});
it("updates branch context on an existing draft thread", () => {
const store = useComposerDraftStore.getState();
store.setProjectDraftThreadId(projectId, threadId, {
+11 -14
View File
@@ -2195,21 +2195,18 @@ export function useEffectiveComposerModelState(input: {
}
/**
* Clear a draft thread once the server has materialized the same thread id.
* Clear draft threads that have been promoted to server threads.
*
* Use the single-thread helper for live `thread.created` events and the
* iterable helper for bootstrap/recovery paths that discover multiple server
* threads at once.
* Call this after a snapshot sync so the route guard in `_chat.$threadId`
* sees the server thread before the draft is removed — avoids a redirect
* to `/` caused by a gap where neither draft nor server thread exists.
*/
export function clearPromotedDraftThread(threadId: ThreadId): void {
if (!useComposerDraftStore.getState().getDraftThread(threadId)) {
return;
}
useComposerDraftStore.getState().clearDraftThread(threadId);
}
export function clearPromotedDraftThreads(serverThreadIds: Iterable<ThreadId>): void {
for (const threadId of serverThreadIds) {
clearPromotedDraftThread(threadId);
export function clearPromotedDraftThreads(serverThreadIds: ReadonlySet<ThreadId>): void {
const store = useComposerDraftStore.getState();
const draftThreadIds = Object.keys(store.draftThreadsByThreadId) as ThreadId[];
for (const draftId of draftThreadIds) {
if (serverThreadIds.has(draftId)) {
store.clearDraftThread(draftId);
}
}
}
+77
View File
@@ -0,0 +1,77 @@
import { describe, expect, it } from "vitest";
import { parseAppearanceCache, resolveAppearanceMode } from "./useAppearance";
describe("resolveAppearanceMode", () => {
it("resolves explicit modes without consulting system preference", () => {
expect(resolveAppearanceMode("light", true)).toBe("light");
expect(resolveAppearanceMode("dark", false)).toBe("dark");
});
it("resolves system mode from the current platform preference", () => {
expect(resolveAppearanceMode("system", true)).toBe("dark");
expect(resolveAppearanceMode("system", false)).toBe("light");
});
});
describe("parseAppearanceCache", () => {
it("decodes valid cached appearance snapshots", () => {
const parsed = parseAppearanceCache(
JSON.stringify({
colorMode: "system",
activeLightThemeId: "custom-codex-light",
activeDarkThemeId: "custom-codex-dark",
customThemes: [
{
id: "custom-codex-light",
name: "Custom Codex Light",
version: 1,
origin: "custom",
mode: "light",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#ffffff",
foreground: "#0d0d0d",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 46,
},
{
id: "custom-codex-dark",
name: "Custom Codex Dark",
version: 1,
origin: "custom",
mode: "dark",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#111111",
foreground: "#fcfcfc",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 41,
},
],
}),
);
expect(parsed?.activeLightThemeId).toBe("custom-codex-light");
expect(parsed?.activeDarkThemeId).toBe("custom-codex-dark");
expect(parsed?.customThemes[0]?.id).toBe("custom-codex-light");
expect(parsed?.customThemes[0]?.radius).toBe("0.75rem");
expect(parsed?.customThemes[0]?.fontSize).toBe("15px");
});
it("drops invalid cache payloads", () => {
expect(
parseAppearanceCache(
JSON.stringify({
colorMode: "system",
activeLightThemeId: "custom-codex-light",
activeDarkThemeId: "custom-codex-dark",
customThemes: [{ id: "bad" }],
}),
),
).toBeNull();
});
});
+240
View File
@@ -0,0 +1,240 @@
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";
import { Schema } from "effect";
import type { DesktopAppearance } from "@t3tools/contracts";
import {
ColorMode,
ThemeDocumentSchema,
type ThemeMode,
type ColorMode as AppearanceColorMode,
} from "@t3tools/contracts";
import {
applyThemeDocumentStyles,
applyThemeVariant,
clearThemeCssVariables,
} from "@t3tools/shared/appearance/apply";
import {
type ResolvedThemeMode,
type ThemeCssVariableMap,
} from "@t3tools/shared/appearance/derive";
import {
DEFAULT_DARK_THEME_ID,
DEFAULT_LIGHT_THEME_ID,
resolveThemeDocument,
serializeAppearanceSnapshot,
} from "@t3tools/shared/appearance/registry";
import { useSettings, useUpdateSettings } from "./useSettings";
const APPEARANCE_CACHE_KEY = "t3code:appearance-cache";
const MEDIA_QUERY = "(prefers-color-scheme: dark)";
const AppearanceCacheSchema = Schema.Struct({
colorMode: ColorMode,
activeLightThemeId: Schema.String,
activeDarkThemeId: Schema.String,
customThemes: Schema.Array(ThemeDocumentSchema),
});
type AppearanceCache = typeof AppearanceCacheSchema.Type;
let appliedVariableNames: ReadonlyArray<keyof ThemeCssVariableMap> = [];
let lastDesktopAppearance: string | null = null;
function getSystemDark(): boolean {
return typeof window.matchMedia === "function" ? window.matchMedia(MEDIA_QUERY).matches : false;
}
export function resolveAppearanceMode(
colorMode: AppearanceColorMode,
systemDark: boolean,
): ResolvedThemeMode {
if (colorMode === "system") {
return systemDark ? "dark" : "light";
}
return colorMode;
}
export function parseAppearanceCache(raw: string | null): AppearanceCache | null {
if (!raw) return null;
try {
const parsed = JSON.parse(raw);
return Schema.decodeUnknownSync(AppearanceCacheSchema)(parsed);
} catch {
return null;
}
}
function resolveActiveThemeId(appearance: AppearanceCache, resolvedTheme: ThemeMode): string {
return resolvedTheme === "dark" ? appearance.activeDarkThemeId : appearance.activeLightThemeId;
}
function applyResolvedAppearance(
appearance: AppearanceCache,
resolvedTheme: ResolvedThemeMode,
): void {
const themeDocument = resolveThemeDocument(
resolveActiveThemeId(appearance, resolvedTheme),
appearance.customThemes,
resolvedTheme,
);
const root = document.documentElement;
root.classList.toggle("dark", resolvedTheme === "dark");
root.style.colorScheme = resolvedTheme;
applyThemeDocumentStyles(root.style, themeDocument);
clearThemeCssVariables(root.style, appliedVariableNames);
appliedVariableNames = applyThemeVariant(root.style, themeDocument);
}
function suppressTransitions(fn: () => void) {
document.documentElement.classList.add("no-transitions");
fn();
void document.documentElement.offsetHeight;
requestAnimationFrame(() => {
document.documentElement.classList.remove("no-transitions");
});
}
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;
});
}
}
if (typeof window !== "undefined" && typeof document !== "undefined") {
const cachedAppearance = parseAppearanceCache(localStorage.getItem(APPEARANCE_CACHE_KEY));
const initialAppearance =
cachedAppearance ??
({
colorMode: "system",
activeLightThemeId: DEFAULT_LIGHT_THEME_ID,
activeDarkThemeId: DEFAULT_DARK_THEME_ID,
customThemes: [],
} satisfies AppearanceCache);
const resolvedTheme = resolveAppearanceMode(initialAppearance.colorMode, getSystemDark());
try {
applyResolvedAppearance(initialAppearance, resolvedTheme);
} catch {
// The cache is best-effort. React will reconcile once settings load.
}
}
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);
};
}
export function useAppearance() {
const { colorMode, activeLightThemeId, activeDarkThemeId, customThemes } = useSettings((s) => ({
colorMode: s.colorMode,
activeLightThemeId: s.activeLightThemeId,
activeDarkThemeId: s.activeDarkThemeId,
customThemes: s.customThemes,
}));
const { updateSettings } = useUpdateSettings();
const activeLightTheme = useMemo(
() => resolveThemeDocument(activeLightThemeId, customThemes, "light"),
[activeLightThemeId, customThemes],
);
const activeDarkTheme = useMemo(
() => resolveThemeDocument(activeDarkThemeId, customThemes, "dark"),
[activeDarkThemeId, customThemes],
);
const systemDark = useSyncExternalStore(subscribeSystemDark, getSystemDarkSnapshot);
const resolvedTheme = useMemo(
() => resolveAppearanceMode(colorMode, systemDark),
[colorMode, systemDark],
);
const activeResolvedTheme = resolvedTheme === "dark" ? activeDarkTheme : activeLightTheme;
useEffect(() => {
suppressTransitions(() => {
applyResolvedAppearance(
{ colorMode, activeLightThemeId, activeDarkThemeId, customThemes },
resolvedTheme,
);
});
localStorage.setItem(
APPEARANCE_CACHE_KEY,
serializeAppearanceSnapshot({
colorMode,
activeLightThemeId,
activeDarkThemeId,
customThemes,
}),
);
syncDesktopAppearance({ mode: colorMode, themeId: activeResolvedTheme.id });
}, [
resolvedTheme,
activeResolvedTheme,
activeLightThemeId,
activeDarkThemeId,
colorMode,
customThemes,
]);
const setColorMode = useCallback(
(mode: AppearanceColorMode) => updateSettings({ colorMode: mode }),
[updateSettings],
);
const setThemeId = useCallback(
(mode: ThemeMode, id: string) =>
updateSettings(mode === "dark" ? { activeDarkThemeId: id } : { activeLightThemeId: id }),
[updateSettings],
);
const setCustomThemes = useCallback(
(themes: AppearanceCache["customThemes"]) => updateSettings({ customThemes: themes }),
[updateSettings],
);
return {
colorMode,
resolvedTheme,
activeLightTheme,
activeDarkTheme,
activeResolvedTheme,
activeLightThemeId,
activeDarkThemeId,
customThemes,
setColorMode,
setThemeId,
setCustomThemes,
} as const;
}
+8 -16
View File
@@ -1,37 +1,29 @@
import { DEFAULT_RUNTIME_MODE, type ProjectId, ThreadId } from "@t3tools/contracts";
import { useNavigate, useParams } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import { useShallow } from "zustand/react/shallow";
import { useCallback } from "react";
import {
type DraftThreadEnvMode,
type DraftThreadState,
useComposerDraftStore,
} from "../composerDraftStore";
import { newThreadId } from "../lib/utils";
import { orderItemsByPreferredIds } from "../components/Sidebar.logic";
import { useStore } from "../store";
import { useThreadById } from "../storeSelectors";
import { useUiStateStore } from "../uiStateStore";
export function useHandleNewThread() {
const projectIds = useStore(useShallow((store) => store.projects.map((project) => project.id)));
const projectOrder = useUiStateStore((store) => store.projectOrder);
const projects = useStore((store) => store.projects);
const threads = useStore((store) => store.threads);
const navigate = useNavigate();
const routeThreadId = useParams({
strict: false,
select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
});
const activeThread = useThreadById(routeThreadId);
const activeDraftThread = useComposerDraftStore((store) =>
routeThreadId ? (store.draftThreadsByThreadId[routeThreadId] ?? null) : null,
);
const orderedProjects = useMemo(() => {
return orderItemsByPreferredIds({
items: projectIds,
preferredIds: projectOrder,
getId: (projectId) => projectId,
});
}, [projectIds, projectOrder]);
const activeThread = routeThreadId
? threads.find((thread) => thread.id === routeThreadId)
: undefined;
const handleNewThread = useCallback(
(
@@ -119,8 +111,8 @@ export function useHandleNewThread() {
return {
activeDraftThread,
activeThread,
defaultProjectId: orderedProjects[0] ?? null,
handleNewThread,
projects,
routeThreadId,
};
}
+13 -3
View File
@@ -70,9 +70,7 @@ function splitPatch(patch: Partial<UnifiedSettings>): {
* only re-render when the slice they care about changes.
*/
export function useSettings<T extends UnifiedSettings = UnifiedSettings>(
selector?: (s: UnifiedSettings) => T,
): T {
export function useSettings<T = UnifiedSettings>(selector?: (s: UnifiedSettings) => T): T {
const { data: serverConfig } = useQuery(serverConfigQueryOptions());
const [clientSettings] = useLocalStorage(
CLIENT_SETTINGS_STORAGE_KEY,
@@ -240,6 +238,18 @@ export function migrateLocalSettingsToServer(): void {
const raw = localStorage.getItem(OLD_SETTINGS_KEY);
if (!raw) return;
// Migrate old t3code:theme localStorage key to server colorMode
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
}
try {
const old = JSON.parse(raw);
if (!Predicate.isObject(old)) return;
-121
View File
@@ -1,121 +0,0 @@
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;
}
+8 -5
View File
@@ -16,6 +16,8 @@ import { toastManager } from "../components/ui/toast";
import { useSettings } from "./useSettings";
export function useThreadActions() {
const threads = useStore((store) => store.threads);
const projects = useStore((store) => store.projects);
const appSettings = useSettings();
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearProjectDraftThreadById = useComposerDraftStore(
@@ -35,7 +37,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
throw new Error("Cannot archive a running thread.");
@@ -51,7 +53,7 @@ export function useThreadActions() {
await handleNewThread(thread.projectId);
}
},
[handleNewThread, routeThreadId],
[handleNewThread, routeThreadId, threads],
);
const unarchiveThread = useCallback(async (threadId: ThreadId) => {
@@ -68,7 +70,6 @@ export function useThreadActions() {
async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
const api = readNativeApi();
if (!api) return;
const { projects, threads } = useStore.getState();
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
const threadProject = projects.find((project) => project.id === thread.projectId);
@@ -170,8 +171,10 @@ export function useThreadActions() {
clearTerminalState,
appSettings.sidebarThreadSortOrder,
navigate,
projects,
removeWorktreeMutation,
routeThreadId,
threads,
],
);
@@ -179,7 +182,7 @@ export function useThreadActions() {
async (threadId: ThreadId) => {
const api = readNativeApi();
if (!api) return;
const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
const thread = threads.find((entry) => entry.id === threadId);
if (!thread) return;
if (appSettings.confirmThreadDelete) {
@@ -196,7 +199,7 @@ export function useThreadActions() {
await deleteThread(threadId);
},
[appSettings.confirmThreadDelete, deleteThread],
[appSettings.confirmThreadDelete, deleteThread, threads],
);
return {
+20 -58
View File
@@ -4,6 +4,13 @@
@theme inline {
--animate-skeleton: skeleton 2s -1s infinite linear;
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar: var(--sidebar);
--color-diff-deletion: var(--diff-deletion);
--color-diff-addition: var(--diff-addition);
--color-warning-foreground: var(--warning-foreground);
--color-warning: var(--warning);
--color-success-foreground: var(--success-foreground);
@@ -62,72 +69,19 @@
}
:root {
color-scheme: light;
--radius: 0.625rem;
--background: var(--color-white);
--foreground: var(--color-neutral-800);
--card: var(--color-white);
--card-foreground: var(--color-neutral-800);
--popover: var(--color-white);
--popover-foreground: var(--color-neutral-800);
--primary: oklch(0.488 0.217 264);
--primary-foreground: var(--color-white);
--secondary: --alpha(var(--color-black) / 4%);
--secondary-foreground: var(--color-neutral-800);
--muted: --alpha(var(--color-black) / 4%);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-black));
--accent: --alpha(var(--color-black) / 4%);
--accent-foreground: var(--color-neutral-800);
--destructive: var(--color-red-500);
--border: --alpha(var(--color-black) / 8%);
--input: --alpha(var(--color-black) / 10%);
--ring: oklch(0.488 0.217 264);
--destructive-foreground: var(--color-red-700);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-700);
--success: var(--color-emerald-500);
--success-foreground: var(--color-emerald-700);
--warning: var(--color-amber-500);
--warning-foreground: var(--color-amber-700);
@variant dark {
color-scheme: dark;
--background: color-mix(in srgb, var(--color-neutral-950) 95%, var(--color-white));
--foreground: var(--color-neutral-100);
--card: color-mix(in srgb, var(--background) 98%, var(--color-white));
--card-foreground: var(--color-neutral-100);
--popover: color-mix(in srgb, var(--background) 98%, var(--color-white));
--popover-foreground: var(--color-neutral-100);
--primary: oklch(0.588 0.217 264);
--primary-foreground: var(--color-white);
--secondary: --alpha(var(--color-white) / 4%);
--secondary-foreground: var(--color-neutral-100);
--muted: --alpha(var(--color-white) / 4%);
--muted-foreground: color-mix(in srgb, var(--color-neutral-500) 90%, var(--color-white));
--accent: --alpha(var(--color-white) / 4%);
--accent-foreground: var(--color-neutral-100);
--destructive: color-mix(in srgb, var(--color-red-500) 90%, var(--color-white));
--border: --alpha(var(--color-white) / 6%);
--input: --alpha(var(--color-white) / 8%);
--ring: oklch(0.588 0.217 264);
--destructive-foreground: var(--color-red-400);
--info: var(--color-blue-500);
--info-foreground: var(--color-blue-400);
--success: var(--color-emerald-500);
--success-foreground: var(--color-emerald-400);
--warning: var(--color-amber-500);
--warning-foreground: var(--color-amber-400);
}
}
body {
font-family:
font-family: var(
--ui-font-family,
"DM Sans",
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
system-ui,
sans-serif;
sans-serif
);
margin: 0;
padding: 0;
min-height: 100vh;
@@ -160,7 +114,15 @@ pre,
code,
textarea,
input {
font-family: "SF Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
font-family: var(
--code-font-family,
"SF Mono",
"SFMono-Regular",
Consolas,
"Liberation Mono",
Menlo,
monospace
);
}
/* Window drag region (frameless titlebar) */
@@ -1,108 +0,0 @@
import {
CheckpointRef,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import { deriveOrchestrationBatchEffects } from "./orchestrationEventEffects";
function makeEvent<T extends OrchestrationEvent["type"]>(
type: T,
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
): Extract<OrchestrationEvent, { type: T }> {
const sequence = overrides.sequence ?? 1;
return {
sequence,
eventId: EventId.makeUnsafe(`event-${sequence}`),
aggregateKind: "thread",
aggregateId:
"threadId" in payload
? payload.threadId
: "projectId" in payload
? payload.projectId
: ProjectId.makeUnsafe("project-1"),
occurredAt: "2026-02-27T00:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type,
payload,
...overrides,
} as Extract<OrchestrationEvent, { type: T }>;
}
describe("deriveOrchestrationBatchEffects", () => {
it("targets draft promotion and terminal cleanup from thread lifecycle events", () => {
const createdThreadId = ThreadId.makeUnsafe("thread-created");
const deletedThreadId = ThreadId.makeUnsafe("thread-deleted");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.created", {
threadId: createdThreadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Created thread",
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
}),
makeEvent("thread.deleted", {
threadId: deletedThreadId,
deletedAt: "2026-02-27T00:00:01.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([createdThreadId]);
expect(effects.clearDeletedThreadIds).toEqual([deletedThreadId]);
expect(effects.removeTerminalStateThreadIds).toEqual([deletedThreadId]);
expect(effects.needsProviderInvalidation).toBe(false);
});
it("keeps only the final lifecycle outcome for a thread within one batch", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const effects = deriveOrchestrationBatchEffects([
makeEvent("thread.deleted", {
threadId,
deletedAt: "2026-02-27T00:00:01.000Z",
}),
makeEvent("thread.created", {
threadId,
projectId: ProjectId.makeUnsafe("project-1"),
title: "Recreated thread",
modelSelection: { provider: "codex", model: "gpt-5-codex" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
}),
makeEvent("thread.turn-diff-completed", {
threadId,
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
completedAt: "2026-02-27T00:00:03.000Z",
}),
]);
expect(effects.clearPromotedDraftThreadIds).toEqual([threadId]);
expect(effects.clearDeletedThreadIds).toEqual([]);
expect(effects.removeTerminalStateThreadIds).toEqual([]);
expect(effects.needsProviderInvalidation).toBe(true);
});
});
-76
View File
@@ -1,76 +0,0 @@
import type { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
export interface OrchestrationBatchEffects {
clearPromotedDraftThreadIds: ThreadId[];
clearDeletedThreadIds: ThreadId[];
removeTerminalStateThreadIds: ThreadId[];
needsProviderInvalidation: boolean;
}
export function deriveOrchestrationBatchEffects(
events: readonly OrchestrationEvent[],
): OrchestrationBatchEffects {
const threadLifecycleEffects = new Map<
ThreadId,
{
clearPromotedDraft: boolean;
clearDeletedThread: boolean;
removeTerminalState: boolean;
}
>();
let needsProviderInvalidation = false;
for (const event of events) {
switch (event.type) {
case "thread.turn-diff-completed":
case "thread.reverted": {
needsProviderInvalidation = true;
break;
}
case "thread.created": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: true,
clearDeletedThread: false,
removeTerminalState: false,
});
break;
}
case "thread.deleted": {
threadLifecycleEffects.set(event.payload.threadId, {
clearPromotedDraft: false,
clearDeletedThread: true,
removeTerminalState: true,
});
break;
}
default: {
break;
}
}
}
const clearPromotedDraftThreadIds: ThreadId[] = [];
const clearDeletedThreadIds: ThreadId[] = [];
const removeTerminalStateThreadIds: ThreadId[] = [];
for (const [threadId, effect] of threadLifecycleEffects) {
if (effect.clearPromotedDraft) {
clearPromotedDraftThreadIds.push(threadId);
}
if (effect.clearDeletedThread) {
clearDeletedThreadIds.push(threadId);
}
if (effect.removeTerminalState) {
removeTerminalStateThreadIds.push(threadId);
}
}
return {
clearPromotedDraftThreadIds,
clearDeletedThreadIds,
removeTerminalStateThreadIds,
needsProviderInvalidation,
};
}
-100
View File
@@ -1,100 +0,0 @@
import { describe, expect, it } from "vitest";
import { createOrchestrationRecoveryCoordinator } from "./orchestrationRecovery";
describe("createOrchestrationRecoveryCoordinator", () => {
it("defers live events until bootstrap completes and then requests replay", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
expect(coordinator.beginSnapshotRecovery("bootstrap")).toBe(true);
expect(coordinator.classifyDomainEvent(4)).toBe("defer");
expect(coordinator.completeSnapshotRecovery(2)).toBe(true);
expect(coordinator.getState()).toMatchObject({
latestSequence: 2,
highestObservedSequence: 4,
bootstrapped: true,
pendingReplay: false,
inFlight: null,
});
});
it("classifies sequence gaps as recovery-only replay work", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
expect(coordinator.classifyDomainEvent(5)).toBe("recover");
expect(coordinator.beginReplayRecovery("sequence-gap")).toBe(true);
expect(coordinator.getState().inFlight).toEqual({
kind: "replay",
reason: "sequence-gap",
});
});
it("tracks live event batches without entering recovery", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
expect(coordinator.classifyDomainEvent(4)).toBe("apply");
expect(coordinator.markEventBatchApplied([{ sequence: 4 }])).toEqual([{ sequence: 4 }]);
expect(coordinator.getState()).toMatchObject({
latestSequence: 4,
highestObservedSequence: 4,
bootstrapped: true,
inFlight: null,
});
});
it("requests another replay when deferred events arrive during replay recovery", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.classifyDomainEvent(5);
coordinator.beginReplayRecovery("sequence-gap");
coordinator.classifyDomainEvent(7);
coordinator.markEventBatchApplied([{ sequence: 4 }, { sequence: 5 }, { sequence: 6 }]);
expect(coordinator.completeReplayRecovery()).toBe(true);
});
it("does not immediately replay again when replay returns no new events", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.classifyDomainEvent(5);
coordinator.beginReplayRecovery("sequence-gap");
expect(coordinator.completeReplayRecovery()).toBe(false);
expect(coordinator.getState()).toMatchObject({
latestSequence: 3,
highestObservedSequence: 5,
pendingReplay: false,
inFlight: null,
});
});
it("marks replay failure as unbootstrapped so snapshot fallback is recovery-only", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
coordinator.beginSnapshotRecovery("bootstrap");
coordinator.completeSnapshotRecovery(3);
coordinator.beginReplayRecovery("sequence-gap");
coordinator.failReplayRecovery();
expect(coordinator.getState()).toMatchObject({
bootstrapped: false,
inFlight: null,
});
expect(coordinator.beginSnapshotRecovery("replay-failed")).toBe(true);
expect(coordinator.getState().inFlight).toEqual({
kind: "snapshot",
reason: "replay-failed",
});
});
});
-136
View File
@@ -1,136 +0,0 @@
export type OrchestrationRecoveryReason = "bootstrap" | "sequence-gap" | "replay-failed";
export interface OrchestrationRecoveryPhase {
kind: "snapshot" | "replay";
reason: OrchestrationRecoveryReason;
}
export interface OrchestrationRecoveryState {
latestSequence: number;
highestObservedSequence: number;
bootstrapped: boolean;
pendingReplay: boolean;
inFlight: OrchestrationRecoveryPhase | null;
}
type SequencedEvent = Readonly<{ sequence: number }>;
export function createOrchestrationRecoveryCoordinator() {
let state: OrchestrationRecoveryState = {
latestSequence: 0,
highestObservedSequence: 0,
bootstrapped: false,
pendingReplay: false,
inFlight: null,
};
let replayStartSequence: number | null = null;
const snapshotState = (): OrchestrationRecoveryState => ({
...state,
...(state.inFlight ? { inFlight: { ...state.inFlight } } : {}),
});
const observeSequence = (sequence: number) => {
state.highestObservedSequence = Math.max(state.highestObservedSequence, sequence);
};
const shouldReplayAfterRecovery = (): boolean => {
const shouldReplay =
state.pendingReplay || state.highestObservedSequence > state.latestSequence;
state.pendingReplay = false;
return shouldReplay;
};
return {
getState(): OrchestrationRecoveryState {
return snapshotState();
},
classifyDomainEvent(sequence: number): "ignore" | "defer" | "recover" | "apply" {
observeSequence(sequence);
if (sequence <= state.latestSequence) {
return "ignore";
}
if (!state.bootstrapped || state.inFlight) {
state.pendingReplay = true;
return "defer";
}
if (sequence !== state.latestSequence + 1) {
state.pendingReplay = true;
return "recover";
}
return "apply";
},
markEventBatchApplied<T extends SequencedEvent>(events: ReadonlyArray<T>): ReadonlyArray<T> {
const nextEvents = events
.filter((event) => event.sequence > state.latestSequence)
.toSorted((left, right) => left.sequence - right.sequence);
if (nextEvents.length === 0) {
return [];
}
state.latestSequence = nextEvents.at(-1)?.sequence ?? state.latestSequence;
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
return nextEvents;
},
beginSnapshotRecovery(reason: OrchestrationRecoveryReason): boolean {
if (state.inFlight?.kind === "snapshot") {
state.pendingReplay = true;
return false;
}
if (state.inFlight?.kind === "replay") {
state.pendingReplay = true;
return false;
}
state.inFlight = { kind: "snapshot", reason };
return true;
},
completeSnapshotRecovery(snapshotSequence: number): boolean {
state.latestSequence = Math.max(state.latestSequence, snapshotSequence);
state.highestObservedSequence = Math.max(state.highestObservedSequence, state.latestSequence);
state.bootstrapped = true;
state.inFlight = null;
return shouldReplayAfterRecovery();
},
failSnapshotRecovery(): void {
state.inFlight = null;
},
beginReplayRecovery(reason: OrchestrationRecoveryReason): boolean {
if (!state.bootstrapped || state.inFlight?.kind === "snapshot") {
state.pendingReplay = true;
return false;
}
if (state.inFlight?.kind === "replay") {
state.pendingReplay = true;
return false;
}
state.pendingReplay = false;
replayStartSequence = state.latestSequence;
state.inFlight = { kind: "replay", reason };
return true;
},
completeReplayRecovery(): boolean {
const replayMadeProgress =
replayStartSequence !== null && state.latestSequence > replayStartSequence;
replayStartSequence = null;
state.inFlight = null;
if (!replayMadeProgress) {
state.pendingReplay = false;
return false;
}
return shouldReplayAfterRecovery();
},
failReplayRecovery(): void {
replayStartSequence = null;
state.bootstrapped = false;
state.inFlight = null;
},
};
}
+36 -1
View File
@@ -1,11 +1,13 @@
import {
DEFAULT_MODEL_BY_PROVIDER,
type ClaudeModelOptions,
type CodexModelOptions,
type ModelCapabilities,
type ProviderKind,
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { normalizeModelSlug, resolveContextWindow, resolveEffort } from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
@@ -67,3 +69,36 @@ 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;
}
+21
View File
@@ -14,6 +14,7 @@ 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({
@@ -40,6 +41,11 @@ 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',
@@ -50,12 +56,14 @@ 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
@@ -65,6 +73,7 @@ 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
@@ -75,12 +84,14 @@ export interface FileRouteTypes {
| '/'
| '/settings'
| '/$threadId'
| '/settings/appearance'
| '/settings/archived'
| '/settings/general'
fileRoutesByTo: FileRoutesByTo
to:
| '/settings'
| '/$threadId'
| '/settings/appearance'
| '/settings/archived'
| '/settings/general'
| '/'
@@ -89,6 +100,7 @@ export interface FileRouteTypes {
| '/_chat'
| '/settings'
| '/_chat/$threadId'
| '/settings/appearance'
| '/settings/archived'
| '/settings/general'
| '/_chat/'
@@ -136,6 +148,13 @@ 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'
@@ -159,11 +178,13 @@ 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,
}
+10 -2
View File
@@ -1,8 +1,11 @@
import { createElement } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createRouter, RouterHistory } from "@tanstack/react-router";
import { createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
import { StoreProvider } from "./store";
type RouterHistory = NonNullable<Parameters<typeof createRouter>[0]["history"]>;
export function getRouter(history: RouterHistory) {
const queryClient = new QueryClient();
@@ -13,7 +16,12 @@ export function getRouter(history: RouterHistory) {
context: {
queryClient,
},
Wrap: ({ children }) => createElement(QueryClientProvider, { client: queryClient }, children),
Wrap: ({ children }) =>
createElement(
QueryClientProvider,
{ client: queryClient },
createElement(StoreProvider, null, children),
),
});
}
+53 -146
View File
@@ -1,4 +1,4 @@
import { OrchestrationEvent, ThreadId } from "@t3tools/contracts";
import { ThreadId } from "@t3tools/contracts";
import {
Outlet,
createRootRouteWithContext,
@@ -17,22 +17,16 @@ import { AnchoredToastProvider, ToastProvider, toastManager } from "../component
import { resolveAndPersistPreferredEditor } from "../editorPreferences";
import { serverConfigQueryOptions, serverQueryKeys } from "../lib/serverReactQuery";
import { readNativeApi } from "../nativeApi";
import {
clearPromotedDraftThread,
clearPromotedDraftThreads,
useComposerDraftStore,
} from "../composerDraftStore";
import { clearPromotedDraftThreads, useComposerDraftStore } from "../composerDraftStore";
import { useStore } from "../store";
import { useUiStateStore } from "../uiStateStore";
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";
import { collectActiveTerminalThreadIds } from "../lib/terminalStateCleanup";
import { deriveOrchestrationBatchEffects } from "../orchestrationEventEffects";
import { createOrchestrationRecoveryCoordinator } from "../orchestrationRecovery";
export const Route = createRootRouteWithContext<{
queryClient: QueryClient;
@@ -45,6 +39,11 @@ export const Route = createRootRouteWithContext<{
});
function RootRouteView() {
// Mount appearance system — drives .dark class, theme tokens, and Electron sync.
// Must be called before any early returns to satisfy React's Rules of Hooks.
// The import also triggers module-scope FOUC prevention.
useAppearance();
if (!readNativeApi()) {
return (
<div className="flex h-screen flex-col bg-background text-foreground">
@@ -142,13 +141,8 @@ function errorDetails(error: unknown): string {
}
function EventRouter() {
const applyOrchestrationEvents = useStore((store) => store.applyOrchestrationEvents);
const syncServerReadModel = useStore((store) => store.syncServerReadModel);
const setProjectExpanded = useUiStateStore((store) => store.setProjectExpanded);
const syncProjects = useUiStateStore((store) => store.syncProjects);
const syncThreads = useUiStateStore((store) => store.syncThreads);
const clearThreadUi = useUiStateStore((store) => store.clearThreadUi);
const removeTerminalState = useTerminalStateStore((store) => store.removeTerminalState);
const setProjectExpanded = useStore((store) => store.setProjectExpanded);
const removeOrphanedTerminalStates = useTerminalStateStore(
(store) => store.removeOrphanedTerminalStates,
);
@@ -164,40 +158,56 @@ function EventRouter() {
const api = readNativeApi();
if (!api) return;
let disposed = false;
const recovery = createOrchestrationRecoveryCoordinator();
let latestSequence = 0;
let syncing = false;
let pending = false;
let needsProviderInvalidation = false;
const reconcileSnapshotDerivedState = () => {
const threads = useStore.getState().threads;
const projects = useStore.getState().projects;
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
syncThreads(
threads.map((thread) => ({
id: thread.id,
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
})),
);
clearPromotedDraftThreads(threads.map((thread) => thread.id));
const flushSnapshotSync = async (): Promise<void> => {
const snapshot = await api.orchestration.getSnapshot();
if (disposed) return;
latestSequence = Math.max(latestSequence, snapshot.snapshotSequence);
syncServerReadModel(snapshot);
clearPromotedDraftThreads(new Set(snapshot.threads.map((t) => t.id)));
const draftThreadIds = Object.keys(
useComposerDraftStore.getState().draftThreadsByThreadId,
) as ThreadId[];
const activeThreadIds = collectActiveTerminalThreadIds({
snapshotThreads: threads.map((thread) => ({ id: thread.id, deletedAt: null })),
snapshotThreads: snapshot.threads,
draftThreadIds,
});
removeOrphanedTerminalStates(activeThreadIds);
if (pending) {
pending = false;
await flushSnapshotSync();
}
};
const queryInvalidationThrottler = new Throttler(
const syncSnapshot = async () => {
if (syncing) {
pending = true;
return;
}
syncing = true;
pending = false;
try {
await flushSnapshotSync();
} catch {
// Keep prior state and wait for next domain event to trigger a resync.
}
syncing = false;
};
const domainEventFlushThrottler = new Throttler(
() => {
if (!needsProviderInvalidation) {
return;
if (needsProviderInvalidation) {
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
// Invalidate workspace entry queries so the @-mention file picker
// reflects files created, deleted, or restored during this turn.
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
}
needsProviderInvalidation = false;
void queryClient.invalidateQueries({ queryKey: providerQueryKeys.all });
// Invalidate workspace entry queries so the @-mention file picker
// reflects files created, deleted, or restored during this turn.
void queryClient.invalidateQueries({ queryKey: projectQueryKeys.all });
void syncSnapshot();
},
{
wait: 100,
@@ -206,113 +216,15 @@ function EventRouter() {
},
);
const applyEventBatch = (events: ReadonlyArray<OrchestrationEvent>) => {
const nextEvents = recovery.markEventBatchApplied(events);
if (nextEvents.length === 0) {
return;
}
const batchEffects = deriveOrchestrationBatchEffects(nextEvents);
const needsProjectUiSync = nextEvents.some(
(event) =>
event.type === "project.created" ||
event.type === "project.meta-updated" ||
event.type === "project.deleted",
);
if (batchEffects.needsProviderInvalidation) {
needsProviderInvalidation = true;
void queryInvalidationThrottler.maybeExecute();
}
applyOrchestrationEvents(nextEvents);
if (needsProjectUiSync) {
const projects = useStore.getState().projects;
syncProjects(projects.map((project) => ({ id: project.id, cwd: project.cwd })));
}
const needsThreadUiSync = nextEvents.some(
(event) => event.type === "thread.created" || event.type === "thread.deleted",
);
if (needsThreadUiSync) {
const threads = useStore.getState().threads;
syncThreads(
threads.map((thread) => ({
id: thread.id,
seedVisitedAt: thread.updatedAt ?? thread.createdAt,
})),
);
}
const draftStore = useComposerDraftStore.getState();
for (const threadId of batchEffects.clearPromotedDraftThreadIds) {
clearPromotedDraftThread(threadId);
}
for (const threadId of batchEffects.clearDeletedThreadIds) {
draftStore.clearDraftThread(threadId);
clearThreadUi(threadId);
}
for (const threadId of batchEffects.removeTerminalStateThreadIds) {
removeTerminalState(threadId);
}
};
const recoverFromSequenceGap = async (): Promise<void> => {
if (!recovery.beginReplayRecovery("sequence-gap")) {
return;
}
try {
const events = await api.orchestration.replayEvents(recovery.getState().latestSequence);
if (!disposed) {
applyEventBatch(events);
}
} catch {
recovery.failReplayRecovery();
void fallbackToSnapshotRecovery();
return;
}
if (!disposed && recovery.completeReplayRecovery()) {
void recoverFromSequenceGap();
}
};
const runSnapshotRecovery = async (reason: "bootstrap" | "replay-failed"): Promise<void> => {
if (!recovery.beginSnapshotRecovery(reason)) {
return;
}
try {
const snapshot = await api.orchestration.getSnapshot();
if (!disposed) {
syncServerReadModel(snapshot);
reconcileSnapshotDerivedState();
if (recovery.completeSnapshotRecovery(snapshot.snapshotSequence)) {
void recoverFromSequenceGap();
}
}
} catch {
// Keep prior state and wait for welcome or a later replay attempt.
recovery.failSnapshotRecovery();
}
};
const bootstrapFromSnapshot = async (): Promise<void> => {
await runSnapshotRecovery("bootstrap");
};
const fallbackToSnapshotRecovery = async (): Promise<void> => {
await runSnapshotRecovery("replay-failed");
};
const unsubDomainEvent = api.orchestration.onDomainEvent((event) => {
const action = recovery.classifyDomainEvent(event.sequence);
if (action === "apply") {
applyEventBatch([event]);
if (event.sequence <= latestSequence) {
return;
}
if (action === "recover") {
void recoverFromSequenceGap();
latestSequence = event.sequence;
if (event.type === "thread.turn-diff-completed" || event.type === "thread.reverted") {
needsProviderInvalidation = true;
}
domainEventFlushThrottler.maybeExecute();
});
const unsubTerminalEvent = api.terminal.onEvent((event) => {
const hasRunningSubprocess = terminalRunningSubprocessFromEvent(event);
@@ -331,7 +243,7 @@ function EventRouter() {
// Migrate old localStorage settings to server on first connect
migrateLocalSettingsToServer();
void (async () => {
await bootstrapFromSnapshot();
await syncSnapshot();
if (disposed) {
return;
}
@@ -413,7 +325,7 @@ function EventRouter() {
return () => {
disposed = true;
needsProviderInvalidation = false;
queryInvalidationThrottler.cancel();
domainEventFlushThrottler.cancel();
unsubDomainEvent();
unsubTerminalEvent();
unsubWelcome();
@@ -421,16 +333,11 @@ function EventRouter() {
unsubProvidersUpdated();
};
}, [
applyOrchestrationEvents,
navigate,
queryClient,
removeTerminalState,
removeOrphanedTerminalStates,
clearThreadUi,
setProjectExpanded,
syncProjects,
syncServerReadModel,
syncThreads,
]);
return null;
+4 -4
View File
@@ -161,7 +161,7 @@ const DiffPanelInlineSidebar = (props: {
};
function ChatThreadRouteView() {
const bootstrapComplete = useStore((store) => store.bootstrapComplete);
const threadsHydrated = useStore((store) => store.threadsHydrated);
const navigate = useNavigate();
const threadId = Route.useParams({
select: (params) => ThreadId.makeUnsafe(params.threadId),
@@ -202,7 +202,7 @@ function ChatThreadRouteView() {
}, [diffOpen]);
useEffect(() => {
if (!bootstrapComplete) {
if (!threadsHydrated) {
return;
}
@@ -210,9 +210,9 @@ function ChatThreadRouteView() {
void navigate({ to: "/", replace: true });
return;
}
}, [bootstrapComplete, navigate, routeThreadExists, threadId]);
}, [navigate, routeThreadExists, threadsHydrated, threadId]);
if (!bootstrapComplete || !routeThreadExists) {
if (!threadsHydrated || !routeThreadExists) {
return null;
}
+11 -14
View File
@@ -17,7 +17,7 @@ const EMPTY_KEYBINDINGS: ResolvedKeybindingsConfig = [];
function ChatRouteGlobalShortcuts() {
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
const selectedThreadIdsSize = useThreadSelectionStore((state) => state.selectedThreadIds.size);
const { activeDraftThread, activeThread, defaultProjectId, handleNewThread, routeThreadId } =
const { activeDraftThread, activeThread, handleNewThread, projects, routeThreadId } =
useHandleNewThread();
const serverConfigQuery = useQuery(serverConfigQueryOptions());
const keybindings = serverConfigQuery.data?.keybindings ?? EMPTY_KEYBINDINGS;
@@ -38,7 +38,7 @@ function ChatRouteGlobalShortcuts() {
return;
}
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? defaultProjectId;
const projectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? projects[0]?.id;
if (!projectId) return;
const command = resolveShortcutCommand(event, keybindings, {
@@ -59,17 +59,14 @@ function ChatRouteGlobalShortcuts() {
return;
}
if (command === "chat.new") {
event.preventDefault();
event.stopPropagation();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode:
activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
});
return;
}
if (command !== "chat.new") return;
event.preventDefault();
event.stopPropagation();
void handleNewThread(projectId, {
branch: activeThread?.branch ?? activeDraftThread?.branch ?? null,
worktreePath: activeThread?.worktreePath ?? activeDraftThread?.worktreePath ?? null,
envMode: activeDraftThread?.envMode ?? (activeThread?.worktreePath ? "worktree" : "local"),
});
};
window.addEventListener("keydown", onWindowKeyDown);
@@ -82,7 +79,7 @@ function ChatRouteGlobalShortcuts() {
clearSelection,
handleNewThread,
keybindings,
defaultProjectId,
projects,
selectedThreadIdsSize,
terminalOpen,
appSettings.defaultThreadEnvMode,
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { AppearanceSettingsPanel } from "../components/settings/AppearanceSettingsPanel";
export const Route = createFileRoute("/settings/appearance")({
component: AppearanceSettingsPanel,
});
-32
View File
@@ -8,7 +8,6 @@ import {
import { describe, expect, it } from "vitest";
import {
deriveCompletionDividerBeforeEntryId,
deriveActiveWorkStartedAt,
deriveActivePlanState,
PROVIDER_OPTIONS,
@@ -965,37 +964,6 @@ describe("deriveTimelineEntries", () => {
},
});
});
it("anchors the completion divider to latestTurn.assistantMessageId before timestamp fallback", () => {
const entries = deriveTimelineEntries(
[
{
id: MessageId.makeUnsafe("assistant-earlier"),
role: "assistant",
text: "progress update",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant-final"),
role: "assistant",
text: "final answer",
createdAt: "2026-02-23T00:00:01.000Z",
streaming: false,
},
],
[],
[],
);
expect(
deriveCompletionDividerBeforeEntryId(entries, {
assistantMessageId: MessageId.makeUnsafe("assistant-final"),
startedAt: "2026-02-23T00:00:00.000Z",
completedAt: "2026-02-23T00:00:02.000Z",
}),
).toBe("assistant-final");
});
});
describe("deriveWorkLogEntries context window handling", () => {
-47
View File
@@ -852,53 +852,6 @@ export function deriveTimelineEntries(
);
}
export function deriveCompletionDividerBeforeEntryId(
timelineEntries: ReadonlyArray<TimelineEntry>,
latestTurn: Pick<
OrchestrationLatestTurn,
"assistantMessageId" | "startedAt" | "completedAt"
> | null,
): string | null {
if (!latestTurn?.startedAt || !latestTurn.completedAt) {
return null;
}
if (latestTurn.assistantMessageId) {
const exactMatch = timelineEntries.find(
(timelineEntry) =>
timelineEntry.kind === "message" &&
timelineEntry.message.role === "assistant" &&
timelineEntry.message.id === latestTurn.assistantMessageId,
);
if (exactMatch) {
return exactMatch.id;
}
}
const turnStartedAt = Date.parse(latestTurn.startedAt);
const turnCompletedAt = Date.parse(latestTurn.completedAt);
if (Number.isNaN(turnStartedAt) || Number.isNaN(turnCompletedAt)) {
return null;
}
let inRangeMatch: string | null = null;
let fallbackMatch: string | null = null;
for (const timelineEntry of timelineEntries) {
if (timelineEntry.kind !== "message" || timelineEntry.message.role !== "assistant") {
continue;
}
const messageAt = Date.parse(timelineEntry.message.createdAt);
if (Number.isNaN(messageAt) || messageAt < turnStartedAt) {
continue;
}
fallbackMatch = timelineEntry.id;
if (messageAt <= turnCompletedAt) {
inRangeMatch = timelineEntry.id;
}
}
return inRangeMatch ?? fallbackMatch;
}
export function inferCheckpointTurnCountByTurnId(
summaries: TurnDiffSummary[],
): Record<TurnId, number> {
+95 -489
View File
@@ -1,22 +1,13 @@
import {
CheckpointRef,
DEFAULT_MODEL_BY_PROVIDER,
EventId,
MessageId,
ProjectId,
ThreadId,
TurnId,
type OrchestrationEvent,
type OrchestrationReadModel,
} from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
applyOrchestrationEvent,
applyOrchestrationEvents,
syncServerReadModel,
type AppState,
} from "./store";
import { markThreadUnread, reorderProjects, syncServerReadModel, type AppState } from "./store";
import { DEFAULT_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, type Thread } from "./types";
function makeThread(overrides: Partial<Thread> = {}): Thread {
@@ -57,41 +48,15 @@ function makeState(thread: Thread): AppState {
provider: "codex",
model: "gpt-5-codex",
},
expanded: true,
scripts: [],
},
],
threads: [thread],
bootstrapComplete: true,
threadsHydrated: true,
};
}
function makeEvent<T extends OrchestrationEvent["type"]>(
type: T,
payload: Extract<OrchestrationEvent, { type: T }>["payload"],
overrides: Partial<Extract<OrchestrationEvent, { type: T }>> = {},
): Extract<OrchestrationEvent, { type: T }> {
const sequence = overrides.sequence ?? 1;
return {
sequence,
eventId: EventId.makeUnsafe(`event-${sequence}`),
aggregateKind: "thread",
aggregateId:
"threadId" in payload
? payload.threadId
: "projectId" in payload
? payload.projectId
: ProjectId.makeUnsafe("project-1"),
occurredAt: "2026-02-27T00:00:00.000Z",
commandId: null,
causationEventId: null,
correlationId: null,
metadata: {},
type,
payload,
...overrides,
} as Extract<OrchestrationEvent, { type: T }>;
}
function makeReadModelThread(overrides: Partial<OrchestrationReadModel["threads"][number]>) {
return {
id: ThreadId.makeUnsafe("thread-1"),
@@ -161,18 +126,97 @@ function makeReadModelProject(
};
}
describe("store read model sync", () => {
it("marks bootstrap complete after snapshot sync", () => {
const initialState: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
describe("store pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeState(
makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "completed",
requestedAt: "2026-02-25T12:28:00.000Z",
startedAt: "2026-02-25T12:28:30.000Z",
completedAt: latestTurnCompletedAt,
assistantMessageId: null,
},
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
const next = syncServerReadModel(initialState, makeReadModel(makeReadModelThread({})));
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
expect(next.bootstrapComplete).toBe(true);
const updatedThread = next.threads[0];
expect(updatedThread).toBeDefined();
expect(updatedThread?.lastVisitedAt).toBe("2026-02-25T12:29:59.999Z");
expect(Date.parse(updatedThread?.lastVisitedAt ?? "")).toBeLessThan(
Date.parse(latestTurnCompletedAt),
);
});
it("markThreadUnread does not change a thread without a completed turn", () => {
const initialState = makeState(
makeThread({
latestTurn: null,
lastVisitedAt: "2026-02-25T12:35:00.000Z",
}),
);
const next = markThreadUnread(initialState, ThreadId.makeUnsafe("thread-1"));
expect(next).toEqual(initialState);
});
it("reorderProjects moves a project to a target index", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const state: AppState = {
projects: [
{
id: project1,
name: "Project 1",
cwd: "/tmp/project-1",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project2,
name: "Project 2",
cwd: "/tmp/project-2",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
id: project3,
name: "Project 3",
cwd: "/tmp/project-3",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
threadsHydrated: true,
};
const next = reorderProjects(state, project1, project3);
expect(next.projects.map((project) => project.id)).toEqual([project2, project3, project1]);
});
});
describe("store read model sync", () => {
it("preserves claude model slugs without an active session", () => {
const initialState = makeState(makeThread());
const readModel = makeReadModel(
@@ -243,7 +287,7 @@ describe("store read model sync", () => {
expect(next.threads[0]?.archivedAt).toBe(archivedAt);
});
it("replaces projects using snapshot order during recovery", () => {
it("preserves the current project order when syncing incoming read model updates", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
@@ -257,6 +301,7 @@ describe("store read model sync", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
{
@@ -267,11 +312,12 @@ describe("store read model sync", () => {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
expanded: true,
scripts: [],
},
],
threads: [],
bootstrapComplete: true,
threadsHydrated: true,
};
const readModel: OrchestrationReadModel = {
snapshotSequence: 2,
@@ -298,446 +344,6 @@ describe("store read model sync", () => {
const next = syncServerReadModel(initialState, readModel);
expect(next.projects.map((project) => project.id)).toEqual([project1, project2, project3]);
});
});
describe("incremental orchestration updates", () => {
it("does not mark bootstrap complete for incremental events", () => {
const state: AppState = {
...makeState(makeThread()),
bootstrapComplete: false,
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.meta-updated", {
threadId: ThreadId.makeUnsafe("thread-1"),
title: "Updated title",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.bootstrapComplete).toBe(false);
});
it("preserves state identity for no-op project and thread deletes", () => {
const thread = makeThread();
const state = makeState(thread);
const nextAfterProjectDelete = applyOrchestrationEvent(
state,
makeEvent("project.deleted", {
projectId: ProjectId.makeUnsafe("project-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
const nextAfterThreadDelete = applyOrchestrationEvent(
state,
makeEvent("thread.deleted", {
threadId: ThreadId.makeUnsafe("thread-missing"),
deletedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(nextAfterProjectDelete).toBe(state);
expect(nextAfterThreadDelete).toBe(state);
});
it("reuses an existing project row when project.created arrives with a new id for the same cwd", () => {
const originalProjectId = ProjectId.makeUnsafe("project-1");
const recreatedProjectId = ProjectId.makeUnsafe("project-2");
const state: AppState = {
projects: [
{
id: originalProjectId,
name: "Project",
cwd: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
},
],
threads: [],
bootstrapComplete: true,
};
const next = applyOrchestrationEvent(
state,
makeEvent("project.created", {
projectId: recreatedProjectId,
title: "Project Recreated",
workspaceRoot: "/tmp/project",
defaultModelSelection: {
provider: "codex",
model: DEFAULT_MODEL_BY_PROVIDER.codex,
},
scripts: [],
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.projects).toHaveLength(1);
expect(next.projects[0]?.id).toBe(recreatedProjectId);
expect(next.projects[0]?.cwd).toBe("/tmp/project");
expect(next.projects[0]?.name).toBe("Project Recreated");
});
it("updates only the affected thread for message events", () => {
const thread1 = makeThread({
id: ThreadId.makeUnsafe("thread-1"),
messages: [
{
id: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: "hello",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
],
});
const thread2 = makeThread({ id: ThreadId.makeUnsafe("thread-2") });
const state: AppState = {
...makeState(thread1),
threads: [thread1, thread2],
};
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: thread1.id,
messageId: MessageId.makeUnsafe("message-1"),
role: "assistant",
text: " world",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: true,
createdAt: "2026-02-27T00:00:01.000Z",
updatedAt: "2026-02-27T00:00:01.000Z",
}),
);
expect(next.threads[0]?.messages[0]?.text).toBe("hello world");
expect(next.threads[0]?.latestTurn?.state).toBe("running");
expect(next.threads[1]).toBe(thread2);
});
it("applies replay batches in sequence and updates session state", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-1"),
state: "running",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: null,
assistantMessageId: null,
},
});
const state = makeState(thread);
const next = applyOrchestrationEvents(state, [
makeEvent(
"thread.session-set",
{
threadId: thread.id,
session: {
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-1"),
lastError: null,
updatedAt: "2026-02-27T00:00:02.000Z",
},
},
{ sequence: 2 },
),
makeEvent(
"thread.message-sent",
{
threadId: thread.id,
messageId: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "done",
turnId: TurnId.makeUnsafe("turn-1"),
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
},
{ sequence: 3 },
),
]);
expect(next.threads[0]?.session?.status).toBe("running");
expect(next.threads[0]?.latestTurn?.state).toBe("completed");
expect(next.threads[0]?.messages).toHaveLength(1);
});
it("does not regress latestTurn when an older turn diff completes late", () => {
const state = makeState(
makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "running",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:03.000Z",
completedAt: null,
assistantMessageId: null,
},
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.turn-diff-completed", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnId: TurnId.makeUnsafe("turn-1"),
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
status: "ready",
files: [],
assistantMessageId: MessageId.makeUnsafe("assistant-1"),
completedAt: "2026-02-27T00:00:04.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries).toHaveLength(1);
expect(next.threads[0]?.latestTurn).toEqual(state.threads[0]?.latestTurn);
});
it("rebinds live turn diffs to the authoritative assistant message when it arrives later", () => {
const turnId = TurnId.makeUnsafe("turn-1");
const state = makeState(
makeThread({
latestTurn: {
turnId,
state: "completed",
requestedAt: "2026-02-27T00:00:00.000Z",
startedAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
},
turnDiffSummaries: [
{
turnId,
completedAt: "2026-02-27T00:00:02.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("checkpoint-1"),
assistantMessageId: MessageId.makeUnsafe("assistant:turn-1"),
files: [{ path: "src/app.ts", additions: 1, deletions: 0 }],
},
],
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.message-sent", {
threadId: ThreadId.makeUnsafe("thread-1"),
messageId: MessageId.makeUnsafe("assistant-real"),
role: "assistant",
text: "final answer",
turnId,
streaming: false,
createdAt: "2026-02-27T00:00:03.000Z",
updatedAt: "2026-02-27T00:00:03.000Z",
}),
);
expect(next.threads[0]?.turnDiffSummaries[0]?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
expect(next.threads[0]?.latestTurn?.assistantMessageId).toBe(
MessageId.makeUnsafe("assistant-real"),
);
});
it("reverts messages, plans, activities, and checkpoints by retained turns", () => {
const state = makeState(
makeThread({
messages: [
{
id: MessageId.makeUnsafe("user-1"),
role: "user",
text: "first",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
completedAt: "2026-02-27T00:00:00.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("assistant-1"),
role: "assistant",
text: "first reply",
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:01.000Z",
completedAt: "2026-02-27T00:00:01.000Z",
streaming: false,
},
{
id: MessageId.makeUnsafe("user-2"),
role: "user",
text: "second",
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:02.000Z",
streaming: false,
},
],
proposedPlans: [
{
id: "plan-1",
turnId: TurnId.makeUnsafe("turn-1"),
planMarkdown: "plan 1",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:00.000Z",
updatedAt: "2026-02-27T00:00:00.000Z",
},
{
id: "plan-2",
turnId: TurnId.makeUnsafe("turn-2"),
planMarkdown: "plan 2",
implementedAt: null,
implementationThreadId: null,
createdAt: "2026-02-27T00:00:02.000Z",
updatedAt: "2026-02-27T00:00:02.000Z",
},
],
activities: [
{
id: EventId.makeUnsafe("activity-1"),
tone: "info",
kind: "step",
summary: "one",
payload: {},
turnId: TurnId.makeUnsafe("turn-1"),
createdAt: "2026-02-27T00:00:00.000Z",
},
{
id: EventId.makeUnsafe("activity-2"),
tone: "info",
kind: "step",
summary: "two",
payload: {},
turnId: TurnId.makeUnsafe("turn-2"),
createdAt: "2026-02-27T00:00:02.000Z",
},
],
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
}),
);
const next = applyOrchestrationEvent(
state,
makeEvent("thread.reverted", {
threadId: ThreadId.makeUnsafe("thread-1"),
turnCount: 1,
}),
);
expect(next.threads[0]?.messages.map((message) => message.id)).toEqual([
"user-1",
"assistant-1",
]);
expect(next.threads[0]?.proposedPlans.map((plan) => plan.id)).toEqual(["plan-1"]);
expect(next.threads[0]?.activities.map((activity) => activity.id)).toEqual([
EventId.makeUnsafe("activity-1"),
]);
expect(next.threads[0]?.turnDiffSummaries.map((summary) => summary.turnId)).toEqual([
TurnId.makeUnsafe("turn-1"),
]);
});
it("clears pending source proposed plans after revert before a new session-set event", () => {
const thread = makeThread({
latestTurn: {
turnId: TurnId.makeUnsafe("turn-2"),
state: "completed",
requestedAt: "2026-02-27T00:00:02.000Z",
startedAt: "2026-02-27T00:00:02.000Z",
completedAt: "2026-02-27T00:00:03.000Z",
assistantMessageId: MessageId.makeUnsafe("assistant-2"),
sourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
},
pendingSourceProposedPlan: {
threadId: ThreadId.makeUnsafe("thread-source"),
planId: "plan-2" as never,
},
turnDiffSummaries: [
{
turnId: TurnId.makeUnsafe("turn-1"),
completedAt: "2026-02-27T00:00:01.000Z",
status: "ready",
checkpointTurnCount: 1,
checkpointRef: CheckpointRef.makeUnsafe("ref-1"),
files: [],
},
{
turnId: TurnId.makeUnsafe("turn-2"),
completedAt: "2026-02-27T00:00:03.000Z",
status: "ready",
checkpointTurnCount: 2,
checkpointRef: CheckpointRef.makeUnsafe("ref-2"),
files: [],
},
],
});
const reverted = applyOrchestrationEvent(
makeState(thread),
makeEvent("thread.reverted", {
threadId: thread.id,
turnCount: 1,
}),
);
expect(reverted.threads[0]?.pendingSourceProposedPlan).toBeUndefined();
const next = applyOrchestrationEvent(
reverted,
makeEvent("thread.session-set", {
threadId: thread.id,
session: {
threadId: thread.id,
status: "running",
providerName: "codex",
runtimeMode: "full-access",
activeTurnId: TurnId.makeUnsafe("turn-3"),
lastError: null,
updatedAt: "2026-02-27T00:00:04.000Z",
},
}),
);
expect(next.threads[0]?.latestTurn).toMatchObject({
turnId: TurnId.makeUnsafe("turn-3"),
state: "running",
});
expect(next.threads[0]?.latestTurn?.sourceProposedPlan).toBeUndefined();
expect(next.projects.map((project) => project.id)).toEqual([project2, project1, project3]);
});
});
+308 -788
View File
File diff suppressed because it is too large. Load diff
-14
View File
@@ -1,14 +0,0 @@
import { type ThreadId } from "@t3tools/contracts";
import { useMemo } from "react";
import { selectProjectById, selectThreadById, useStore } from "./store";
import { type Project, type Thread } from "./types";
export function useProjectById(projectId: Project["id"] | null | undefined): Project | undefined {
const selector = useMemo(() => selectProjectById(projectId), [projectId]);
return useStore(selector);
}
export function useThreadById(threadId: ThreadId | null | undefined): Thread | undefined {
const selector = useMemo(() => selectThreadById(threadId), [threadId]);
return useStore(selector);
}
-10
View File
@@ -485,7 +485,6 @@ interface TerminalStateStoreState {
hasRunningSubprocess: boolean,
) => void;
clearTerminalState: (threadId: ThreadId) => void;
removeTerminalState: (threadId: ThreadId) => void;
removeOrphanedTerminalStates: (activeThreadIds: Set<ThreadId>) => void;
}
@@ -531,15 +530,6 @@ export const useTerminalStateStore = create<TerminalStateStoreState>()(
),
clearTerminalState: (threadId) =>
updateTerminal(threadId, () => createDefaultThreadTerminalState()),
removeTerminalState: (threadId) =>
set((state) => {
if (state.terminalStateByThreadId[threadId] === undefined) {
return state;
}
const next = { ...state.terminalStateByThreadId };
delete next[threadId];
return { terminalStateByThreadId: next };
}),
removeOrphanedTerminalStates: (activeThreadIds) =>
set((state) => {
const orphanedIds = Object.keys(state.terminalStateByThreadId).filter(
+2 -2
View File
@@ -45,7 +45,6 @@ export interface ChatMessage {
role: "user" | "assistant" | "system";
text: string;
attachments?: ChatAttachment[];
turnId?: TurnId | null;
createdAt: string;
completedAt?: string | undefined;
streaming: boolean;
@@ -83,6 +82,7 @@ export interface Project {
name: string;
cwd: string;
defaultModelSelection: ModelSelection | null;
expanded: boolean;
createdAt?: string | undefined;
updatedAt?: string | undefined;
scripts: ProjectScript[];
@@ -104,7 +104,7 @@ export interface Thread {
archivedAt: string | null;
updatedAt?: string | undefined;
latestTurn: OrchestrationLatestTurn | null;
pendingSourceProposedPlan?: OrchestrationLatestTurn["sourceProposedPlan"];
lastVisitedAt?: string | undefined;
branch: string | null;
worktreePath: string | null;
turnDiffSummaries: TurnDiffSummary[];
-192
View File
@@ -1,192 +0,0 @@
import { ProjectId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vitest";
import {
clearThreadUi,
markThreadUnread,
reorderProjects,
setProjectExpanded,
syncProjects,
syncThreads,
type UiState,
} from "./uiStateStore";
function makeUiState(overrides: Partial<UiState> = {}): UiState {
return {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
...overrides,
};
}
describe("uiStateStore pure functions", () => {
it("markThreadUnread moves lastVisitedAt before completion for a completed thread", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const latestTurnCompletedAt = "2026-02-25T12:30:00.000Z";
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:35:00.000Z",
},
});
const next = markThreadUnread(initialState, threadId, latestTurnCompletedAt);
expect(next.threadLastVisitedAtById[threadId]).toBe("2026-02-25T12:29:59.999Z");
});
it("markThreadUnread does not change a thread without a completed turn", () => {
const threadId = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[threadId]: "2026-02-25T12:35:00.000Z",
},
});
const next = markThreadUnread(initialState, threadId, null);
expect(next).toBe(initialState);
});
it("reorderProjects moves a project to a target index", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState = makeUiState({
projectOrder: [project1, project2, project3],
});
const next = reorderProjects(initialState, project1, project3);
expect(next.projectOrder).toEqual([project2, project3, project1]);
});
it("syncProjects preserves current project order during snapshot recovery", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const project2 = ProjectId.makeUnsafe("project-2");
const project3 = ProjectId.makeUnsafe("project-3");
const initialState = makeUiState({
projectExpandedById: {
[project1]: true,
[project2]: false,
},
projectOrder: [project2, project1],
});
const next = syncProjects(initialState, [
{ id: project1, cwd: "/tmp/project-1" },
{ id: project2, cwd: "/tmp/project-2" },
{ id: project3, cwd: "/tmp/project-3" },
]);
expect(next.projectOrder).toEqual([project2, project1, project3]);
expect(next.projectExpandedById[project2]).toBe(false);
});
it("syncProjects preserves manual order when a project is recreated with the same cwd", () => {
const oldProject1 = ProjectId.makeUnsafe("project-1");
const oldProject2 = ProjectId.makeUnsafe("project-2");
const recreatedProject2 = ProjectId.makeUnsafe("project-2b");
const initialState = syncProjects(
makeUiState({
projectExpandedById: {
[oldProject1]: true,
[oldProject2]: false,
},
projectOrder: [oldProject2, oldProject1],
}),
[
{ id: oldProject1, cwd: "/tmp/project-1" },
{ id: oldProject2, cwd: "/tmp/project-2" },
],
);
const next = syncProjects(initialState, [
{ id: oldProject1, cwd: "/tmp/project-1" },
{ id: recreatedProject2, cwd: "/tmp/project-2" },
]);
expect(next.projectOrder).toEqual([recreatedProject2, oldProject1]);
expect(next.projectExpandedById[recreatedProject2]).toBe(false);
});
it("syncProjects returns a new state when only project cwd changes", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const initialState = syncProjects(
makeUiState({
projectExpandedById: {
[project1]: false,
},
projectOrder: [project1],
}),
[{ id: project1, cwd: "/tmp/project-1" }],
);
const next = syncProjects(initialState, [{ id: project1, cwd: "/tmp/project-1-renamed" }]);
expect(next).not.toBe(initialState);
expect(next.projectOrder).toEqual([project1]);
expect(next.projectExpandedById[project1]).toBe(false);
});
it("syncThreads prunes missing thread UI state", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const thread2 = ThreadId.makeUnsafe("thread-2");
const initialState = makeUiState({
threadLastVisitedAtById: {
[thread1]: "2026-02-25T12:35:00.000Z",
[thread2]: "2026-02-25T12:36:00.000Z",
},
});
const next = syncThreads(initialState, [{ id: thread1 }]);
expect(next.threadLastVisitedAtById).toEqual({
[thread1]: "2026-02-25T12:35:00.000Z",
});
});
it("syncThreads seeds visit state for unseen snapshot threads", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState();
const next = syncThreads(initialState, [
{
id: thread1,
seedVisitedAt: "2026-02-25T12:35:00.000Z",
},
]);
expect(next.threadLastVisitedAtById).toEqual({
[thread1]: "2026-02-25T12:35:00.000Z",
});
});
it("setProjectExpanded updates expansion without touching order", () => {
const project1 = ProjectId.makeUnsafe("project-1");
const initialState = makeUiState({
projectExpandedById: {
[project1]: true,
},
projectOrder: [project1],
});
const next = setProjectExpanded(initialState, project1, false);
expect(next.projectExpandedById[project1]).toBe(false);
expect(next.projectOrder).toEqual([project1]);
});
it("clearThreadUi removes visit state for deleted threads", () => {
const thread1 = ThreadId.makeUnsafe("thread-1");
const initialState = makeUiState({
threadLastVisitedAtById: {
[thread1]: "2026-02-25T12:35:00.000Z",
},
});
const next = clearThreadUi(initialState, thread1);
expect(next.threadLastVisitedAtById).toEqual({});
});
});
-417
View File
@@ -1,417 +0,0 @@
import { Debouncer } from "@tanstack/react-pacer";
import { type ProjectId, type ThreadId } from "@t3tools/contracts";
import { create } from "zustand";
const PERSISTED_STATE_KEY = "t3code:ui-state:v1";
const LEGACY_PERSISTED_STATE_KEYS = [
"t3code:renderer-state:v8",
"t3code:renderer-state:v7",
"t3code:renderer-state:v6",
"t3code:renderer-state:v5",
"t3code:renderer-state:v4",
"t3code:renderer-state:v3",
"codething:renderer-state:v4",
"codething:renderer-state:v3",
"codething:renderer-state:v2",
"codething:renderer-state:v1",
] as const;
interface PersistedUiState {
expandedProjectCwds?: string[];
projectOrderCwds?: string[];
}
export interface UiProjectState {
projectExpandedById: Record<string, boolean>;
projectOrder: ProjectId[];
}
export interface UiThreadState {
threadLastVisitedAtById: Record<string, string>;
}
export interface UiState extends UiProjectState, UiThreadState {}
export interface SyncProjectInput {
id: ProjectId;
cwd: string;
}
export interface SyncThreadInput {
id: ThreadId;
seedVisitedAt?: string | undefined;
}
const initialState: UiState = {
projectExpandedById: {},
projectOrder: [],
threadLastVisitedAtById: {},
};
const persistedExpandedProjectCwds = new Set<string>();
const persistedProjectOrderCwds: string[] = [];
const currentProjectCwdById = new Map<ProjectId, string>();
let legacyKeysCleanedUp = false;
function readPersistedState(): UiState {
if (typeof window === "undefined") {
return initialState;
}
try {
const raw = window.localStorage.getItem(PERSISTED_STATE_KEY);
if (!raw) {
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
const legacyRaw = window.localStorage.getItem(legacyKey);
if (!legacyRaw) {
continue;
}
hydratePersistedProjectState(JSON.parse(legacyRaw) as PersistedUiState);
return initialState;
}
return initialState;
}
hydratePersistedProjectState(JSON.parse(raw) as PersistedUiState);
return initialState;
} catch {
return initialState;
}
}
function hydratePersistedProjectState(parsed: PersistedUiState): void {
persistedExpandedProjectCwds.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.projectOrderCwds ?? []) {
if (typeof cwd === "string" && cwd.length > 0 && !persistedProjectOrderCwds.includes(cwd)) {
persistedProjectOrderCwds.push(cwd);
}
}
}
function persistState(state: UiState): void {
if (typeof window === "undefined") {
return;
}
try {
const expandedProjectCwds = Object.entries(state.projectExpandedById)
.filter(([, expanded]) => expanded)
.flatMap(([projectId]) => {
const cwd = currentProjectCwdById.get(projectId as ProjectId);
return cwd ? [cwd] : [];
});
const projectOrderCwds = state.projectOrder.flatMap((projectId) => {
const cwd = currentProjectCwdById.get(projectId);
return cwd ? [cwd] : [];
});
window.localStorage.setItem(
PERSISTED_STATE_KEY,
JSON.stringify({
expandedProjectCwds,
projectOrderCwds,
} satisfies PersistedUiState),
);
if (!legacyKeysCleanedUp) {
legacyKeysCleanedUp = true;
for (const legacyKey of LEGACY_PERSISTED_STATE_KEYS) {
window.localStorage.removeItem(legacyKey);
}
}
} catch {
// Ignore quota/storage errors to avoid breaking chat UX.
}
}
const debouncedPersistState = new Debouncer(persistState, { wait: 500 });
function recordsEqual<T>(left: Record<string, T>, right: Record<string, T>): boolean {
const leftEntries = Object.entries(left);
const rightEntries = Object.entries(right);
if (leftEntries.length !== rightEntries.length) {
return false;
}
for (const [key, value] of leftEntries) {
if (right[key] !== value) {
return false;
}
}
return true;
}
function projectOrdersEqual(left: readonly ProjectId[], right: readonly ProjectId[]): boolean {
return (
left.length === right.length && left.every((projectId, index) => projectId === right[index])
);
}
export function syncProjects(state: UiState, projects: readonly SyncProjectInput[]): UiState {
const previousProjectCwdById = new Map(currentProjectCwdById);
const previousProjectIdByCwd = new Map(
[...previousProjectCwdById.entries()].map(([projectId, cwd]) => [cwd, projectId] as const),
);
currentProjectCwdById.clear();
for (const project of projects) {
currentProjectCwdById.set(project.id, project.cwd);
}
const cwdMappingChanged =
previousProjectCwdById.size !== currentProjectCwdById.size ||
projects.some((project) => previousProjectCwdById.get(project.id) !== project.cwd);
const nextExpandedById: Record<string, boolean> = {};
const previousExpandedById = state.projectExpandedById;
const persistedOrderByCwd = new Map(
persistedProjectOrderCwds.map((cwd, index) => [cwd, index] as const),
);
const mappedProjects = projects.map((project, index) => {
const previousProjectIdForCwd = previousProjectIdByCwd.get(project.cwd);
const expanded =
previousExpandedById[project.id] ??
(previousProjectIdForCwd ? previousExpandedById[previousProjectIdForCwd] : undefined) ??
(persistedExpandedProjectCwds.size > 0
? persistedExpandedProjectCwds.has(project.cwd)
: true);
nextExpandedById[project.id] = expanded;
return {
id: project.id,
cwd: project.cwd,
incomingIndex: index,
};
});
const nextProjectOrder =
state.projectOrder.length > 0
? (() => {
const nextProjectIdByCwd = new Map(
mappedProjects.map((project) => [project.cwd, project.id] as const),
);
const usedProjectIds = new Set<ProjectId>();
const orderedProjectIds: ProjectId[] = [];
for (const projectId of state.projectOrder) {
const matchedProjectId =
(projectId in nextExpandedById ? projectId : undefined) ??
(() => {
const previousCwd = previousProjectCwdById.get(projectId);
return previousCwd ? nextProjectIdByCwd.get(previousCwd) : undefined;
})();
if (!matchedProjectId || usedProjectIds.has(matchedProjectId)) {
continue;
}
usedProjectIds.add(matchedProjectId);
orderedProjectIds.push(matchedProjectId);
}
for (const project of mappedProjects) {
if (usedProjectIds.has(project.id)) {
continue;
}
orderedProjectIds.push(project.id);
}
return orderedProjectIds;
})()
: mappedProjects
.map((project) => ({
id: project.id,
incomingIndex: project.incomingIndex,
orderIndex:
persistedOrderByCwd.get(project.cwd) ??
persistedProjectOrderCwds.length + project.incomingIndex,
}))
.toSorted((left, right) => {
const byOrder = left.orderIndex - right.orderIndex;
if (byOrder !== 0) {
return byOrder;
}
return left.incomingIndex - right.incomingIndex;
})
.map((project) => project.id);
if (
recordsEqual(state.projectExpandedById, nextExpandedById) &&
projectOrdersEqual(state.projectOrder, nextProjectOrder) &&
!cwdMappingChanged
) {
return state;
}
return {
...state,
projectExpandedById: nextExpandedById,
projectOrder: nextProjectOrder,
};
}
export function syncThreads(state: UiState, threads: readonly SyncThreadInput[]): UiState {
const retainedThreadIds = new Set(threads.map((thread) => thread.id));
const nextThreadLastVisitedAtById = Object.fromEntries(
Object.entries(state.threadLastVisitedAtById).filter(([threadId]) =>
retainedThreadIds.has(threadId as ThreadId),
),
);
for (const thread of threads) {
if (
nextThreadLastVisitedAtById[thread.id] === undefined &&
thread.seedVisitedAt !== undefined &&
thread.seedVisitedAt.length > 0
) {
nextThreadLastVisitedAtById[thread.id] = thread.seedVisitedAt;
}
}
if (recordsEqual(state.threadLastVisitedAtById, nextThreadLastVisitedAtById)) {
return state;
}
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
};
}
export function markThreadVisited(state: UiState, threadId: ThreadId, visitedAt?: string): UiState {
const at = visitedAt ?? new Date().toISOString();
const visitedAtMs = Date.parse(at);
const previousVisitedAt = state.threadLastVisitedAtById[threadId];
const previousVisitedAtMs = previousVisitedAt ? Date.parse(previousVisitedAt) : NaN;
if (
Number.isFinite(previousVisitedAtMs) &&
Number.isFinite(visitedAtMs) &&
previousVisitedAtMs >= visitedAtMs
) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: at,
},
};
}
export function markThreadUnread(
state: UiState,
threadId: ThreadId,
latestTurnCompletedAt: string | null | undefined,
): UiState {
if (!latestTurnCompletedAt) {
return state;
}
const latestTurnCompletedAtMs = Date.parse(latestTurnCompletedAt);
if (Number.isNaN(latestTurnCompletedAtMs)) {
return state;
}
const unreadVisitedAt = new Date(latestTurnCompletedAtMs - 1).toISOString();
if (state.threadLastVisitedAtById[threadId] === unreadVisitedAt) {
return state;
}
return {
...state,
threadLastVisitedAtById: {
...state.threadLastVisitedAtById,
[threadId]: unreadVisitedAt,
},
};
}
export function clearThreadUi(state: UiState, threadId: ThreadId): UiState {
if (!(threadId in state.threadLastVisitedAtById)) {
return state;
}
const nextThreadLastVisitedAtById = { ...state.threadLastVisitedAtById };
delete nextThreadLastVisitedAtById[threadId];
return {
...state,
threadLastVisitedAtById: nextThreadLastVisitedAtById,
};
}
export function toggleProject(state: UiState, projectId: ProjectId): UiState {
const expanded = state.projectExpandedById[projectId] ?? true;
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: !expanded,
},
};
}
export function setProjectExpanded(
state: UiState,
projectId: ProjectId,
expanded: boolean,
): UiState {
if ((state.projectExpandedById[projectId] ?? true) === expanded) {
return state;
}
return {
...state,
projectExpandedById: {
...state.projectExpandedById,
[projectId]: expanded,
},
};
}
export function reorderProjects(
state: UiState,
draggedProjectId: ProjectId,
targetProjectId: ProjectId,
): UiState {
if (draggedProjectId === targetProjectId) {
return state;
}
const draggedIndex = state.projectOrder.findIndex((projectId) => projectId === draggedProjectId);
const targetIndex = state.projectOrder.findIndex((projectId) => projectId === targetProjectId);
if (draggedIndex < 0 || targetIndex < 0) {
return state;
}
const projectOrder = [...state.projectOrder];
const [draggedProject] = projectOrder.splice(draggedIndex, 1);
if (!draggedProject) {
return state;
}
projectOrder.splice(targetIndex, 0, draggedProject);
return {
...state,
projectOrder,
};
}
interface UiStateStore extends UiState {
syncProjects: (projects: readonly SyncProjectInput[]) => void;
syncThreads: (threads: readonly SyncThreadInput[]) => void;
markThreadVisited: (threadId: ThreadId, visitedAt?: string) => void;
markThreadUnread: (threadId: ThreadId, latestTurnCompletedAt: string | null | undefined) => void;
clearThreadUi: (threadId: ThreadId) => void;
toggleProject: (projectId: ProjectId) => void;
setProjectExpanded: (projectId: ProjectId, expanded: boolean) => void;
reorderProjects: (draggedProjectId: ProjectId, targetProjectId: ProjectId) => void;
}
export const useUiStateStore = create<UiStateStore>((set) => ({
...readPersistedState(),
syncProjects: (projects) => set((state) => syncProjects(state, projects)),
syncThreads: (threads) => set((state) => syncThreads(state, threads)),
markThreadVisited: (threadId, visitedAt) =>
set((state) => markThreadVisited(state, threadId, visitedAt)),
markThreadUnread: (threadId, latestTurnCompletedAt) =>
set((state) => markThreadUnread(state, threadId, latestTurnCompletedAt)),
clearThreadUi: (threadId) => set((state) => clearThreadUi(state, threadId)),
toggleProject: (projectId) => set((state) => toggleProject(state, projectId)),
setProjectExpanded: (projectId, expanded) =>
set((state) => setProjectExpanded(state, projectId, expanded)),
reorderProjects: (draggedProjectId, targetProjectId) =>
set((state) => reorderProjects(state, draggedProjectId, targetProjectId)),
}));
useUiStateStore.subscribe((state) => debouncedPersistState.maybeExecute(state));
if (typeof window !== "undefined") {
window.addEventListener("beforeunload", () => {
debouncedPersistState.flush();
});
}
+1 -1
View File
@@ -99,7 +99,7 @@ const defaultProviders: ReadonlyArray<ServerProvider> = [
installed: true,
version: "0.116.0",
status: "ready",
auth: { status: "authenticated" },
authStatus: "authenticated",
checkedAt: "2026-01-01T00:00:00.000Z",
models: [],
},
+26 -11
View File
@@ -54,6 +54,7 @@
"@pierre/diffs": "^1.1.0-beta.16",
"effect": "catalog:",
"node-pty": "^1.1.0",
"open": "^10.1.0",
"ws": "^8.18.0",
},
"devDependencies": {
@@ -175,13 +176,13 @@
"vite": "^8.0.0",
},
"catalog": {
"@effect/language-service": "0.84.2",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@effect/language-service": "0.84.1",
"@effect/platform-node": "4.0.0-beta.42",
"@effect/sql-sqlite-bun": "4.0.0-beta.42",
"@effect/vitest": "4.0.0-beta.42",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"effect": "4.0.0-beta.43",
"effect": "4.0.0-beta.42",
"tsdown": "^0.20.3",
"typescript": "^5.7.3",
"vitest": "^4.0.0",
@@ -267,15 +268,15 @@
"@dnd-kit/utilities": ["@dnd-kit/[email protected]", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "react": ">=16.8.0" } }, "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg=="],
"@effect/language-service": ["@effect/[email protected].2", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-l04qNxpiA8rY5yXWckRPJ7Mk5MNerXuNymSFf+IdflfI5i8jgL1bpBNLuP6ijg7wgjdHc/KmTnCj2kT0SCntuA=="],
"@effect/language-service": ["@effect/[email protected].1", "", { "bin": { "effect-language-service": "cli.js" } }, "sha512-YUqjJU24HeYgPV453cR2fDqkZ+zZKMuxGnmxWAPscWJ6gt6FB7JZohMCOczRTIOGPrQMcloJX7BjCaPu+RNhpw=="],
"@effect/platform-node": ["@effect/[email protected]3", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.43", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43", "ioredis": "^5.7.0" } }, "sha512-Uq6E1rjaIpjHauzjwoB2HzAg3battYt2Boy8XO50GoHiWCXKE6WapYZ0/AnaBx5v5qg2sOfqpuiLsUf9ZgxOkA=="],
"@effect/platform-node": ["@effect/[email protected]2", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-beta.42", "mime": "^4.1.0", "undici": "^7.24.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42", "ioredis": "^5.7.0" } }, "sha512-kbdRML2FBa4q8U8rZQcnmLKZ5zN/z1bAA7t5D1/UsBHZqJgnfRgu1CP6kaEfb1Nie6YyaWshxTktZQryjvW/Yg=="],
"@effect/platform-node-shared": ["@effect/[email protected]3", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-A9q0GEb61pYcQ06Dr6gXj1nKlDI3KHsar1sk3qb1ZY+kVSR64tBAylI8zGon23KY+NPtTUj/sEIToB7jc3Qt5w=="],
"@effect/platform-node-shared": ["@effect/[email protected]2", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.19.0" }, "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-PC+lxLsrwob3+nBChAPrQq32olCeyApgXBvs1NrRsoArLViNT76T/68CttuCAksCZj5e1bZ1ZibLPel3vUmx2g=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected]3", "", { "peerDependencies": { "effect": "^4.0.0-beta.43" } }, "sha512-Ryb7x0rBjW5NHegbzvz9y2Yv4KpwZ1UiPk7/Rv+Mkux74Qkjdmotmrvy9P+M5A9TZyL2Av+GpaLTPJKsL0PG+Q=="],
"@effect/sql-sqlite-bun": ["@effect/[email protected]2", "", { "peerDependencies": { "effect": "^4.0.0-beta.42" } }, "sha512-Ah2QfkeV+I9r5OBVJijSDnFXCv51giBXngSwhju5gefc0uWiM3G1tsYAqrNX24HlvFFEnOAZqNf/Sq1h4NqOAA=="],
"@effect/vitest": ["@effect/[email protected]3", "", { "peerDependencies": { "effect": "^4.0.0-beta.43", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-XN2LAwiUWPqbV2jrsYYRjrVydQ8MIgwr83MVImtUaOQco4vk43+8OHlXQMRN/u2HnGK29KT+O2yTMMBdk2Q6Sw=="],
"@effect/vitest": ["@effect/[email protected]2", "", { "peerDependencies": { "effect": "^4.0.0-beta.42", "vitest": "^3.0.0 || ^4.0.0" } }, "sha512-/11arjUnCRhIrBRvOn/nrbg5p/FadjAPvStddZlpl1VrCxtB2s0n39cbG9uTyDdf1ZrRBG73Upo1ZDF1CTWy8w=="],
"@electron/get": ["@electron/[email protected]", "", { "dependencies": { "debug": "^4.1.1", "env-paths": "^2.2.0", "fs-extra": "^8.1.0", "got": "^11.8.5", "progress": "^2.0.3", "semver": "^6.2.0", "sumchecker": "^3.0.1" }, "optionalDependencies": { "global-agent": "^3.0.0" } }, "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ=="],
@@ -895,6 +896,8 @@
"bun-types": ["[email protected]", "", { "dependencies": { "@types/node": "*" } }, "sha512-tcpfCCl6XWo6nCVnpcVrxQ+9AYN1iqMIzgrSKYMB/fjLtV2eyAVEg7AxQJuCq/26R6HpKWykQXuSOq/21RYcbg=="],
"bundle-name": ["[email protected]", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="],
"cac": ["[email protected]", "", {}, "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ=="],
"cacheable-lookup": ["[email protected]", "", {}, "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA=="],
@@ -969,10 +972,16 @@
"decompress-response": ["[email protected]", "", { "dependencies": { "mimic-response": "^3.1.0" } }, "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ=="],
"default-browser": ["[email protected]", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="],
"default-browser-id": ["[email protected]", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="],
"defer-to-connect": ["[email protected]", "", {}, "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg=="],
"define-data-property": ["[email protected]", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
"define-lazy-prop": ["[email protected]", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="],
"define-properties": ["[email protected]", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
"defu": ["[email protected]", "", {}, "sha512-mEQCMmwJu317oSz8CwdIOdwf3xMif1ttiM8LTufzc3g6kR+9Pe236twL8j3IYT1F7GfRgGcW6MWxzZjLIkuHIg=="],
@@ -1011,7 +1020,7 @@
"dunder-proto": ["[email protected]", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"effect": ["[email protected]3", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-AJYyDimIwJOn87uUz/JzmgDc5GfjxJbXvEbTvNzMa+M3Uer344bLo/O5mMRkqc1vBleA+Ygs4+dbE3QsqOkKTQ=="],
"effect": ["[email protected]2", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.5.3", "find-my-way-ts": "^0.1.6", "ini": "^6.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^1.11.8", "multipasta": "^0.2.7", "toml": "^3.0.0", "uuid": "^13.0.0", "yaml": "^2.8.2" } }, "sha512-c1UrRP+tLzyHb4Fepl8XBDJlLQLkrcMXrRBba441GQRxMbeQ/aIOSFcBwSda1iMJ5l9F0lYc3Bhe33/whrmavQ=="],
"electron": ["[email protected]", "", { "dependencies": { "@electron/get": "^2.0.0", "@types/node": "^24.9.0", "extract-zip": "^2.0.1" }, "bin": { "electron": "cli.js" } }, "sha512-ett8W+yOFGDuM0vhJMamYSkrbV3LoaffzJd9GfjI96zRAxyrNqUSKqBpf/WGbQCweDxX2pkUCUfrv4wwKpsFZA=="],
@@ -1453,6 +1462,8 @@
"oniguruma-to-es": ["[email protected]", "", { "dependencies": { "oniguruma-parser": "^0.12.1", "regex": "^6.1.0", "regex-recursion": "^6.0.2" } }, "sha512-Zjygswjpsewa0NLTsiizVuMQZbp0MDyM6lIt66OxsF21npUDlzpHi1Mgb/qhQdkb+dWFTzJmFbEWdvZgRho8eQ=="],
"open": ["[email protected]", "", { "dependencies": { "default-browser": "^5.2.1", "define-lazy-prop": "^3.0.0", "is-inside-container": "^1.0.0", "wsl-utils": "^0.1.0" } }, "sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA=="],
"outvariant": ["[email protected]", "", {}, "sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA=="],
"oxfmt": ["[email protected]", "", { "dependencies": { "tinypool": "2.1.0" }, "optionalDependencies": { "@oxfmt/binding-android-arm-eabi": "0.40.0", "@oxfmt/binding-android-arm64": "0.40.0", "@oxfmt/binding-darwin-arm64": "0.40.0", "@oxfmt/binding-darwin-x64": "0.40.0", "@oxfmt/binding-freebsd-x64": "0.40.0", "@oxfmt/binding-linux-arm-gnueabihf": "0.40.0", "@oxfmt/binding-linux-arm-musleabihf": "0.40.0", "@oxfmt/binding-linux-arm64-gnu": "0.40.0", "@oxfmt/binding-linux-arm64-musl": "0.40.0", "@oxfmt/binding-linux-ppc64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-gnu": "0.40.0", "@oxfmt/binding-linux-riscv64-musl": "0.40.0", "@oxfmt/binding-linux-s390x-gnu": "0.40.0", "@oxfmt/binding-linux-x64-gnu": "0.40.0", "@oxfmt/binding-linux-x64-musl": "0.40.0", "@oxfmt/binding-openharmony-arm64": "0.40.0", "@oxfmt/binding-win32-arm64-msvc": "0.40.0", "@oxfmt/binding-win32-ia32-msvc": "0.40.0", "@oxfmt/binding-win32-x64-msvc": "0.40.0" }, "bin": { "oxfmt": "bin/oxfmt" } }, "sha512-g0C3I7xUj4b4DcagevM9kgH6+pUHytikxUcn3/VUkvzTNaaXBeyZqb7IBsHwojeXm4mTBEC/aBjBTMVUkZwWUQ=="],
@@ -1587,6 +1598,8 @@
"rolldown-plugin-dts": ["[email protected]", "", { "dependencies": { "@babel/generator": "8.0.0-rc.2", "@babel/helper-validator-identifier": "8.0.0-rc.2", "@babel/parser": "8.0.0-rc.2", "@babel/types": "8.0.0-rc.2", "ast-kit": "^3.0.0-beta.1", "birpc": "^4.0.0", "dts-resolver": "^2.1.3", "get-tsconfig": "^4.13.6", "obug": "^2.1.1" }, "peerDependencies": { "@ts-macro/tsc": "^0.3.6", "@typescript/native-preview": ">=7.0.0-dev.20250601.1", "rolldown": "^1.0.0-rc.3", "typescript": "^5.0.0 || ^6.0.0-beta", "vue-tsc": "~3.2.0" }, "optionalPeers": ["@ts-macro/tsc", "@typescript/native-preview", "typescript", "vue-tsc"] }, "sha512-M/HXfM4cboo+jONx9Z0X+CUf3B5tCi7ni+kR5fUW50Fp9AlZk0oVLesibGWgCXDKFp5lpgQ9yhKoImUFjl3VZw=="],
"run-applescript": ["[email protected]", "", {}, "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q=="],
"rxjs": ["[email protected]", "", { "dependencies": { "tslib": "^2.1.0" } }, "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA=="],
"sax": ["[email protected]", "", {}, "sha512-21IYA3Q5cQf089Z6tgaUTr7lDAyzoTPx5HRtbhsME8Udispad8dC/+sziTNugOEx54ilvatQ9YCzl4KQLPcRHA=="],
@@ -1843,6 +1856,8 @@
"ws": ["[email protected]", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg=="],
"wsl-utils": ["[email protected]", "", { "dependencies": { "is-wsl": "^3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="],
"xxhash-wasm": ["[email protected]", "", {}, "sha512-147y/6YNh+tlp6nd/2pWq38i9h6mz/EuQ6njIrmW8D1BS5nCqs0P6DG+m6zTGnNz5I+uhZ0SHxBs9BsPrwcKDA=="],
"y18n": ["[email protected]", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
+5 -5
View File
@@ -8,11 +8,11 @@
"scripts"
],
"catalog": {
"effect": "4.0.0-beta.43",
"@effect/platform-node": "4.0.0-beta.43",
"@effect/sql-sqlite-bun": "4.0.0-beta.43",
"@effect/vitest": "4.0.0-beta.43",
"@effect/language-service": "0.84.2",
"effect": "4.0.0-beta.42",
"@effect/platform-node": "4.0.0-beta.42",
"@effect/sql-sqlite-bun": "4.0.0-beta.42",
"@effect/vitest": "4.0.0-beta.42",
"@effect/language-service": "0.84.1",
"@types/bun": "^1.3.9",
"@types/node": "^24.10.13",
"tsdown": "^0.20.3",
+5
View File
@@ -10,6 +10,11 @@
"module": "./dist/index.mjs",
"types": "./src/index.ts",
"exports": {
"./appearanceTheme": {
"types": "./src/appearanceTheme.ts",
"import": "./src/appearanceTheme.ts",
"require": "./src/appearanceTheme.ts"
},
"./settings": {
"types": "./src/settings.ts",
"import": "./src/settings.ts",
+304
View File
@@ -0,0 +1,304 @@
import * as Schema from "effect/Schema";
import { TrimmedNonEmptyString } from "./baseSchemas";
const HEX_COLOR_PATTERN = /^#(?:[0-9a-f]{6}|[0-9a-f]{8})$/i;
const HexColor = TrimmedNonEmptyString.check(Schema.isPattern(HEX_COLOR_PATTERN)).annotate({
title: "Hex color",
description: "A 6-digit or 8-digit hex color string.",
examples: ["#0169cc", "#f5f7fb", "#0d0d0d"],
});
const CssColorValue = TrimmedNonEmptyString.annotate({
title: "CSS color value",
description: "Any valid CSS color string or color-mix expression.",
examples: ["#0b6bcb", "rgb(10 20 30 / 80%)", "color-mix(in srgb, #111 92%, #fff)"],
});
const FontFamilyValue = TrimmedNonEmptyString.annotate({
title: "Font family",
description: "A CSS font-family value.",
examples: [
'"Fraunces", "Iowan Old Style", serif',
'"IBM Plex Sans", "Segoe UI", sans-serif',
'"SF Mono", Menlo, monospace',
],
});
const CssLengthValue = TrimmedNonEmptyString.annotate({
title: "CSS length",
description: "A CSS length value such as px, rem, or em.",
examples: ["16px", "0.625rem", "1em"],
});
const ThemeContrast = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))
.check(Schema.isLessThanOrEqualTo(100))
.annotate({
title: "Contrast",
description: "A normalized contrast modifier from 0 to 100.",
examples: [24, 46, 72],
});
export const DEFAULT_THEME_RADIUS = "0.625rem";
export const DEFAULT_THEME_FONT_SIZE = "16px";
export const ThemeRadiusSchema = CssLengthValue.pipe(
Schema.withDecodingDefault(() => DEFAULT_THEME_RADIUS),
).annotate({
title: "Theme radius",
description: "Global corner radius used by the theme.",
examples: ["0.625rem", "0.5rem", "0.875rem"],
});
export type ThemeRadius = typeof ThemeRadiusSchema.Type;
export const ThemeFontSizeSchema = CssLengthValue.pipe(
Schema.withDecodingDefault(() => DEFAULT_THEME_FONT_SIZE),
).annotate({
title: "Theme font size",
description: "Base root font size used by the theme.",
examples: ["16px", "15px", "17px"],
});
export type ThemeFontSize = typeof ThemeFontSizeSchema.Type;
const OverrideTokenValue = CssColorValue.annotate({
title: "Override token",
description: "An explicit override for a derived appearance token.",
});
function makeOverrideField(title: string, description: string, examples?: ReadonlyArray<string>) {
return Schema.optionalKey(
OverrideTokenValue.annotate({
title,
description,
...(examples ? { examples } : {}),
}),
).annotateKey({ title, description });
}
export const ThemeSeedColorsSchema = Schema.Struct({
accent: HexColor.annotate({
title: "Accent",
description: "Primary brand or highlight color used for actions and focus states.",
examples: ["#0169cc", "#d95f2b", "#00827a"],
}).annotateKey({
title: "Accent",
description: "Primary brand or highlight color used for actions and focus states.",
}),
background: HexColor.annotate({
title: "Background",
description: "Primary canvas color for the app surface.",
examples: ["#ffffff", "#111111", "#f7f0e8"],
}).annotateKey({
title: "Background",
description: "Primary canvas color for the app surface.",
}),
foreground: HexColor.annotate({
title: "Foreground",
description: "Primary text color drawn over the background.",
examples: ["#0d0d0d", "#fcfcfc", "#1a120f"],
}).annotateKey({
title: "Foreground",
description: "Primary text color drawn over the background.",
}),
}).annotate({
title: "Theme seed colors",
description: "The base palette from which the rest of the appearance tokens are derived.",
});
export type ThemeSeedColors = typeof ThemeSeedColorsSchema.Type;
export const ThemeDerivedOverridesSchema = Schema.Struct({
background: makeOverrideField("Background", "Override the primary app background."),
foreground: makeOverrideField("Foreground", "Override the primary app foreground color."),
card: makeOverrideField("Card", "Override the card background."),
cardForeground: makeOverrideField("Card foreground", "Override the text color used on cards."),
popover: makeOverrideField("Popover", "Override the popover background."),
popoverForeground: makeOverrideField(
"Popover foreground",
"Override the text color used on popovers.",
),
primary: makeOverrideField("Primary", "Override the primary accent fill."),
primaryForeground: makeOverrideField(
"Primary foreground",
"Override the text color used on the primary accent fill.",
),
secondary: makeOverrideField("Secondary", "Override the secondary surface."),
secondaryForeground: makeOverrideField(
"Secondary foreground",
"Override the text color used on the secondary surface.",
),
muted: makeOverrideField("Muted", "Override the muted surface."),
mutedForeground: makeOverrideField(
"Muted foreground",
"Override the text color used for muted copy.",
),
accentSurface: makeOverrideField("Accent surface", "Override the accent-tinted surface token."),
accentForeground: makeOverrideField(
"Accent foreground",
"Override the text color used on accent-tinted surfaces.",
),
border: makeOverrideField("Border", "Override the default border color."),
input: makeOverrideField("Input", "Override the default input border or fill color."),
ring: makeOverrideField("Ring", "Override the focus ring color."),
destructive: makeOverrideField("Destructive", "Override the destructive fill color."),
destructiveForeground: makeOverrideField(
"Destructive foreground",
"Override the text color used on destructive fills.",
),
info: makeOverrideField("Info", "Override the informational fill color."),
infoForeground: makeOverrideField(
"Info foreground",
"Override the text color used on informational fills.",
),
success: makeOverrideField("Success", "Override the success fill color."),
successForeground: makeOverrideField(
"Success foreground",
"Override the text color used on success fills.",
),
warning: makeOverrideField("Warning", "Override the warning fill color."),
warningForeground: makeOverrideField(
"Warning foreground",
"Override the text color used on warning fills.",
),
diffAddition: makeOverrideField("Diff addition", "Override the addition color used in diffs.", [
"#0969da",
]),
diffDeletion: makeOverrideField("Diff deletion", "Override the deletion color used in diffs.", [
"#bc4c00",
]),
sidebar: makeOverrideField("Sidebar", "Override the sidebar surface."),
sidebarForeground: makeOverrideField(
"Sidebar foreground",
"Override the default sidebar text color.",
),
sidebarAccent: makeOverrideField("Sidebar accent", "Override hover and active sidebar surfaces."),
sidebarAccentForeground: makeOverrideField(
"Sidebar accent foreground",
"Override text color on sidebar hover and active surfaces.",
),
sidebarBorder: makeOverrideField("Sidebar border", "Override sidebar border and divider color."),
}).annotate({
title: "Theme overrides",
description: "Optional advanced overrides for exact control over derived appearance tokens.",
});
export type ThemeDerivedOverrides = typeof ThemeDerivedOverridesSchema.Type;
export const ThemeVariantSchema = Schema.Struct({
...ThemeSeedColorsSchema.fields,
uiFontFamily: FontFamilyValue.annotate({
title: "UI font family",
description: "Font family used for the application interface.",
}).annotateKey({
title: "UI font family",
description: "Font family used for the application interface.",
}),
codeFontFamily: FontFamilyValue.annotate({
title: "Code font family",
description: "Font family used for code, terminal, and monospace surfaces.",
}).annotateKey({
title: "Code font family",
description: "Font family used for code, terminal, and monospace surfaces.",
}),
contrast: ThemeContrast.annotateKey({
title: "Contrast",
description: "A normalized contrast modifier from 0 to 100.",
}),
overrides: Schema.optionalKey(ThemeDerivedOverridesSchema).annotateKey({
title: "Overrides",
description: "Optional advanced overrides for exact control over derived appearance tokens.",
}),
}).annotate({
title: "Theme variant",
description:
"A light or dark appearance variant with seed colors, fonts, and optional overrides.",
});
export type ThemeVariant = typeof ThemeVariantSchema.Type;
export const ThemeOriginSchema = Schema.Literals(["builtin", "custom"]).annotate({
title: "Theme origin",
description: "Whether a theme ships with the app or was created/imported by the user.",
examples: ["builtin", "custom"],
});
export type ThemeOrigin = typeof ThemeOriginSchema.Type;
export const ThemeModeSchema = Schema.Literals(["light", "dark"]).annotate({
title: "Theme mode",
description: "Whether this theme targets light mode or dark mode.",
examples: ["light", "dark"],
});
export type ThemeMode = typeof ThemeModeSchema.Type;
export const ThemeVersionSchema = Schema.Literal(1).annotate({
title: "Theme document version",
description: "Version of the theme document schema.",
examples: [1],
});
export type ThemeVersion = typeof ThemeVersionSchema.Type;
export const ThemeMetadataSchema = Schema.Struct({
id: TrimmedNonEmptyString.annotate({
title: "Theme id",
description: "Stable identifier used for selection and persistence.",
examples: ["t3code", "warm-editorial", "custom-midnight-ledger"],
}).annotateKey({
title: "Theme id",
description: "Stable identifier used for selection and persistence.",
}),
name: TrimmedNonEmptyString.annotate({
title: "Theme name",
description: "Human-readable theme label shown in the UI.",
examples: ["T3Code", "Warm Ledger", "Cool Current"],
}).annotateKey({
title: "Theme name",
description: "Human-readable theme label shown in the UI.",
}),
version: ThemeVersionSchema.annotateKey({
title: "Version",
description: "Version of the theme document schema.",
}),
origin: ThemeOriginSchema.annotateKey({
title: "Origin",
description: "Whether the theme is builtin or custom.",
}),
}).annotate({
title: "Theme metadata",
description: "Metadata shared by every appearance theme document.",
});
export type ThemeMetadata = typeof ThemeMetadataSchema.Type;
export const ThemeDocumentSchema = Schema.Struct({
...ThemeMetadataSchema.fields,
mode: ThemeModeSchema.annotateKey({
title: "Mode",
description: "Whether this theme targets light mode or dark mode.",
}),
radius: ThemeRadiusSchema.annotateKey({
title: "Radius",
description: "Global corner radius used across the interface.",
}),
fontSize: ThemeFontSizeSchema.annotateKey({
title: "Font size",
description: "Base root font size used across the interface.",
}),
...ThemeVariantSchema.fields,
}).annotate({
title: "Theme document",
description: "A complete single-mode appearance theme document.",
examples: [
{
id: "codex-light",
name: "Codex Light",
version: 1,
origin: "custom",
mode: "light",
radius: "0.625rem",
fontSize: "16px",
accent: "#0169cc",
background: "#ffffff",
foreground: "#0d0d0d",
uiFontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',
codeFontFamily: '"SF Mono", Menlo, monospace',
contrast: 46,
},
],
});
export type ThemeDocument = typeof ThemeDocumentSchema.Type;
+1
View File
@@ -1,4 +1,5 @@
export * from "./baseSchemas";
export * from "./appearanceTheme";
export * from "./ipc";
export * from "./terminal";
export * from "./provider";
+13 -6
View File
@@ -73,6 +73,11 @@ export type DesktopUpdateStatus =
export type DesktopRuntimeArch = "arm64" | "x64" | "other";
export type DesktopTheme = "light" | "dark" | "system";
export type DesktopAppearance = {
mode: DesktopTheme;
themeId: string;
};
export interface DesktopRuntimeInfo {
hostArch: DesktopRuntimeArch;
appArch: DesktopRuntimeArch;
@@ -110,7 +115,9 @@ 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 },
@@ -130,12 +137,12 @@ export interface NativeApi {
confirm: (message: string) => Promise<boolean>;
};
terminal: {
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>;
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>;
onEvent: (callback: (event: TerminalEvent) => void) => () => void;
};
projects: {
+1 -8
View File
@@ -35,13 +35,6 @@ 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,
@@ -56,7 +49,7 @@ export const ServerProvider = Schema.Struct({
installed: Schema.Boolean,
version: Schema.NullOr(TrimmedNonEmptyString),
status: ServerProviderState,
auth: ServerProviderAuth,
authStatus: ServerProviderAuthStatus,
checkedAt: IsoDateTime,
message: Schema.optional(TrimmedNonEmptyString),
models: Schema.Array(ServerProviderModel),
+86
View File
@@ -0,0 +1,86 @@
import { describe, expect, it } from "vitest";
import { Schema } from "effect";
import { ThemeDocumentSchema } from "./appearanceTheme";
import { DEFAULT_CLIENT_SETTINGS, ServerSettingsPatch } from "./settings";
describe("DEFAULT_CLIENT_SETTINGS", () => {
it("includes archive confirmation with a false default", () => {
expect(DEFAULT_CLIENT_SETTINGS.confirmThreadArchive).toBe(false);
});
});
describe("ThemeDocumentSchema", () => {
it("decodes a valid custom theme document", () => {
const theme = Schema.decodeUnknownSync(ThemeDocumentSchema)({
id: "custom-codex-light",
name: "Custom Codex Light",
version: 1,
origin: "custom",
mode: "light",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#ffffff",
foreground: "#0d0d0d",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 44,
overrides: {
diffAddition: "#0969da",
diffDeletion: "#bc4c00",
},
});
expect(theme.overrides?.diffAddition).toBe("#0969da");
expect(theme.mode).toBe("light");
expect(theme.radius).toBe("0.75rem");
expect(theme.fontSize).toBe("15px");
});
it("rejects invalid seed colors", () => {
expect(() =>
Schema.decodeUnknownSync(ThemeDocumentSchema)({
id: "bad-theme",
name: "Bad Theme",
version: 1,
origin: "custom",
mode: "light",
accent: "blue",
background: "#ffffff",
foreground: "#0d0d0d",
uiFontFamily: "sans-serif",
codeFontFamily: "monospace",
contrast: 40,
}),
).toThrow();
});
});
describe("ServerSettingsPatch", () => {
it("accepts customThemes updates", () => {
const patch = Schema.decodeUnknownSync(ServerSettingsPatch)({
activeLightThemeId: "custom-codex-light",
activeDarkThemeId: "t3code-dark",
customThemes: [
{
id: "custom-codex-light",
name: "Custom Codex Light",
version: 1,
origin: "custom",
mode: "light",
radius: "0.75rem",
fontSize: "15px",
accent: "#0169cc",
background: "#ffffff",
foreground: "#0d0d0d",
uiFontFamily: '"IBM Plex Sans", sans-serif',
codeFontFamily: '"IBM Plex Mono", monospace',
contrast: 38,
},
],
});
expect(patch.activeLightThemeId).toBe("custom-codex-light");
expect(patch.customThemes?.[0]?.id).toBe("custom-codex-light");
});
});
+26 -1
View File
@@ -1,6 +1,7 @@
import { Effect } from "effect";
import * as Schema from "effect/Schema";
import * as SchemaTransformation from "effect/SchemaTransformation";
import { ThemeDocumentSchema } from "./appearanceTheme";
import { TrimmedNonEmptyString, TrimmedString } from "./baseSchemas";
import {
ClaudeModelOptions,
@@ -39,6 +40,15 @@ 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_LIGHT_THEME_ID = "t3code-light";
export const DEFAULT_ACTIVE_DARK_THEME_ID = "t3code-dark";
// ── Server Settings (server-authoritative) ────────────────────
export const ThreadEnvMode = Schema.Literals(["local", "worktree"]);
@@ -83,6 +93,18 @@ export const ServerSettings = Schema.Struct({
})),
),
// Appearance
colorMode: ColorMode.pipe(
Schema.withDecodingDefault(() => "system" as const satisfies ColorMode),
),
activeLightThemeId: Schema.String.pipe(
Schema.withDecodingDefault(() => DEFAULT_ACTIVE_LIGHT_THEME_ID),
),
activeDarkThemeId: Schema.String.pipe(
Schema.withDecodingDefault(() => DEFAULT_ACTIVE_DARK_THEME_ID),
),
customThemes: Schema.Array(ThemeDocumentSchema).pipe(Schema.withDecodingDefault(() => [])),
// Provider specific settings
providers: Schema.Struct({
codex: CodexSettings.pipe(Schema.withDecodingDefault(() => ({}))),
@@ -112,7 +134,6 @@ 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([
@@ -145,6 +166,10 @@ export const ServerSettingsPatch = Schema.Struct({
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
defaultThreadEnvMode: Schema.optionalKey(ThreadEnvMode),
textGenerationModelSelection: Schema.optionalKey(ModelSelectionPatch),
colorMode: Schema.optionalKey(ColorMode),
activeLightThemeId: Schema.optionalKey(Schema.String),
activeDarkThemeId: Schema.optionalKey(Schema.String),
customThemes: Schema.optionalKey(Schema.Array(ThemeDocumentSchema)),
providers: Schema.optionalKey(
Schema.Struct({
codex: Schema.optionalKey(CodexSettingsPatch),
+2 -2
View File
@@ -26,7 +26,7 @@ const TerminalIdWithDefaultSchema = TerminalIdSchema.pipe(
export const TerminalThreadInput = Schema.Struct({
threadId: TrimmedNonEmptyStringSchema,
});
export type TerminalThreadInput = typeof TerminalThreadInput.Type;
export type TerminalThreadInput = Schema.Codec.Encoded<typeof TerminalThreadInput>;
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 = typeof TerminalCloseInput.Type;
export type TerminalCloseInput = Schema.Codec.Encoded<typeof TerminalCloseInput>;
export const TerminalSessionStatus = Schema.Literals(["starting", "running", "exited", "error"]);
export type TerminalSessionStatus = typeof TerminalSessionStatus.Type;
+12 -4
View File
@@ -4,6 +4,18 @@
"private": true,
"type": "module",
"exports": {
"./appearance/registry": {
"types": "./src/appearance/registry.ts",
"import": "./src/appearance/registry.ts"
},
"./appearance/derive": {
"types": "./src/appearance/derive.ts",
"import": "./src/appearance/derive.ts"
},
"./appearance/apply": {
"types": "./src/appearance/apply.ts",
"import": "./src/appearance/apply.ts"
},
"./model": {
"types": "./src/model.ts",
"import": "./src/model.ts"
@@ -28,10 +40,6 @@
"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"
@@ -1,96 +0,0 @@
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"]);
}),
),
);
});
@@ -1,140 +0,0 @@
/**
* 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>;
});
+45
View File
@@ -0,0 +1,45 @@
import type { ThemeDocument, ThemeVariant } from "@t3tools/contracts/appearanceTheme";
import { deriveThemeCssVariables, type ThemeCssVariableMap } from "./derive";
export interface CssVariableTarget {
setProperty(name: string, value: string): void;
removeProperty(name: string): void;
}
export function applyThemeCssVariables(
target: CssVariableTarget,
variables: ThemeCssVariableMap,
): ReadonlyArray<keyof ThemeCssVariableMap> {
const applied: Array<keyof ThemeCssVariableMap> = [];
for (const [name, value] of Object.entries(variables) as Array<
[keyof ThemeCssVariableMap, string]
>) {
target.setProperty(name, value);
applied.push(name);
}
return applied;
}
export function applyThemeVariant(
target: CssVariableTarget,
themeVariant: ThemeVariant,
): ReadonlyArray<keyof ThemeCssVariableMap> {
return applyThemeCssVariables(target, deriveThemeCssVariables(themeVariant));
}
export function applyThemeDocumentStyles(
target: CssVariableTarget,
themeDocument: ThemeDocument,
): void {
target.setProperty("--radius", themeDocument.radius);
target.setProperty("font-size", themeDocument.fontSize);
}
export function clearThemeCssVariables(
target: CssVariableTarget,
variableNames: ReadonlyArray<keyof ThemeCssVariableMap>,
): void {
for (const variableName of variableNames) {
target.removeProperty(variableName);
}
}
@@ -0,0 +1,72 @@
import { describe, expect, it } from "vitest";
import { deriveThemeCssVariables, deriveThemeTokens } from "./derive";
import { BUILTIN_THEME_DOCUMENTS } from "./registry";
const t3codeLightTheme = BUILTIN_THEME_DOCUMENTS.find((theme) => theme.id === "t3code-light")!;
const t3codeDarkTheme = BUILTIN_THEME_DOCUMENTS.find((theme) => theme.id === "t3code-dark")!;
const warmLedgerDarkTheme = BUILTIN_THEME_DOCUMENTS.find(
(theme) => theme.id === "warm-ledger-dark",
)!;
const coolCurrentLightTheme = BUILTIN_THEME_DOCUMENTS.find(
(theme) => theme.id === "cool-current-light",
)!;
describe("deriveThemeTokens", () => {
it("derives the full semantic token set from a light theme", () => {
const tokens = deriveThemeTokens(t3codeLightTheme);
expect(tokens.background).toBe("#fff");
expect(tokens.foreground).toBe("oklch(26.9% 0 0)");
expect(tokens.primary).toBe("oklch(0.488 0.217 264)");
expect(tokens.accent).toBe("color-mix(in oklab, #000 4%, transparent)");
expect(tokens.border).toBe("color-mix(in oklab, #000 8%, transparent)");
expect(tokens["sidebar-border"]).toBe("transparent");
expect(tokens["sidebar-blur"]).toBe("0px");
});
it("preserves the exact main-branch dark baseline for the default theme", () => {
const tokens = deriveThemeTokens(t3codeDarkTheme);
expect(tokens.background).toBe("color-mix(in srgb, oklch(14.5% 0 0) 95%, #fff)");
expect(tokens.foreground).toBe("oklch(97% 0 0)");
expect(tokens.primary).toBe("oklch(0.588 0.217 264)");
expect(tokens.accent).toBe("color-mix(in oklab, #fff 4%, transparent)");
expect(tokens.border).toBe("color-mix(in oklab, #fff 6%, transparent)");
expect(tokens["sidebar-border"]).toBe("transparent");
expect(tokens["sidebar-blur"]).toBe("0px");
});
it("strengthens borders and inputs at higher contrast", () => {
const lowContrast = deriveThemeTokens({
...warmLedgerDarkTheme,
contrast: 10,
});
const highContrast = deriveThemeTokens({
...warmLedgerDarkTheme,
contrast: 90,
});
expect(highContrast.border).not.toBe(lowContrast.border);
expect(highContrast.input).not.toBe(lowContrast.input);
});
it("applies overrides after derivation", () => {
const tokens = deriveThemeTokens({
...coolCurrentLightTheme,
overrides: {
border: "#222222",
diffAddition: "#123456",
},
});
expect(tokens.border).toBe("#222222");
expect(tokens["diff-addition"]).toBe("#123456");
});
it("exports css variable names in the expected format", () => {
const variables = deriveThemeCssVariables(t3codeDarkTheme);
expect(variables["--background"]).toBe("color-mix(in srgb, oklch(14.5% 0 0) 95%, #fff)");
expect(variables["--ui-font-family"]).toContain("DM Sans");
});
});
+322
View File
@@ -0,0 +1,322 @@
import type { ThemeDerivedOverrides, ThemeVariant } from "@t3tools/contracts/appearanceTheme";
export type ResolvedThemeMode = "light" | "dark";
export const THEME_TOKEN_ORDER = [
"background",
"foreground",
"card",
"card-foreground",
"popover",
"popover-foreground",
"primary",
"primary-foreground",
"secondary",
"secondary-foreground",
"muted",
"muted-foreground",
"accent",
"accent-foreground",
"border",
"input",
"ring",
"destructive",
"destructive-foreground",
"info",
"info-foreground",
"success",
"success-foreground",
"warning",
"warning-foreground",
"diff-addition",
"diff-deletion",
"sidebar",
"sidebar-foreground",
"sidebar-accent",
"sidebar-accent-foreground",
"sidebar-border",
"ui-font-family",
"code-font-family",
"sidebar-blur",
] as const;
export type ThemeTokenName = (typeof THEME_TOKEN_ORDER)[number];
export type ThemeTokenMap = Record<ThemeTokenName, string>;
export type ThemeCssVariableMap = Record<`--${ThemeTokenName}`, string>;
type Rgb = {
r: number;
g: number;
b: number;
};
function transformGammaChannel(channel: number): number {
const normalized = channel / 255;
return normalized <= 0.03928 ? normalized / 12.92 : ((normalized + 0.055) / 1.055) ** 2.4;
}
const STATUS_PALETTE = {
light: {
destructive: "#c53b2c",
info: "#0b6bcb",
success: "#0a7d5d",
warning: "#a95a00",
},
dark: {
destructive: "#ff7b72",
info: "#58a6ff",
success: "#3fb950",
warning: "#d29922",
},
} as const;
const OVERRIDE_TOKEN_MAP: Record<keyof ThemeDerivedOverrides, ThemeTokenName> = {
background: "background",
foreground: "foreground",
card: "card",
cardForeground: "card-foreground",
popover: "popover",
popoverForeground: "popover-foreground",
primary: "primary",
primaryForeground: "primary-foreground",
secondary: "secondary",
secondaryForeground: "secondary-foreground",
muted: "muted",
mutedForeground: "muted-foreground",
accentSurface: "accent",
accentForeground: "accent-foreground",
border: "border",
input: "input",
ring: "ring",
destructive: "destructive",
destructiveForeground: "destructive-foreground",
info: "info",
infoForeground: "info-foreground",
success: "success",
successForeground: "success-foreground",
warning: "warning",
warningForeground: "warning-foreground",
diffAddition: "diff-addition",
diffDeletion: "diff-deletion",
sidebar: "sidebar",
sidebarForeground: "sidebar-foreground",
sidebarAccent: "sidebar-accent",
sidebarAccentForeground: "sidebar-accent-foreground",
sidebarBorder: "sidebar-border",
};
function clamp(value: number, min: number, max: number): number {
return Math.min(max, Math.max(min, value));
}
function parseHexColor(hex: string): Rgb {
const normalized = hex.replace("#", "");
const expanded =
normalized.length === 8 ? normalized.slice(0, 6) : normalized.length === 6 ? normalized : "";
if (!expanded) {
throw new Error(`Invalid hex color: ${hex}`);
}
return {
r: Number.parseInt(expanded.slice(0, 2), 16),
g: Number.parseInt(expanded.slice(2, 4), 16),
b: Number.parseInt(expanded.slice(4, 6), 16),
};
}
function toHexColor({ r, g, b }: Rgb): string {
const channel = (value: number) =>
Math.round(clamp(value, 0, 255))
.toString(16)
.padStart(2, "0");
return `#${channel(r)}${channel(g)}${channel(b)}`;
}
function mixColors(left: string, right: string, ratio: number): string {
const from = parseHexColor(left);
const to = parseHexColor(right);
const amount = clamp(ratio, 0, 1);
return toHexColor({
r: from.r + (to.r - from.r) * amount,
g: from.g + (to.g - from.g) * amount,
b: from.b + (to.b - from.b) * amount,
});
}
function withAlpha(color: string, alpha: number): string {
const { r, g, b } = parseHexColor(color);
return `rgb(${r} ${g} ${b} / ${clamp(alpha, 0, 1).toFixed(3)})`;
}
function getRelativeLuminance(color: string): number {
const { r, g, b } = parseHexColor(color);
return (
0.2126 * transformGammaChannel(r) +
0.7152 * transformGammaChannel(g) +
0.0722 * transformGammaChannel(b)
);
}
function getContrastRatio(left: string, right: string): number {
const leftLuminance = getRelativeLuminance(left);
const rightLuminance = getRelativeLuminance(right);
const lighter = Math.max(leftLuminance, rightLuminance);
const darker = Math.min(leftLuminance, rightLuminance);
return (lighter + 0.05) / (darker + 0.05);
}
function pickReadableText(background: string, candidates: ReadonlyArray<string>): string {
return (
candidates
.toSorted(
(left, right) => getContrastRatio(background, right) - getContrastRatio(background, left),
)
.at(0) ?? candidates[0]!
);
}
function stripUndefinedKeys<T extends Record<string, string | undefined>>(
value: T,
): Record<string, string> {
const entries = Object.entries(value).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
);
return Object.fromEntries(entries);
}
export function deriveThemeTokens(themeVariant: ThemeVariant): ThemeTokenMap {
const contrastFactor = clamp(themeVariant.contrast / 100, 0, 1);
const isDark =
getRelativeLuminance(themeVariant.background) < getRelativeLuminance(themeVariant.foreground);
const card = mixColors(
themeVariant.background,
themeVariant.foreground,
isDark ? 0.02 + contrastFactor * 0.04 : 0.006 + contrastFactor * 0.016,
);
const popover = mixColors(
themeVariant.background,
themeVariant.foreground,
isDark ? 0.035 + contrastFactor * 0.05 : 0.012 + contrastFactor * 0.02,
);
const secondary = withAlpha(themeVariant.foreground, 0.03 + contrastFactor * 0.035);
const muted = withAlpha(themeVariant.foreground, 0.04 + contrastFactor * 0.03);
const accentSurface = mixColors(
themeVariant.background,
themeVariant.accent,
0.11 + contrastFactor * 0.09,
);
const border = withAlpha(themeVariant.foreground, 0.08 + contrastFactor * 0.18);
const input = withAlpha(themeVariant.foreground, 0.1 + contrastFactor * 0.2);
const mutedForeground = mixColors(
themeVariant.foreground,
themeVariant.background,
0.38 - contrastFactor * 0.14,
);
const sidebarBase = mixColors(
themeVariant.background,
themeVariant.foreground,
isDark ? 0.055 + contrastFactor * 0.055 : 0.045 + contrastFactor * 0.05,
);
const statusPalette = isDark ? STATUS_PALETTE.dark : STATUS_PALETTE.light;
const primaryForeground = pickReadableText(themeVariant.accent, [
themeVariant.foreground,
themeVariant.background,
"#0d0d0d",
"#ffffff",
]);
const accentForeground = pickReadableText(accentSurface, [
themeVariant.foreground,
themeVariant.background,
"#0d0d0d",
"#ffffff",
]);
const destructiveForeground = pickReadableText(statusPalette.destructive, [
themeVariant.background,
themeVariant.foreground,
"#ffffff",
"#0d0d0d",
]);
const infoForeground = pickReadableText(statusPalette.info, [
themeVariant.background,
themeVariant.foreground,
"#ffffff",
"#0d0d0d",
]);
const successForeground = pickReadableText(statusPalette.success, [
themeVariant.background,
themeVariant.foreground,
"#ffffff",
"#0d0d0d",
]);
const warningForeground = pickReadableText(statusPalette.warning, [
themeVariant.background,
themeVariant.foreground,
"#ffffff",
"#0d0d0d",
]);
const tokens: ThemeTokenMap = {
background: themeVariant.background,
foreground: themeVariant.foreground,
card,
"card-foreground": themeVariant.foreground,
popover,
"popover-foreground": themeVariant.foreground,
primary: themeVariant.accent,
"primary-foreground": primaryForeground,
secondary,
"secondary-foreground": themeVariant.foreground,
muted,
"muted-foreground": mutedForeground,
accent: accentSurface,
"accent-foreground": accentForeground,
border,
input,
ring: mixColors(themeVariant.accent, themeVariant.foreground, isDark ? 0.12 : 0.08),
destructive: statusPalette.destructive,
"destructive-foreground": destructiveForeground,
info: statusPalette.info,
"info-foreground": infoForeground,
success: statusPalette.success,
"success-foreground": successForeground,
warning: statusPalette.warning,
"warning-foreground": warningForeground,
"diff-addition": statusPalette.success,
"diff-deletion": statusPalette.destructive,
sidebar: sidebarBase,
"sidebar-foreground": themeVariant.foreground,
"sidebar-accent": mixColors(sidebarBase, themeVariant.accent, 0.16 + contrastFactor * 0.1),
"sidebar-accent-foreground": accentForeground,
"sidebar-border": border,
"ui-font-family": themeVariant.uiFontFamily,
"code-font-family": themeVariant.codeFontFamily,
"sidebar-blur": "0px",
};
if (themeVariant.overrides) {
for (const [overrideKey, overrideValue] of Object.entries(themeVariant.overrides) as Array<
[keyof ThemeDerivedOverrides, string | undefined]
>) {
if (!overrideValue) continue;
const tokenName = OVERRIDE_TOKEN_MAP[overrideKey];
tokens[tokenName] = overrideValue;
}
}
return tokens;
}
export function deriveThemeCssVariables(themeVariant: ThemeVariant): ThemeCssVariableMap {
const tokens = deriveThemeTokens(themeVariant);
const entries = THEME_TOKEN_ORDER.map((tokenName) => [`--${tokenName}`, tokens[tokenName]]);
return Object.fromEntries(entries) as ThemeCssVariableMap;
}
export function serializeThemeDerivedOverrides(
overrides: ThemeDerivedOverrides | undefined,
): ThemeDerivedOverrides | undefined {
if (!overrides) return undefined;
const next = stripUndefinedKeys(overrides);
return Object.keys(next).length === 0 ? undefined : (next as ThemeDerivedOverrides);
}
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import {
BUILTIN_THEME_DOCUMENTS,
DEFAULT_DARK_THEME_ID,
DEFAULT_LIGHT_THEME_ID,
duplicateThemeDocument,
resolveThemeDocument,
serializeAppearanceSnapshot,
serializeThemeDocument,
} from "./registry";
describe("appearance registry", () => {
it("resolves builtin themes before falling back to custom themes", () => {
const resolved = resolveThemeDocument(
DEFAULT_LIGHT_THEME_ID,
[duplicateThemeDocument(BUILTIN_THEME_DOCUMENTS[0]!, DEFAULT_LIGHT_THEME_ID, "Custom Clash")],
"light",
);
expect(resolved.origin).toBe("builtin");
expect(resolved.id).toBe(DEFAULT_LIGHT_THEME_ID);
});
it("duplicates builtin themes into custom theme documents", () => {
const duplicated = duplicateThemeDocument(
BUILTIN_THEME_DOCUMENTS[0]!,
"custom-copy",
"Custom Copy",
);
expect(duplicated.origin).toBe("custom");
expect(duplicated.id).toBe("custom-copy");
expect(duplicated.accent).toBe(BUILTIN_THEME_DOCUMENTS[0]!.accent);
expect(duplicated.mode).toBe(BUILTIN_THEME_DOCUMENTS[0]!.mode);
});
it("serializes themes and appearance snapshots deterministically", () => {
const theme = duplicateThemeDocument(BUILTIN_THEME_DOCUMENTS[0]!, "custom-copy", "Custom Copy");
const themeJson = serializeThemeDocument(theme);
const snapshotJson = serializeAppearanceSnapshot({
colorMode: "system",
activeLightThemeId: "custom-copy",
activeDarkThemeId: DEFAULT_DARK_THEME_ID,
customThemes: [theme],
});
expect(themeJson).toContain('"id": "custom-copy"');
expect(themeJson).toContain('"radius": "0.625rem"');
expect(themeJson).toContain('"fontSize": "16px"');
expect(snapshotJson).toContain('"activeLightThemeId":"custom-copy"');
expect(snapshotJson).toContain(`"activeDarkThemeId":"${DEFAULT_DARK_THEME_ID}"`);
});
});
Loaded 100 of 103 files, more files were not shown because too many files have changed in this diff. Show more