Compare commits

..
Author SHA1 Message Date
Cursor AgentandJulius Marminge 6d9e4a1f30 Optimize model picker search rerenders
Co-authored-by: Julius Marminge <[email protected]>
2026-06-30 16:48:44 +00:00
12 changed files with 356 additions and 386 deletions

No files matched your search

@@ -607,7 +607,6 @@ export const make = Effect.gen(function* () {
const backendExposure = yield* serverExposure.backendConfig;
const persistedSettings = yield* settings.get;
const shared = yield* sharedInputs;
yield* wslEnvironment.preWarm(persistedSettings.wslDistro);
return yield* resolveWslStartConfig({
...shared,
port: backendExposure.port,
@@ -1,9 +1,8 @@
import { assert, describe, expect, it } from "@effect/vitest";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -12,7 +11,6 @@ import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as ProcessDiagnostics from "./ProcessDiagnostics.ts";
const encoder = new TextEncoder();
const encodeJsonFixture = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
function mockHandle(result: {
readonly stdout?: string;
@@ -69,108 +67,6 @@ describe("ProcessDiagnostics", () => {
}),
);
it.effect("parses Windows CIM JSON arrays with command fallback defaults", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
encodeJsonFixture([
{
ProcessId: 10,
ParentProcessId: 1,
CommandLine: "node server.js",
Name: "node.exe",
Status: "Running",
WorkingSetSize: 1234.4,
PercentProcessorTime: 2.5,
},
{
ProcessId: 11,
ParentProcessId: 10,
CommandLine: "",
Name: "agent.exe",
},
]),
);
assert.deepEqual(rows, [
{
pid: 10,
ppid: 1,
pgid: null,
status: "Running",
cpuPercent: 2.5,
rssBytes: 1234,
elapsed: "",
command: "node server.js",
},
{
pid: 11,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "agent.exe",
},
]);
}),
);
it.effect("parses single Windows CIM JSON objects", () =>
Effect.sync(() => {
const rows = ProcessDiagnostics.parseWindowsProcessRows(
encodeJsonFixture({
ProcessId: 20,
ParentProcessId: 10,
CommandLine: "codex app-server",
WorkingSetSize: 4096,
PercentProcessorTime: 1,
}),
);
assert.deepEqual(rows, [
{
pid: 20,
ppid: 10,
pgid: null,
status: "Live",
cpuPercent: 1,
rssBytes: 4096,
elapsed: "",
command: "codex app-server",
},
]);
}),
);
it.effect("ignores malformed Windows CIM output and invalid records", () =>
Effect.sync(() => {
assert.deepEqual(ProcessDiagnostics.parseWindowsProcessRows("{not-json"), []);
assert.deepEqual(
ProcessDiagnostics.parseWindowsProcessRows(
encodeJsonFixture([
{ ProcessId: 0, ParentProcessId: 1, CommandLine: "missing-pid" },
{ ProcessId: 30, ParentProcessId: -1, CommandLine: "missing-parent" },
{ ProcessId: 31, ParentProcessId: 1, CommandLine: "" },
{ ProcessId: 32, ParentProcessId: 1, CommandLine: "valid" },
]),
),
[
{
pid: 32,
ppid: 1,
pgid: null,
status: "Live",
cpuPercent: 0,
rssBytes: 0,
elapsed: "",
command: "valid",
},
],
);
}),
);
it.effect("aggregates only descendants of the server process", () =>
Effect.sync(() => {
const diagnostics = ProcessDiagnostics.aggregateProcessDiagnostics({
@@ -121,21 +121,6 @@ const ProcessDiagnosticsError = Schema.Union([
type ProcessDiagnosticsError = typeof ProcessDiagnosticsError.Type;
const isProcessDiagnosticsError = Schema.is(ProcessDiagnosticsError);
const WindowsCimProcessRecord = Schema.Struct({
ProcessId: Schema.Number,
ParentProcessId: Schema.Number,
CommandLine: Schema.optional(Schema.NullOr(Schema.String)),
Name: Schema.optional(Schema.NullOr(Schema.String)),
WorkingSetSize: Schema.optional(Schema.NullOr(Schema.Number)),
PercentProcessorTime: Schema.optional(Schema.NullOr(Schema.Number)),
Status: Schema.optional(Schema.NullOr(Schema.String)),
});
type WindowsCimProcessRecord = typeof WindowsCimProcessRecord.Type;
const decodeWindowsCimProcessRecord = Schema.decodeUnknownOption(WindowsCimProcessRecord);
const decodeWindowsCimProcessJson = Schema.decodeUnknownOption(
Schema.fromJsonString(Schema.Unknown),
);
function parsePositiveInt(value: string): number | null {
const parsed = Number.parseInt(value, 10);
return Number.isInteger(parsed) && parsed > 0 ? parsed : null;
@@ -216,57 +201,51 @@ export function parsePosixProcessRows(output: string): ReadonlyArray<ProcessRow>
return rows;
}
function nonEmptyStringOption(value: string | null | undefined): Option.Option<string> {
return typeof value === "string" && value.trim().length > 0 ? Option.some(value) : Option.none();
function normalizeWindowsProcessRow(value: unknown): ProcessRow | null {
if (typeof value !== "object" || value === null) return null;
const record = value as Record<string, unknown>;
const pid = typeof record.ProcessId === "number" ? record.ProcessId : null;
const ppid = typeof record.ParentProcessId === "number" ? record.ParentProcessId : null;
const commandLine =
typeof record.CommandLine === "string" && record.CommandLine.trim().length > 0
? record.CommandLine
: typeof record.Name === "string"
? record.Name
: null;
const workingSet =
typeof record.WorkingSetSize === "number" && Number.isFinite(record.WorkingSetSize)
? Math.max(0, Math.round(record.WorkingSetSize))
: 0;
const cpuPercent =
typeof record.PercentProcessorTime === "number" && Number.isFinite(record.PercentProcessorTime)
? Math.max(0, record.PercentProcessorTime)
: 0;
if (!pid || pid <= 0 || ppid === null || ppid < 0 || !commandLine) return null;
return {
pid,
ppid,
pgid: null,
status: typeof record.Status === "string" && record.Status.length > 0 ? record.Status : "Live",
cpuPercent,
rssBytes: workingSet,
elapsed: "",
command: commandLine,
};
}
function optionalNonNegativeNumber(value: number | null | undefined): number {
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, value) : 0;
}
function normalizeWindowsProcessRow(value: unknown): Option.Option<ProcessRow> {
return Option.flatMap(decodeWindowsCimProcessRecord(value), (record) => {
if (
!Number.isInteger(record.ProcessId) ||
record.ProcessId <= 0 ||
!Number.isInteger(record.ParentProcessId) ||
record.ParentProcessId < 0
) {
return Option.none();
}
return Option.map(
nonEmptyStringOption(record.CommandLine).pipe(
Option.orElse(() => nonEmptyStringOption(record.Name)),
),
(command) => ({
pid: record.ProcessId,
ppid: record.ParentProcessId,
pgid: null,
status: Option.getOrElse(nonEmptyStringOption(record.Status), () => "Live"),
cpuPercent: optionalNonNegativeNumber(record.PercentProcessorTime),
rssBytes: Math.round(optionalNonNegativeNumber(record.WorkingSetSize)),
elapsed: "",
command,
}),
);
});
}
export function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
function parseWindowsProcessRows(output: string): ReadonlyArray<ProcessRow> {
if (output.trim().length === 0) return [];
return Option.match(decodeWindowsCimProcessJson(output), {
onNone: () => [],
onSome: (parsed) => {
const rows: ProcessRow[] = [];
const records = Array.isArray(parsed) ? parsed : [parsed];
for (const record of records) {
const row = normalizeWindowsProcessRow(record);
if (Option.isSome(row)) rows.push(row.value);
}
return rows;
},
});
try {
const parsed = JSON.parse(output) as unknown;
const records = Array.isArray(parsed) ? parsed : [parsed];
return records.flatMap((record) => {
const row = normalizeWindowsProcessRow(record);
return row ? [row] : [];
});
} catch {
return [];
}
}
export function buildDescendantEntries(
@@ -193,36 +193,6 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
],
}),
},
{
slug: "claude-sonnet-5",
name: "Claude Sonnet 5",
isCustom: false,
capabilities: createModelCapabilities({
optionDescriptors: [
buildSelectOptionDescriptor({
id: "effort",
label: "Reasoning",
options: [
{ value: "low", label: "Low" },
{ value: "medium", label: "Medium" },
{ value: "high", label: "High", isDefault: true },
{ value: "xhigh", label: "Extra High" },
{ value: "max", label: "Max" },
{ value: "ultrathink", label: "Ultrathink" },
],
promptInjectedValues: ["ultrathink"],
}),
buildSelectOptionDescriptor({
id: "contextWindow",
label: "Context Window",
options: [
{ value: "200k", label: "200k", isDefault: true },
{ value: "1m", label: "1M" },
],
}),
],
}),
},
{
slug: "claude-sonnet-4-6",
name: "Claude Sonnet 4.6",
@@ -352,12 +322,7 @@ export function normalizeClaudeCliEffort(
if (effort === "ultracode") {
return "xhigh";
}
if (
effort === "xhigh" &&
model !== "claude-fable-5" &&
model !== "claude-opus-4-8" &&
model !== "claude-sonnet-5"
) {
if (effort === "xhigh" && model !== "claude-fable-5" && model !== "claude-opus-4-8") {
return "max";
}
if (effort === "max" && model === "claude-sonnet-4-6") {
@@ -185,15 +185,8 @@ it.layer(TestLayer, { excludeTestServices: true })("WorkspaceFileSystemLive", (i
operationPath: resolvedPath,
operation: "realpath-target",
});
expect(error.cause).toMatchObject({
_tag: "PlatformError",
reason: {
_tag: "NotFound",
module: "FileSystem",
method: "realPath",
pathOrDescriptor: resolvedPath,
},
});
expect(error.cause).toBeInstanceOf(Error);
expect((error.cause as NodeJS.ErrnoException).code).toBe("ENOENT");
}),
);
});
+127 -90
View File
@@ -1,3 +1,4 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* WorkspaceFileSystem - Effect service contract for workspace file mutations.
*
@@ -6,6 +7,8 @@
*
* @module WorkspaceFileSystem
*/
import * as NodeFSP from "node:fs/promises";
import type {
ProjectReadFileInput,
ProjectReadFileResult,
@@ -16,7 +19,6 @@ import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -24,7 +26,6 @@ import * as WorkspaceEntries from "./WorkspaceEntries.ts";
import * as WorkspacePaths from "./WorkspacePaths.ts";
const PROJECT_READ_FILE_MAX_BYTES = 1024 * 1024;
const PROJECT_READ_FILE_MAX_SIZE = FileSystem.Size(PROJECT_READ_FILE_MAX_BYTES);
export class WorkspaceFileSystemOperationError extends Schema.TaggedErrorClass<WorkspaceFileSystemOperationError>()(
"WorkspaceFileSystemOperationError",
@@ -131,23 +132,6 @@ export const make = Effect.gen(function* () {
const workspacePaths = yield* WorkspacePaths.WorkspacePaths;
const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;
const operationError =
(
input: ProjectReadFileInput | ProjectWriteFileInput,
resolvedPath: string,
operationPath: string,
operation: WorkspaceFileSystemOperationError["operation"],
) =>
(cause: unknown) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath,
operationPath,
operation,
cause,
});
const readFile: WorkspaceFileSystem["Service"]["readFile"] = Effect.fn(
"WorkspaceFileSystem.readFile",
)(function* (input) {
@@ -156,20 +140,30 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
const realWorkspaceRoot = yield* fileSystem
.realPath(input.cwd)
.pipe(
Effect.mapError(
operationError(input, target.absolutePath, input.cwd, "realpath-workspace-root"),
),
);
const realTargetPath = yield* fileSystem
.realPath(target.absolutePath)
.pipe(
Effect.mapError(
operationError(input, target.absolutePath, target.absolutePath, "realpath-target"),
),
);
const realWorkspaceRoot = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(input.cwd),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: input.cwd,
operation: "realpath-workspace-root",
cause,
}),
});
const realTargetPath = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(target.absolutePath),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "realpath-target",
cause,
}),
});
const relativeRealPath = path.relative(realWorkspaceRoot, realTargetPath);
if (
relativeRealPath.startsWith(`..${path.sep}`) ||
@@ -184,48 +178,84 @@ export const make = Effect.gen(function* () {
});
}
return yield* Effect.scoped(
Effect.gen(function* () {
const file = yield* fileSystem
.open(realTargetPath, { flag: "r" })
.pipe(Effect.mapError(operationError(input, realTargetPath, realTargetPath, "open")));
const stat = yield* file.stat.pipe(
Effect.mapError(operationError(input, realTargetPath, realTargetPath, "stat")),
);
if (stat.type !== "File") {
return yield* new WorkspacePathNotFileError({
return yield* Effect.acquireUseRelease(
Effect.tryPromise({
try: () => NodeFSP.open(realTargetPath, "r"),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead =
stat.size > PROJECT_READ_FILE_MAX_SIZE ? PROJECT_READ_FILE_MAX_BYTES : Number(stat.size);
const fileBytes =
bytesToRead === 0
? new Uint8Array()
: yield* file
.readAlloc(bytesToRead)
.pipe(
Effect.map(Option.getOrElse(() => new Uint8Array())),
Effect.mapError(operationError(input, realTargetPath, realTargetPath, "read")),
);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: Number(stat.size),
truncated: stat.size > PROJECT_READ_FILE_MAX_SIZE,
};
operationPath: realTargetPath,
operation: "open",
cause,
}),
}),
(handle) =>
Effect.gen(function* () {
const stat = yield* Effect.tryPromise({
try: () => handle.stat(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "stat",
cause,
}),
});
if (!stat.isFile()) {
return yield* new WorkspacePathNotFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
const bytesToRead = Math.min(stat.size, PROJECT_READ_FILE_MAX_BYTES);
const buffer = Buffer.alloc(bytesToRead);
const { bytesRead } = yield* Effect.tryPromise({
try: () => handle.read(buffer, 0, bytesToRead, 0),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "read",
cause,
}),
});
const fileBytes = buffer.subarray(0, bytesRead);
if (fileBytes.includes(0)) {
return yield* new WorkspaceBinaryFileError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
});
}
return {
relativePath: target.relativePath,
contents: new TextDecoder("utf-8").decode(fileBytes),
byteLength: stat.size,
truncated: stat.size > PROJECT_READ_FILE_MAX_BYTES,
};
}),
(handle) =>
Effect.tryPromise({
try: () => handle.close(),
catch: (cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: realTargetPath,
operationPath: realTargetPath,
operation: "close",
cause,
}),
}),
);
});
@@ -237,25 +267,32 @@ export const make = Effect.gen(function* () {
relativePath: input.relativePath,
});
yield* fileSystem
.makeDirectory(path.dirname(target.absolutePath), { recursive: true })
.pipe(
Effect.mapError(
operationError(
input,
target.absolutePath,
path.dirname(target.absolutePath),
"make-directory",
),
),
);
yield* fileSystem
.writeFileString(target.absolutePath, input.contents)
.pipe(
Effect.mapError(
operationError(input, target.absolutePath, target.absolutePath, "write-file"),
),
);
yield* fileSystem.makeDirectory(path.dirname(target.absolutePath), { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: path.dirname(target.absolutePath),
operation: "make-directory",
cause,
}),
),
);
yield* fileSystem.writeFileString(target.absolutePath, input.contents).pipe(
Effect.mapError(
(cause) =>
new WorkspaceFileSystemOperationError({
workspaceRoot: input.cwd,
relativePath: input.relativePath,
resolvedPath: target.absolutePath,
operationPath: target.absolutePath,
operation: "write-file",
cause,
}),
),
);
yield* workspaceEntries.refresh(input.cwd);
return { relativePath: target.relativePath };
});
@@ -331,19 +331,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
},
[props],
);
const handleTabMouseDown = useCallback((event: ReactMouseEvent) => {
if (event.button !== 1) return;
event.preventDefault();
}, []);
const handleTabAuxClick = useCallback(
(event: ReactMouseEvent, surface: RightPanelSurface) => {
if (event.button !== 1) return;
event.preventDefault();
event.stopPropagation();
props.onCloseSurface(surface);
},
[props],
);
useEffect(() => {
const activeTab = tabListRef.current?.querySelector<HTMLElement>("[data-active-tab='true']");
@@ -380,8 +367,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<div
key={surface.id}
data-active-tab={active}
onMouseDown={handleTabMouseDown}
onAuxClick={(event) => handleTabAuxClick(event, surface)}
onContextMenu={(event) => void handleTabContextMenu(event, surface)}
className={cn(
"group flex h-7 min-w-25 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-sm",
@@ -5,7 +5,18 @@ import {
} from "@t3tools/contracts";
import { resolveSelectableModel } from "@t3tools/shared/model";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { memo, useMemo, useState, useCallback, useEffect, useLayoutEffect, useRef } from "react";
import {
type ChangeEvent,
type KeyboardEvent as ReactKeyboardEvent,
memo,
useMemo,
useState,
useCallback,
useEffect,
useLayoutEffect,
useRef,
type RefObject,
} from "react";
import { SearchIcon } from "lucide-react";
import { ModelListRow } from "./ModelListRow";
import { ModelPickerSidebar } from "./ModelPickerSidebar";
@@ -43,6 +54,8 @@ type ModelPickerItem = {
const EMPTY_MODEL_JUMP_LABELS = new Map<string, string>();
const normalizeModelSearchQuery = (value: string): string => value.trim();
// Split a `${instanceId}:${slug}` combobox key back into its pieces. Slugs
// can contain colons (e.g. some vendor model ids), so we only split on the
// first colon — anything after that is the slug.
@@ -57,6 +70,70 @@ function splitInstanceModelKey(key: string): { instanceId: ProviderInstanceId; s
};
}
const ModelPickerSearchInput = memo(function ModelPickerSearchInput(props: {
inputRef: RefObject<HTMLInputElement | null>;
onSearchQueryChange: (query: string) => void;
onRequestClose?: () => void;
onSubmitHighlightedModel: () => boolean;
}) {
const { inputRef, onRequestClose, onSearchQueryChange, onSubmitHighlightedModel } = props;
const [inputValue, setInputValue] = useState("");
const lastNormalizedQueryRef = useRef("");
const handleChange = useCallback(
(event: ChangeEvent<HTMLInputElement>) => {
const nextValue = event.target.value;
const nextNormalizedQuery = normalizeModelSearchQuery(nextValue);
setInputValue(nextValue);
if (lastNormalizedQueryRef.current === nextNormalizedQuery) {
return;
}
lastNormalizedQueryRef.current = nextNormalizedQuery;
onSearchQueryChange(nextNormalizedQuery);
},
[onSearchQueryChange],
);
const handleKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLInputElement>) => {
if (event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
onRequestClose?.();
return;
}
if (event.key === "Enter" && onSubmitHighlightedModel()) {
(event as typeof event & { preventBaseUIHandler?: () => void }).preventBaseUIHandler?.();
event.preventDefault();
event.stopPropagation();
return;
}
event.stopPropagation();
},
[onRequestClose, onSubmitHighlightedModel],
);
return (
<ComboboxInput
ref={inputRef}
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
inputClassName="rounded-none bg-transparent text-sm"
placeholder="Search models..."
showTrigger={false}
startAddon={
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
}
value={inputValue}
onChange={handleChange}
onKeyDown={handleKeyDown}
onMouseDown={(event) => event.stopPropagation()}
onTouchStart={(event) => event.stopPropagation()}
size="sm"
unstyled
/>
);
});
export const ModelPickerContent = memo(function ModelPickerContent(props: {
/** The instance currently selected in the composer (combobox "value"). */
activeInstanceId: ProviderInstanceId;
@@ -518,6 +595,15 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
};
}, [filteredModelKeys, updateModelListScrollFades]);
const submitHighlightedModel = useCallback(() => {
if (!highlightedModelKeyRef.current) {
return false;
}
const { instanceId, slug } = splitInstanceModelKey(highlightedModelKeyRef.current);
handleModelSelect(slug, instanceId);
return true;
}, [handleModelSelect]);
return (
<TooltipProvider delay={0}>
<div
@@ -577,42 +663,11 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: {
{/* Search bar */}
<div className="px-4 pt-2.5">
<div className="-translate-y-px border-b border-border/70 pb-2.5 transition-colors focus-within:border-ring">
<ComboboxInput
ref={searchInputRef}
className="[&_input]:h-6.5 [&_input]:font-sans [&_input]:leading-6.5"
inputClassName="rounded-none bg-transparent text-sm"
placeholder="Search models..."
showTrigger={false}
startAddon={
<SearchIcon className="-translate-x-0.5 size-4 shrink-0 text-muted-foreground/55" />
}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
props.onRequestClose?.();
return;
}
if (e.key === "Enter" && highlightedModelKeyRef.current) {
(
e as typeof e & { preventBaseUIHandler?: () => void }
).preventBaseUIHandler?.();
e.preventDefault();
e.stopPropagation();
const { instanceId, slug } = splitInstanceModelKey(
highlightedModelKeyRef.current,
);
handleModelSelect(slug, instanceId);
return;
}
e.stopPropagation();
}}
onMouseDown={(e) => e.stopPropagation()}
onTouchStart={(e) => e.stopPropagation()}
size="sm"
unstyled
<ModelPickerSearchInput
inputRef={searchInputRef}
onSearchQueryChange={setSearchQuery}
onSubmitHighlightedModel={submitHighlightedModel}
{...(props.onRequestClose ? { onRequestClose: props.onRequestClose } : {})}
/>
</div>
</div>
@@ -32,7 +32,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
*/
const CUSTOM_MODEL_PLACEHOLDER_BY_KIND: Partial<Record<ProviderDriverKind, string>> = {
[ProviderDriverKind.make("codex")]: "gpt-6.7-codex-ultra-preview",
[ProviderDriverKind.make("claudeAgent")]: "claude-sonnet-5",
[ProviderDriverKind.make("claudeAgent")]: "claude-sonnet-5-0",
[ProviderDriverKind.make("cursor")]: "claude-sonnet-4-6",
[ProviderDriverKind.make("opencode")]: "openai/gpt-5",
};
-23
View File
@@ -812,35 +812,12 @@ label:has(> select#reasoning-effort) select {
#ec4899 90%,
#ff6b6b 100%
);
position: relative;
background: transparent;
}
.ultrathink-frame::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
padding: 2px;
background-image: var(--ultrathink-spectrum);
background-size: 220% 220%;
pointer-events: none;
filter: saturate(0.82) brightness(0.92);
-webkit-mask:
linear-gradient(#000 0 0) content-box,
linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask:
linear-gradient(#000 0 0) content-box,
linear-gradient(#000 0 0);
mask-composite: exclude;
animation: ultrathink-rainbow 10s linear infinite;
}
.ultrathink-frame > * {
position: relative;
}
.ultrathink-chroma {
animation: ultrathink-chroma-shift 10s linear infinite;
}
+2 -5
View File
@@ -138,7 +138,7 @@ export const DEFAULT_GIT_TEXT_GENERATION_MODEL = "gpt-5.4-mini";
export const DEFAULT_MODEL_BY_PROVIDER: Partial<Record<ProviderDriverKind, string>> = {
[CODEX_DRIVER_KIND]: DEFAULT_MODEL,
[CLAUDE_DRIVER_KIND]: "claude-sonnet-5",
[CLAUDE_DRIVER_KIND]: "claude-sonnet-4-6",
[CURSOR_DRIVER_KIND]: "auto",
[GROK_DRIVER_KIND]: "grok-build",
[OPENCODE_DRIVER_KIND]: "openai/gpt-5",
@@ -174,10 +174,7 @@ export const MODEL_SLUG_ALIASES_BY_PROVIDER: Partial<
"opus-4.6": "claude-opus-4-6",
"claude-opus-4.6": "claude-opus-4-6",
"claude-opus-4-6-20251117": "claude-opus-4-6",
sonnet: "claude-sonnet-5",
"sonnet-5": "claude-sonnet-5",
"claude-sonnet-5.0": "claude-sonnet-5",
"claude-sonnet-5-0": "claude-sonnet-5",
sonnet: "claude-sonnet-4-6",
"sonnet-4.6": "claude-sonnet-4-6",
"claude-sonnet-4.6": "claude-sonnet-4-6",
"claude-sonnet-4-6-20251117": "claude-sonnet-4-6",
+88 -1
View File
@@ -1,7 +1,13 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ModelCapabilities } from "@t3tools/contracts";
import {
DEFAULT_MODEL,
ProviderDriverKind,
ProviderInstanceId,
type ModelCapabilities,
} from "@t3tools/contracts";
import {
applyClaudePromptEffortPrefix,
buildProviderOptionSelectionsFromDescriptors,
createModelCapabilities,
createModelSelection,
@@ -10,6 +16,11 @@ import {
getProviderOptionDescriptors,
getProviderOptionBooleanSelectionValue,
getProviderOptionStringSelectionValue,
isClaudeUltrathinkPrompt,
normalizeModelSlug,
resolveModelSlugForProvider,
resolveSelectableModel,
trimOrNull,
} from "./model.ts";
const codexCaps: ModelCapabilities = createModelCapabilities({
@@ -59,6 +70,82 @@ const claudeCaps: ModelCapabilities = createModelCapabilities({
],
});
describe("normalizeModelSlug", () => {
it("maps known aliases to canonical slugs", () => {
const claude = ProviderDriverKind.make("claudeAgent");
expect(normalizeModelSlug("gpt-5-codex")).toBe("gpt-5.4");
expect(normalizeModelSlug("5.3")).toBe("gpt-5.3-codex");
expect(normalizeModelSlug("sonnet", claude)).toBe("claude-sonnet-4-6");
});
it("returns null for empty or missing values", () => {
expect(normalizeModelSlug("")).toBeNull();
expect(normalizeModelSlug(" ")).toBeNull();
expect(normalizeModelSlug(null)).toBeNull();
expect(normalizeModelSlug(undefined)).toBeNull();
});
});
describe("resolveModelSlugForProvider", () => {
it("returns defaults when the model is missing", () => {
expect(resolveModelSlugForProvider(ProviderDriverKind.make("codex"), undefined)).toBe(
DEFAULT_MODEL,
);
expect(resolveModelSlugForProvider(ProviderDriverKind.make("ollama"), undefined)).toBe(
DEFAULT_MODEL,
);
expect(resolveModelSlugForProvider(ProviderDriverKind.make("grok"), undefined)).toBe(
"grok-build",
);
});
it("preserves normalized unknown models", () => {
expect(
resolveModelSlugForProvider(ProviderDriverKind.make("codex"), "custom/internal-model"),
).toBe("custom/internal-model");
});
});
describe("resolveSelectableModel", () => {
it("resolves exact slugs, labels, and aliases", () => {
const options = [
{ slug: "gpt-5.3-codex", name: "GPT-5.3 Codex" },
{ slug: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
];
expect(resolveSelectableModel(ProviderDriverKind.make("codex"), "gpt-5.3-codex", options)).toBe(
"gpt-5.3-codex",
);
expect(resolveSelectableModel(ProviderDriverKind.make("codex"), "gpt-5.3 codex", options)).toBe(
"gpt-5.3-codex",
);
expect(resolveSelectableModel(ProviderDriverKind.make("claudeAgent"), "sonnet", options)).toBe(
"claude-sonnet-4-6",
);
});
});
describe("misc helpers", () => {
it("detects ultrathink prompts", () => {
expect(isClaudeUltrathinkPrompt("Please ultrathink about this")).toBe(true);
expect(isClaudeUltrathinkPrompt("Ultrathink:\nInvestigate")).toBe(true);
expect(isClaudeUltrathinkPrompt("Investigate")).toBe(false);
});
it("prefixes ultrathink prompts once", () => {
expect(applyClaudePromptEffortPrefix("Investigate", "ultrathink")).toBe(
"Ultrathink:\nInvestigate",
);
expect(applyClaudePromptEffortPrefix("Ultrathink:\nInvestigate", "ultrathink")).toBe(
"Ultrathink:\nInvestigate",
);
});
it("trims strings to null", () => {
expect(trimOrNull(" hi ")).toBe("hi");
expect(trimOrNull(" ")).toBeNull();
});
});
describe("descriptor helpers", () => {
it("applies selection values to capability descriptors", () => {
expect(