Compare commits

..
Author SHA1 Message Date
Ben Davis 4db64afccc Use Codex defaults for custom model capabilities
- Apply standard Codex capabilities to custom Codex models
- Keep provider and composer UI behavior consistent for custom models
- Add coverage for custom Codex model defaults
2026-04-06 14:24:05 -07:00
sonderandJulius Marminge c6f57a1064 Rename "Chat" to "Build" in interaction mode toggle (#1769)
Co-authored-by: Julius Marminge <[email protected]>
2026-04-06 17:29:58 +00:00
legs 340dbbb36e fix(web): unwrap windows shell command wrappers (#1719) 2026-04-06 17:19:27 +00:00
Julius Marmingeandcodex 53a552e80d Stream git status updates over WebSocket (#1763)
Co-authored-by: codex <[email protected]>
2026-04-06 09:26:29 -07:00
Julius Marminge cf2c628bc0 Use active worktree path for workspace saves (#1762) 2026-04-05 11:22:24 -07:00
Julius Marminge e0874b651d Raise slow RPC ack warning threshold to 15s (#1760) 2026-04-05 16:53:53 +00:00
15 changed files with 503 additions and 54 deletions

No files matched your search

@@ -32,6 +32,7 @@ import {
spawnAndCollect,
type CommandResult,
} from "../providerSnapshot";
import { DEFAULT_CODEX_MODEL_CAPABILITIES } from "@t3tools/shared/model";
import { makeManagedServerProvider } from "../makeManagedServerProvider";
import {
formatCodexCliUpgradeMessage,
@@ -159,13 +160,8 @@ const BUILT_IN_MODELS: ReadonlyArray<ServerProviderModel> = [
export function getCodexModelCapabilities(model: string | null | undefined): ModelCapabilities {
const slug = model?.trim();
return (
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ?? {
reasoningEffortLevels: [],
supportsFastMode: false,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
}
BUILT_IN_MODELS.find((candidate) => candidate.slug === slug)?.capabilities ??
DEFAULT_CODEX_MODEL_CAPABILITIES
);
}
@@ -339,7 +335,12 @@ export const checkCodexProviderStatus = Effect.fn("checkCodexProviderStatus")(fu
Effect.map((settings) => settings.providers.codex),
);
const checkedAt = new Date().toISOString();
const models = providerModelsFromSettings(BUILT_IN_MODELS, PROVIDER, codexSettings.customModels);
const models = providerModelsFromSettings(
BUILT_IN_MODELS,
PROVIDER,
codexSettings.customModels,
DEFAULT_CODEX_MODEL_CAPABILITIES,
);
if (!codexSettings.enabled) {
return buildServerProvider({
@@ -220,6 +220,41 @@ it.layer(Layer.mergeAll(NodeServices.layer, ServerSettingsService.layerTest()))(
),
);
it.effect("adds standard codex capabilities to custom codex models", () =>
Effect.gen(function* () {
yield* withTempCodexHome();
const serverSettingsLayer = ServerSettingsService.layerTest({
providers: {
codex: {
customModels: ["custom-codex-model"],
},
},
});
const status = yield* checkCodexProviderStatus().pipe(
Effect.provide(serverSettingsLayer),
);
const customModel = status.models.find((model) => model.slug === "custom-codex-model");
assert.ok(customModel);
assert.strictEqual(customModel.isCustom, true);
assert.deepStrictEqual(
customModel.capabilities?.reasoningEffortLevels.map((level) => level.value),
["xhigh", "high", "medium", "low"],
);
assert.strictEqual(customModel.capabilities?.supportsFastMode, 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();
+3 -1
View File
@@ -1,4 +1,5 @@
import type {
ModelCapabilities,
ServerProvider,
ServerProviderAuth,
ServerProviderModel,
@@ -102,6 +103,7 @@ export function providerModelsFromSettings(
builtInModels: ReadonlyArray<ServerProviderModel>,
provider: ServerProvider["provider"],
customModels: ReadonlyArray<string>,
defaultCustomCapabilities: ModelCapabilities | null = null,
): ReadonlyArray<ServerProviderModel> {
const resolvedBuiltInModels = [...builtInModels];
const seen = new Set(resolvedBuiltInModels.map((model) => model.slug));
@@ -117,7 +119,7 @@ export function providerModelsFromSettings(
slug: normalized,
name: normalized,
isCustom: true,
capabilities: null,
capabilities: defaultCustomCapabilities,
});
}
@@ -106,7 +106,6 @@ export function BranchToolbarBranchSelector({
gitBranchSearchInfiniteQueryOptions({
cwd: branchCwd,
query: deferredTrimmedBranchQuery,
enabled: isBranchMenuOpen,
}),
);
const branches = useMemo(
+54 -5
View File
@@ -874,7 +874,7 @@ async function expectComposerActionsContained(): Promise<void> {
}
async function waitForInteractionModeButton(
expectedLabel: "Chat" | "Plan",
expectedLabel: "Build" | "Plan",
): Promise<HTMLButtonElement> {
return waitForElement(
() =>
@@ -2111,7 +2111,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
});
try {
const initialModeButton = await waitForInteractionModeButton("Chat");
const initialModeButton = await waitForInteractionModeButton("Build");
expect(initialModeButton.title).toContain("enter plan mode");
window.dispatchEvent(
@@ -2124,7 +2124,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
);
await waitForLayout();
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
const composerEditor = await waitForComposerEditor();
composerEditor.focus();
@@ -2140,7 +2140,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Plan")).title).toContain(
"return to normal chat mode",
"return to normal build mode",
);
},
{ timeout: 8_000, interval: 16 },
@@ -2157,7 +2157,7 @@ describe("ChatView timeline estimator parity (full app)", () => {
await vi.waitFor(
async () => {
expect((await waitForInteractionModeButton("Chat")).title).toContain("enter plan mode");
expect((await waitForInteractionModeButton("Build")).title).toContain("enter plan mode");
},
{ timeout: 8_000, interval: 16 },
);
@@ -2833,6 +2833,55 @@ describe("ChatView timeline estimator parity (full app)", () => {
}
});
it("uses the active worktree path when saving a proposed plan to the workspace", async () => {
const snapshot = createSnapshotWithLongProposedPlan();
const threads = snapshot.threads.slice();
const targetThreadIndex = threads.findIndex((thread) => thread.id === THREAD_ID);
const targetThread = targetThreadIndex >= 0 ? threads[targetThreadIndex] : undefined;
if (targetThread) {
threads[targetThreadIndex] = {
...targetThread,
worktreePath: "/repo/worktrees/plan-thread",
};
}
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: {
...snapshot,
threads,
},
});
try {
const planActionsButton = await waitForElement(
() => document.querySelector<HTMLButtonElement>('button[aria-label="Plan actions"]'),
"Unable to find proposed plan actions button.",
);
planActionsButton.click();
const saveToWorkspaceItem = await waitForElement(
() =>
(Array.from(document.querySelectorAll('[data-slot="menu-item"]')).find(
(item) => item.textContent?.trim() === "Save to workspace",
) ?? null) as HTMLElement | null,
'Unable to find "Save to workspace" menu item.',
);
saveToWorkspaceItem.click();
await vi.waitFor(
() => {
expect(document.body.textContent).toContain(
"Enter a path relative to /repo/worktrees/plan-thread.",
);
},
{ timeout: 8_000, interval: 16 },
);
} finally {
await mounted.cleanup();
}
});
it("keeps pending-question footer actions inside the composer after a real resize", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
+7 -6
View File
@@ -1476,7 +1476,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
type: "slash-command",
command: "default",
label: "/default",
description: "Switch this thread back to normal chat mode",
description: "Switch this thread back to normal build mode",
},
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
const query = composerTrigger.query.trim().toLowerCase();
@@ -1526,6 +1526,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
);
const activeProjectCwd = activeProject?.cwd ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
const activeTerminalLaunchContext =
terminalLaunchContext?.threadId === activeThreadId
? terminalLaunchContext
@@ -4004,7 +4005,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
markdownCwd={gitCwd ?? undefined}
resolvedTheme={resolvedTheme}
timestampFormat={timestampFormat}
workspaceRoot={activeProject?.cwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
/>
</div>
@@ -4028,7 +4029,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
<form
ref={composerFormRef}
onSubmit={onSend}
className="mx-auto w-full min-w-0 max-w-[52rem]"
className="mx-auto w-full min-w-0 max-w-208"
data-chat-composer-form="true"
>
<div
@@ -4283,13 +4284,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
onClick={toggleInteractionMode}
title={
interactionMode === "plan"
? "Plan mode — click to return to normal chat mode"
? "Plan mode — click to return to normal build mode"
: "Default mode — click to enter plan mode"
}
>
<BotIcon />
<span className="sr-only sm:not-sr-only">
{interactionMode === "plan" ? "Plan" : "Chat"}
{interactionMode === "plan" ? "Plan" : "Build"}
</span>
</Button>
@@ -4438,7 +4439,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
activePlan={activePlan}
activeProposedPlan={sidebarProposedPlan}
markdownCwd={gitCwd ?? undefined}
workspaceRoot={activeProject?.cwd ?? undefined}
workspaceRoot={activeWorkspaceRoot}
timestampFormat={timestampFormat}
onClose={() => {
setPlanSidebarOpen(false);
@@ -48,6 +48,7 @@ import {
type MessagesTimelineRow,
} from "./MessagesTimeline.logic";
import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import {
deriveDisplayedUserMessageState,
type ParsedTerminalContextEntry,
@@ -792,6 +793,16 @@ function workEntryPreview(
: `${firstPath} +${workEntry.changedFiles!.length - 1} more`;
}
function workEntryRawCommand(
workEntry: Pick<TimelineWorkEntry, "command" | "rawCommand">,
): string | null {
const rawCommand = workEntry.rawCommand?.trim();
if (!rawCommand || !workEntry.command) {
return null;
}
return rawCommand === workEntry.command.trim() ? null : rawCommand;
}
function workEntryIcon(workEntry: TimelineWorkEntry): LucideIcon {
if (workEntry.requestKind === "command") return TerminalIcon;
if (workEntry.requestKind === "file-read") return EyeIcon;
@@ -840,6 +851,7 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
const EntryIcon = workEntryIcon(workEntry);
const heading = toolWorkEntryHeading(workEntry);
const preview = workEntryPreview(workEntry);
const rawCommand = workEntryRawCommand(workEntry);
const displayText = preview ? `${heading} - ${preview}` : heading;
const hasChangedFiles = (workEntry.changedFiles?.length ?? 0) > 0;
const previewIsChangedFiles = hasChangedFiles && !workEntry.command && !workEntry.detail;
@@ -853,19 +865,46 @@ const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
<EntryIcon className="size-3" />
</span>
<div className="min-w-0 flex-1 overflow-hidden">
<p
className={cn(
"truncate text-[11px] leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
title={displayText}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview && <span className="text-muted-foreground/55"> - {preview}</span>}
</p>
<div className="max-w-full">
<p
className={cn(
"truncate text-[11px] leading-5",
workToneClass(workEntry.tone),
preview ? "text-muted-foreground/70" : "",
)}
title={rawCommand ? undefined : displayText}
>
<span className={cn("text-foreground/80", workToneClass(workEntry.tone))}>
{heading}
</span>
{preview &&
(rawCommand ? (
<Tooltip>
<TooltipTrigger
closeDelay={0}
delay={75}
render={
<span className="max-w-full cursor-default text-muted-foreground/55 transition-colors hover:text-muted-foreground/75 focus-visible:text-muted-foreground/75">
{" "}
- {preview}
</span>
}
/>
<TooltipPopup
align="start"
className="max-w-[min(56rem,calc(100vw-2rem))] px-0 py-0"
side="top"
>
<div className="max-w-[min(56rem,calc(100vw-2rem))] overflow-x-auto px-1.5 py-1 font-mono text-[11px] leading-4 whitespace-nowrap">
{rawCommand}
</div>
</TooltipPopup>
</Tooltip>
) : (
<span className="text-muted-foreground/55"> - {preview}</span>
))}
</p>
</div>
</div>
</div>
{hasChangedFiles && !previewIsChangedFiles && (
@@ -477,6 +477,23 @@ describe("TraitsPicker (Codex)", () => {
});
});
it("shows default effort options for custom codex models without capabilities", async () => {
await using _ = await mountCodexPicker({
model: "custom-codex-model",
options: { reasoningEffort: "low" },
});
await page.getByRole("button").click();
await vi.waitFor(() => {
const text = document.body.textContent ?? "";
expect(text).toContain("Extra High");
expect(text).toContain("High");
expect(text).toContain("Medium");
expect(text).toContain("Low");
});
});
it("persists sticky codex model options when traits change", async () => {
await using _ = await mountCodexPicker({
options: { fastMode: false },
@@ -149,6 +149,36 @@ describe("getComposerProviderState", () => {
});
});
it("uses standard codex defaults for custom codex models without capabilities", () => {
const state = getComposerProviderState({
provider: "codex",
model: "custom-codex-model",
models: [
...CODEX_MODELS,
{
slug: "custom-codex-model",
name: "custom-codex-model",
isCustom: true,
capabilities: null,
},
],
prompt: "",
modelOptions: {
codex: {
reasoningEffort: "low",
},
},
});
expect(state).toEqual({
provider: "codex",
promptEffort: "low",
modelOptionsForDispatch: {
reasoningEffort: "low",
},
});
});
it("preserves codex fast mode when it is the only active option", () => {
const state = getComposerProviderState({
provider: "codex",
+5 -2
View File
@@ -5,7 +5,7 @@ import {
type ServerProvider,
type ServerProviderModel,
} from "@t3tools/contracts";
import { normalizeModelSlug } from "@t3tools/shared/model";
import { DEFAULT_CODEX_MODEL_CAPABILITIES, normalizeModelSlug } from "@t3tools/shared/model";
const EMPTY_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [],
@@ -53,7 +53,10 @@ export function getProviderModelCapabilities(
provider: ProviderKind,
): ModelCapabilities {
const slug = normalizeModelSlug(model, provider);
return models.find((candidate) => candidate.slug === slug)?.capabilities ?? EMPTY_CAPABILITIES;
const capabilities = models.find((candidate) => candidate.slug === slug)?.capabilities;
return (
capabilities ?? (provider === "codex" ? DEFAULT_CODEX_MODEL_CAPABILITIES : EMPTY_CAPABILITIES)
);
}
export function getDefaultServerModel(
+9 -3
View File
@@ -3,8 +3,9 @@ import { Atom } from "effect/unstable/reactivity";
import { appAtomRegistry } from "./atomRegistry";
export const SLOW_RPC_ACK_THRESHOLD_MS = 2_500;
export const SLOW_RPC_ACK_THRESHOLD_MS = 15_000;
export const MAX_TRACKED_RPC_ACK_REQUESTS = 256;
let slowRpcAckThresholdMs = SLOW_RPC_ACK_THRESHOLD_MS;
export interface SlowRpcAckRequest {
readonly requestId: string;
@@ -56,12 +57,12 @@ export function trackRpcRequestSent(requestId: string, tag: string): void {
startedAt: new Date(startedAtMs).toISOString(),
startedAtMs,
tag,
thresholdMs: SLOW_RPC_ACK_THRESHOLD_MS,
thresholdMs: slowRpcAckThresholdMs,
};
const timeoutId = setTimeout(() => {
pendingRpcAckRequests.delete(requestId);
appendSlowRpcAckRequest(request);
}, SLOW_RPC_ACK_THRESHOLD_MS);
}, slowRpcAckThresholdMs);
pendingRpcAckRequests.set(requestId, {
request,
@@ -119,9 +120,14 @@ function evictOldestPendingRpcRequestIfNeeded(): void {
}
export function resetRequestLatencyStateForTests(): void {
slowRpcAckThresholdMs = SLOW_RPC_ACK_THRESHOLD_MS;
clearAllTrackedRpcRequests();
}
export function setSlowRpcAckThresholdMsForTests(thresholdMs: number): void {
slowRpcAckThresholdMs = thresholdMs;
}
export function useSlowRpcAckRequests(): ReadonlyArray<SlowRpcAckRequest> {
return useAtomValue(slowRpcAckRequestsAtom);
}
+91
View File
@@ -709,6 +709,97 @@ describe("deriveWorkLogEntries", () => {
expect(entry?.command).toBe("bun run lint");
});
it("unwraps PowerShell command wrappers for displayed command text", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "command-tool-windows-wrapper",
kind: "tool.completed",
summary: "Ran command",
payload: {
itemType: "command_execution",
data: {
item: {
command: "\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",
},
},
},
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
expect(entry?.command).toBe("bun run lint");
expect(entry?.rawCommand).toBe(
"\"C:\\Program Files\\PowerShell\\7\\pwsh.exe\" -Command 'bun run lint'",
);
});
it("unwraps PowerShell command wrappers from argv-style command payloads", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "command-tool-windows-wrapper-argv",
kind: "tool.completed",
summary: "Ran command",
payload: {
itemType: "command_execution",
data: {
item: {
command: ["C:\\Program Files\\PowerShell\\7\\pwsh.exe", "-Command", "rg -n foo ."],
},
},
},
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
expect(entry?.command).toBe("rg -n foo .");
expect(entry?.rawCommand).toBe(
'"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -Command "rg -n foo ."',
);
});
it("extracts command text from command detail when structured command metadata is missing", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "command-tool-windows-detail-fallback",
kind: "tool.completed",
summary: "Ran command",
payload: {
itemType: "command_execution",
detail:
'"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command \'rg -n -F "new Date()" .\' <exited with exit code 0>',
},
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
expect(entry?.command).toBe('rg -n -F "new Date()" .');
expect(entry?.rawCommand).toBe(
`"C:\\Program Files\\PowerShell\\7\\pwsh.exe" -NoLogo -NoProfile -Command 'rg -n -F "new Date()" .'`,
);
});
it("does not unwrap shell commands when no wrapper flag is present", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
id: "command-tool-shell-script",
kind: "tool.completed",
summary: "Ran command",
payload: {
itemType: "command_execution",
data: {
item: {
command: "bash script.sh",
},
},
},
}),
];
const [entry] = deriveWorkLogEntries(activities, undefined);
expect(entry?.command).toBe("bash script.sh");
expect(entry?.rawCommand).toBeUndefined();
});
it("keeps compact Codex tool metadata used for icons and labels", () => {
const activities: OrchestrationThreadActivity[] = [
makeActivity({
+169 -12
View File
@@ -38,6 +38,7 @@ export interface WorkLogEntry {
label: string;
detail?: string;
command?: string;
rawCommand?: string;
changedFiles?: ReadonlyArray<string>;
tone: "thinking" | "tool" | "info" | "error";
toolTitle?: string;
@@ -489,7 +490,7 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
activity.payload && typeof activity.payload === "object"
? (activity.payload as Record<string, unknown>)
: null;
const command = extractToolCommand(payload);
const commandPreview = extractToolCommand(payload);
const changedFiles = extractChangedFiles(payload);
const title = extractToolTitle(payload);
const entry: DerivedWorkLogEntry = {
@@ -507,8 +508,11 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
entry.detail = detail;
}
}
if (command) {
entry.command = command;
if (commandPreview.command) {
entry.command = commandPreview.command;
}
if (commandPreview.rawCommand) {
entry.rawCommand = commandPreview.rawCommand;
}
if (changedFiles.length > 0) {
entry.changedFiles = changedFiles;
@@ -567,6 +571,7 @@ function mergeDerivedWorkLogEntries(
const changedFiles = mergeChangedFiles(previous.changedFiles, next.changedFiles);
const detail = next.detail ?? previous.detail;
const command = next.command ?? previous.command;
const rawCommand = next.rawCommand ?? previous.rawCommand;
const toolTitle = next.toolTitle ?? previous.toolTitle;
const itemType = next.itemType ?? previous.itemType;
const requestKind = next.requestKind ?? previous.requestKind;
@@ -576,6 +581,7 @@ function mergeDerivedWorkLogEntries(
...next,
...(detail ? { detail } : {}),
...(command ? { command } : {}),
...(rawCommand ? { rawCommand } : {}),
...(changedFiles.length > 0 ? { changedFiles } : {}),
...(toolTitle ? { toolTitle } : {}),
...(itemType ? { itemType } : {}),
@@ -636,7 +642,121 @@ function asTrimmedString(value: unknown): string | null {
return trimmed.length > 0 ? trimmed : null;
}
function normalizeCommandValue(value: unknown): string | null {
function trimMatchingOuterQuotes(value: string): string {
const trimmed = value.trim();
if (
(trimmed.startsWith("'") && trimmed.endsWith("'")) ||
(trimmed.startsWith('"') && trimmed.endsWith('"'))
) {
const unquoted = trimmed.slice(1, -1).trim();
return unquoted.length > 0 ? unquoted : trimmed;
}
return trimmed;
}
function executableBasename(value: string): string | null {
const trimmed = trimMatchingOuterQuotes(value);
if (trimmed.length === 0) {
return null;
}
const normalized = trimmed.replace(/\\/g, "/");
const segments = normalized.split("/");
const last = segments.at(-1)?.trim() ?? "";
return last.length > 0 ? last.toLowerCase() : null;
}
function splitExecutableAndRest(value: string): { executable: string; rest: string } | null {
const trimmed = value.trim();
if (trimmed.length === 0) {
return null;
}
if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
const quote = trimmed.charAt(0);
const closeIndex = trimmed.indexOf(quote, 1);
if (closeIndex <= 0) {
return null;
}
return {
executable: trimmed.slice(0, closeIndex + 1),
rest: trimmed.slice(closeIndex + 1).trim(),
};
}
const firstWhitespace = trimmed.search(/\s/);
if (firstWhitespace < 0) {
return {
executable: trimmed,
rest: "",
};
}
return {
executable: trimmed.slice(0, firstWhitespace),
rest: trimmed.slice(firstWhitespace).trim(),
};
}
const SHELL_WRAPPER_SPECS = [
{
executables: ["pwsh", "pwsh.exe", "powershell", "powershell.exe"],
wrapperFlagPattern: /(?:^|\s)-command\s+/i,
},
{
executables: ["cmd", "cmd.exe"],
wrapperFlagPattern: /(?:^|\s)\/c\s+/i,
},
{
executables: ["bash", "sh", "zsh"],
wrapperFlagPattern: /(?:^|\s)-(?:l)?c\s+/i,
},
] as const;
function findShellWrapperSpec(shell: string) {
return SHELL_WRAPPER_SPECS.find((spec) =>
(spec.executables as ReadonlyArray<string>).includes(shell),
);
}
function unwrapCommandRemainder(value: string, wrapperFlagPattern: RegExp): string | null {
const match = wrapperFlagPattern.exec(value);
if (!match) {
return null;
}
const command = value.slice(match.index + match[0].length).trim();
if (command.length === 0) {
return null;
}
const unwrapped = trimMatchingOuterQuotes(command);
return unwrapped.length > 0 ? unwrapped : null;
}
function unwrapKnownShellCommandWrapper(value: string): string {
const split = splitExecutableAndRest(value);
if (!split || split.rest.length === 0) {
return value;
}
const shell = executableBasename(split.executable);
if (!shell) {
return value;
}
const spec = findShellWrapperSpec(shell);
if (!spec) {
return value;
}
return unwrapCommandRemainder(split.rest, spec.wrapperFlagPattern) ?? value;
}
function formatCommandArrayPart(value: string): string {
return /[\s"'`]/.test(value) ? `"${value.replace(/"/g, '\\"')}"` : value;
}
function formatCommandValue(value: unknown): string | null {
const direct = asTrimmedString(value);
if (direct) {
return direct;
@@ -647,21 +767,58 @@ function normalizeCommandValue(value: unknown): string | null {
const parts = value
.map((entry) => asTrimmedString(entry))
.filter((entry): entry is string => entry !== null);
return parts.length > 0 ? parts.join(" ") : null;
if (parts.length === 0) {
return null;
}
return parts.map((part) => formatCommandArrayPart(part)).join(" ");
}
function extractToolCommand(payload: Record<string, unknown> | null): string | null {
function normalizeCommandValue(value: unknown): string | null {
const formatted = formatCommandValue(value);
return formatted ? unwrapKnownShellCommandWrapper(formatted) : null;
}
function toRawToolCommand(value: unknown, normalizedCommand: string | null): string | null {
const formatted = formatCommandValue(value);
if (!formatted || normalizedCommand === null) {
return null;
}
return formatted === normalizedCommand ? null : formatted;
}
function extractToolCommand(payload: Record<string, unknown> | null): {
command: string | null;
rawCommand: string | null;
} {
const data = asRecord(payload?.data);
const item = asRecord(data?.item);
const itemResult = asRecord(item?.result);
const itemInput = asRecord(item?.input);
const candidates = [
normalizeCommandValue(item?.command),
normalizeCommandValue(itemInput?.command),
normalizeCommandValue(itemResult?.command),
normalizeCommandValue(data?.command),
const itemType = asTrimmedString(payload?.itemType);
const detail = asTrimmedString(payload?.detail);
const candidates: unknown[] = [
item?.command,
itemInput?.command,
itemResult?.command,
data?.command,
itemType === "command_execution" && detail ? stripTrailingExitCode(detail).output : null,
];
return candidates.find((candidate) => candidate !== null) ?? null;
for (const candidate of candidates) {
const command = normalizeCommandValue(candidate);
if (!command) {
continue;
}
return {
command,
rawCommand: toRawToolCommand(candidate, command),
};
}
return {
command: null,
rawCommand: null,
};
}
function extractToolTitle(payload: Record<string, unknown> | null): string | null {
+9 -3
View File
@@ -5,7 +5,11 @@ import {
__resetClientTracingForTests,
configureClientTracing,
} from "./observability/clientTracing";
import { getSlowRpcAckRequests, resetRequestLatencyStateForTests } from "./rpc/requestLatencyState";
import {
getSlowRpcAckRequests,
resetRequestLatencyStateForTests,
setSlowRpcAckThresholdMsForTests,
} from "./rpc/requestLatencyState";
import {
getWsConnectionStatus,
getWsConnectionUiState,
@@ -292,6 +296,8 @@ describe("WsTransport", () => {
});
it("marks unary requests as slow until the first server ack arrives", async () => {
const slowAckThresholdMs = 25;
setSlowRpcAckThresholdMsForTests(slowAckThresholdMs);
const transport = new WsTransport("ws://localhost:3020");
const requestPromise = transport.request((client) =>
@@ -320,7 +326,7 @@ describe("WsTransport", () => {
tag: WS_METHODS.serverUpsertKeybinding,
},
]);
}, 5_000);
}, 1_000);
socket.serverMessage(
JSON.stringify({
@@ -343,7 +349,7 @@ describe("WsTransport", () => {
expect(getSlowRpcAckRequests()).toEqual([]);
await transport.dispose();
}, 10_000);
}, 5_000);
it("sends unary RPC requests and resolves successful exits", async () => {
const transport = new WsTransport("ws://localhost:3020");
+13
View File
@@ -14,6 +14,19 @@ export interface SelectableModelOption {
name: string;
}
export const DEFAULT_CODEX_MODEL_CAPABILITIES: ModelCapabilities = {
reasoningEffortLevels: [
{ value: "xhigh", label: "Extra High" },
{ value: "high", label: "High", isDefault: true },
{ value: "medium", label: "Medium" },
{ value: "low", label: "Low" },
],
supportsFastMode: true,
supportsThinkingToggle: false,
contextWindowOptions: [],
promptInjectedEffortLevels: [],
};
// ── Effort helpers ────────────────────────────────────────────────────
/** Check whether a capabilities object includes a given effort value. */