Compare commits

..
Author SHA1 Message Date
Mohamed Boudra dc72e6e5a2 test(app): assert the exact plugin toggle name 2026-11-18 19:03:32 +01:00
Mohamed Boudra 872b791aaa fix(app): preserve plugin toggle labels 2026-11-18 19:03:05 +01:00
Mohamed Boudra b242b99340 fix(claude): keep Ultra Code enabled when reopening older sessions 2026-11-18 18:39:13 +01:00
Mohamed Boudra 3a291393ca fix(app): share the draft effort action across controls
Keep the schedule effort picker able to select Ultra Code while schedules use a single effort field.
2026-11-18 18:27:22 +01:00
Mohamed Boudra f12f9ff9f6 fix(claude): let the host translate legacy Ultracode settings
Retain the legacy effort through older hosts. Promote the resolved setting on effort changes only when the current host exposes a toggle, and persist it with the effort choice.
2026-11-18 18:11:21 +01:00
Mohamed Boudra dac365aaac fix(claude): retain Ultracode when a legacy draft changes effort
Keep migrated model options in the draft model. Preserve the combined Extra high behavior for older Claude Code versions.
2026-11-18 17:57:51 +01:00
Mohamed Boudra 59eb9c0057 fix(claude): preserve model-specific Ultracode preferences
Read the legacy setting for the selected model and leave schedules editable through their existing effort control. Keep the state in the default toolbar tooltip.
2026-11-18 17:44:47 +01:00
Mohamed Boudra 4fc3631080 fix(claude): carry saved Ultra Code choices into the toggle
Convert saved settings before consumers validate effort. Keep provider-supplied toolbar tooltips so availability notices remain visible.
2026-11-18 17:31:11 +01:00
Mohamed Boudra ae61c08ac6 test(app): cover visible toggle state in the composer 2026-11-18 17:14:02 +01:00
Mohamed Boudraandfivetaku 6444c021ea feat(claude): give Ultracode its own toggle
Keep workflow orchestration enabled across live effort changes. Preserve the combined effort choice for older Claude Code versions and legacy sessions.

Co-authored-by: fivetaku <zipsanyang.ai@gmail.com>
2026-11-18 17:10:14 +01:00
40 changed files with 591 additions and 556 deletions
+2 -2
View File
@@ -50,8 +50,8 @@ or without a control.
reject. A key the running session cannot apply (one the provider reads only when it opens) is
rejected too, so a stored option always describes what runs. Claude reads most options when it
starts its query, and replacing a started query would end its background work, so after the
first prompt only Fast can change. Codex fixes its approval policy and sandbox when the thread
starts, so it applies only `service_tier` and `plan_mode` live. A session with no
first prompt only Fast and Ultracode can change. Codex fixes its approval policy and sandbox
when the thread starts, so it applies only `service_tier` and `plan_mode` live. A session with no
`applyOptions` rejects every patch; the daemon enforces this. The provider returns the options
it ended up with when they differ from the request. The daemon stores the patch and that
result in one step after the call resolves. Throwing rejects the whole patch and none of it is
@@ -56,20 +56,11 @@ function inFlightTurn(page: Page) {
return page.getByTestId("turn-working-indicator");
}
/**
* Presses a fork trigger until its menu shows.
*
* The in-flight turn's trigger sits below text that is still streaming in. While the chat is
* shorter than the viewport, each new line moves the trigger down. A line that arrives between
* the press and the release moves the trigger away from the pointer, so the press opens nothing,
* and the next press lands on the trigger where it is now.
*/
async function openForkMenu(page: Page, trigger: ReturnType<Page["getByRole"]>): Promise<void> {
const forkInNewTab = page.getByRole("menuitem", { name: "Fork in a new tab" });
await expect(async () => {
await trigger.click({ timeout: 5_000 });
await expect(forkInNewTab).toBeVisible({ timeout: 5_000 });
}).toPass({ timeout: 30_000 });
await trigger.click();
await expect(page.getByRole("menuitem", { name: "Fork in a new tab" })).toBeVisible({
timeout: 10_000,
});
}
export async function openMostRecentAssistantForkMenu(page: Page): Promise<void> {
@@ -30,6 +30,25 @@ function answer(
}
describe("draft options model", () => {
it("retains an Ultracode option only after the current host advertises it", () => {
const model = openDraftOptions({ provider: "claude" });
const legacy = { provider: "claude", cwd: "/repo", thinkingOptionId: "ultracode" };
model.applyResolved(answer("claude", "old-host", {}, []));
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
expect(draftControlsRequest(model.getState(), legacy)).toEqual(legacy);
model.applyResolved(
answer("claude", "new-host", { ultracode: true }, [
{ type: "toggle", key: "ultracode", label: "Ultracode" },
]),
);
expect(model.retainResolvedOption("ultracode", "old-host")).toBeUndefined();
expect(model.retainResolvedOption("ultracode", "new-host")).toEqual({ ultracode: true });
expect(
draftControlsRequest(model.getState(), { ...legacy, thinkingOptionId: "high" }),
).toMatchObject({ thinkingOptionId: "high", providerOptions: { ultracode: true } });
});
it("draws a legacy Fast profile as the Fast tier the daemon resolved", () => {
const model = openDraftOptions({ provider: "codex", seed: { service_tier: "fast" } });
model.applyResolved(answer("codex", "k1", { service_tier: "priority" }));
@@ -47,6 +47,7 @@ export interface DraftOptionsModel {
applyProfile: (profile: { provider: string; options: ProviderOptions }) => void;
setRemembered: (remembered: ProviderOptions) => void;
setOption: (key: string, value: unknown) => void;
retainResolvedOption: (key: string, requestKey: string) => ProviderOptions | undefined;
applyResolved: (resolved: ResolvedDraftOptions) => void;
}
@@ -112,6 +113,17 @@ export function openDraftOptions(input: {
: { ...current, edits: { ...current.edits, [key]: value } },
);
},
retainResolvedOption: (key, requestKey) => {
const resolved = state.resolved;
if (resolved?.requestKey !== requestKey || key in state.edits) return undefined;
const value = resolved.options[key];
if (value === undefined || !resolved.controls.some((control) => control.key === key)) {
return undefined;
}
const patch = { [key]: value };
publish((current) => ({ ...current, edits: { ...current.edits, ...patch } }));
return patch;
},
applyResolved: (resolved) =>
publish((current) => ({
...current,
File diff suppressed because one or more lines are too long
@@ -215,32 +215,6 @@ describe("Mermaid sandbox runtime", () => {
expect(widths).toEqual([240, 350, 900]);
});
/**
* Agents often write a label that starts with a mention or holds an email address. Mermaid 11
* read the text up to the "@" as an edge id, so these diagrams failed to parse.
*/
it.each([
"flowchart LR\n F[@mention in any workspace] --> G[Look up token]",
"flowchart LR\n A[ops@example.com] --> B",
"flowchart LR\n A -->|@user approves| B",
"graph TD\n A(@x) --> B{@x?}",
])("renders a flowchart whose label contains an @: %s", async (source) => {
const frame = await mountRuntime();
const result = await render(frame, { revision: 1, source });
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
});
it("still renders a flowchart edge id", async () => {
const frame = await mountRuntime();
const source = "flowchart LR\n A[Start] e1@--> B[End]";
const result = await render(frame, { revision: 1, source });
expect(result).toMatchObject({ type: "rendered", revision: 1, source });
});
it("coalesces queued input and never reports an obsolete result", async () => {
const frame = await mountRuntime();
const obsoleteSource = `flowchart TD\n${Array.from({ length: 250 }, (_, index) => `A${index} --> A${index + 1}`).join("\n")}`;
@@ -1,103 +0,0 @@
// @vitest-environment jsdom
import type { ReactNode } from "react";
import { cleanup, renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, expect, it } from "vitest";
import type { FileReadResult } from "@getpaseo/client/internal/daemon-client";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import type { AttachmentStore } from "@/attachments/types";
import { useMarkdownSource, type MarkdownImageContext } from "./images";
import { PENDING_MARKDOWN_IMAGE } from "./source";
const memoryStore: AttachmentStore = {
storageType: "web-indexeddb",
async save(input) {
return {
id: input.id ?? "att_chart",
mimeType: input.mimeType ?? "image/png",
storageType: "web-indexeddb",
storageKey: input.id ?? "att_chart",
fileName: input.fileName,
createdAt: 1,
};
},
async encodeBase64() {
return "";
},
async resolvePreviewUrl() {
return "blob:chart";
},
async releasePreviewUrl() {},
async delete() {},
async garbageCollect() {},
};
function createHostFiles() {
const reads: { cwd: string; path: string }[] = [];
return {
reads,
async readFile(cwd: string, path: string): Promise<FileReadResult> {
reads.push({ cwd, path });
return {
kind: "image",
path,
mime: "image/png",
size: 4,
modifiedAt: "2026-11-18T00:00:00.000Z",
bytes: new Uint8Array([1, 2, 3, 4]),
};
},
};
}
beforeEach(() => {
__setAttachmentStoreForTests(memoryStore);
});
afterEach(() => {
cleanup();
__setAttachmentStoreForTests(null);
});
function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) {
// No retries: a failed read settles at once. For a host's Markdown this is the state once the
// retries have run out on a host that is slow to connect.
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), {
wrapper,
initialProps,
});
return { ...rendered, queryClient };
}
it("waits for the host's client before reading a workspace image", async () => {
const context = { serverId: "srv_test", workspaceRoot: "/repo" };
const { result, rerender, queryClient } = renderMarkdownSource("![Chart](chart.png)", {
...context,
client: null,
});
await waitFor(() => {
expect(queryClient.isFetching()).toBe(0);
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe(
"![Chart](<pending>)",
);
});
const files = createHostFiles();
rerender({ ...context, client: files });
await waitFor(() => expect(result.current.imageSources).toEqual({ "blob:chart": "chart.png" }));
expect(files.reads).toEqual([{ cwd: "/repo", path: "chart.png" }]);
});
it("shows the alt text of a file image in Markdown that belongs to no host", async () => {
const { result } = renderMarkdownSource("![Chart](/tmp/chart.png)", {});
await waitFor(() =>
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"),
);
});
@@ -81,10 +81,7 @@ export function useMarkdownSource(
const results = useFetchQueries(
acquisitions.map((acquisition, index) => ({
queryKey: ["markdownImage", acquisition?.key ?? sources[index]],
// A host that hasn't connected yet has no client. Its images stay pending until it does: the
// key doesn't change when the client arrives, so a read that already failed would not run
// again. Markdown with no host has no client to wait for and falls back to its alt text.
enabled: acquisition !== null && (context.client != null || !context.serverId),
enabled: acquisition !== null,
immutableWhen: () => true,
dataShape: "value",
gcTime: 0,
@@ -82,10 +82,10 @@ describe("ComposerControls", () => {
expect(trigger.textContent).not.toContain("Large");
});
it("flips a toggle on press in the toolbar", () => {
it("keeps the toolbar toggle name and flips it on press", () => {
const onChange = vi.fn();
renderControls([{ ...base, type: "toggle", value: true, onChange }]);
fireEvent.click(screen.getByRole("button", { name: "Context" }));
fireEvent.click(screen.getByRole("button", { name: /^Context$/ }));
expect(onChange).toHaveBeenCalledWith(false);
});
@@ -94,6 +94,12 @@ describe("ComposerControls", () => {
expect(screen.getByRole("button", { name: "Context" }).textContent).toContain("On");
});
it("keeps the provider's tooltip for a toolbar toggle", () => {
const tooltip = "Fast is enabled but does not apply to this model.";
renderControls([{ ...base, type: "toggle", value: true, tooltip, onChange: () => undefined }]);
expect(screen.getByRole("button", { name: tooltip })).toBeDefined();
});
it("gives a sheet row's value the row's width, so a short value is not truncated", () => {
const toast = createToast();
render(
@@ -157,6 +163,8 @@ describe("ComposerControls", () => {
});
const FAST_ON = { fast_mode: true };
const ULTRACODE_ON = { ultracode: true };
const ignoreOption = () => undefined;
describe("provider option controls", () => {
const fastMode: AgentOptionControl = {
@@ -173,7 +181,11 @@ describe("provider option controls", () => {
onSetOption: (key: string, value: unknown) => void;
}) {
const optionControls = React.useMemo(
() => ({ controls: [fastMode], options, onSetOption }),
() => ({
controls: [fastMode, { key: "ultracode", label: "Ultracode", type: "toggle" as const }],
options,
onSetOption,
}),
[onSetOption, options],
);
const items = useAgentControlItems({
@@ -197,4 +209,9 @@ describe("provider option controls", () => {
fireEvent.click(screen.getByTestId("agent-feature-fast_mode"));
expect(writes).toEqual([["fast_mode", false]]);
});
it("announces the state of a provider toggle with no custom tooltip", () => {
render(<OptionControls options={ULTRACODE_ON} onSetOption={ignoreOption} />);
expect(screen.getByRole("button", { name: "Ultracode: On" })).toBeDefined();
});
});
@@ -28,7 +28,7 @@ interface ComposerControlBase {
title: string;
icon: AgentControlIcon;
/** Tints the icon; muted when absent. */
highlight?: "blue" | "green" | "yellow";
highlight?: "blue" | "green" | "purple" | "yellow";
/** Defaults to the title, or to "title: choice" on an icon-only select. */
tooltip?: string;
/** Defaults to the tooltip. */
@@ -393,6 +393,7 @@ function ComposerControlSlot({
const styles = StyleSheet.create((theme) => ({
fieldIcon: { color: theme.colors.foregroundMuted },
blue: { color: theme.colors.palette.blue[400] },
purple: { color: theme.colors.palette.purple[500] },
green: { color: theme.colors.palette.green[400] },
yellow: { color: theme.colors.palette.yellow[400] },
tooltipText: {
@@ -33,6 +33,8 @@ function getFeatureHighlight(
function toFeatureItem(
control: AgentOptionControl,
optionControls: ComposerOptionControls,
surface: ComposerControlSurface,
t: TFunction,
): ComposerControlItem {
const { options, onSetOption } = optionControls;
const base = {
@@ -43,11 +45,15 @@ function toFeatureItem(
testID: `agent-feature-${control.key}`,
};
if (control.type === "toggle") {
const enabled = readToggleOption(control, options);
const stateLabel = enabled ? t("agentControls.features.on") : t("agentControls.features.off");
return {
...base,
type: "toggle",
tooltip: getControlTooltip(control),
value: readToggleOption(control, options),
tooltip:
control.tooltip ??
(surface === "toolbar" ? `${control.label}: ${stateLabel}` : control.label),
value: enabled,
onChange: (value) => onSetOption(control.key, value),
};
}
@@ -92,9 +98,11 @@ export function useAgentControlItems({
const features = useMemo(
() =>
optionControls
? optionControls.controls.map((control) => toFeatureItem(control, optionControls))
? optionControls.controls.map((control) =>
toFeatureItem(control, optionControls, surface, t),
)
: [],
[optionControls],
[optionControls, surface, t],
);
return { thinking: thinkingItem, features };
}
@@ -1316,8 +1316,7 @@ export function DraftAgentControls({
return toThinkingControlOptions(thinkingOptions);
}, [thinkingOptions]);
const effectiveSelectedThinkingOption =
selectedThinkingOptionId || mappedThinkingOptions[0]?.id || undefined;
const effectiveSelectedThinkingOption = selectedThinkingOptionId || mappedThinkingOptions[0]?.id;
const modelOptions = useMemo<AgentControlOption[]>(
() =>
@@ -20,6 +20,7 @@ describe("feature metadata helpers", () => {
expect(getFeatureHighlightColor("fast_mode")).toBe("yellow");
expect(getFeatureHighlightColor("service_tier")).toBe("yellow");
expect(getFeatureHighlightColor("plan_mode")).toBe("blue");
expect(getFeatureHighlightColor("ultracode")).toBe("purple");
expect(getFeatureHighlightColor("other")).toBe("default");
});
});
@@ -8,7 +8,7 @@ import {
} from "@/agent-controls/policy";
export type ExplainedAgentControl = "mode" | "model" | "thinking";
export type FeatureHighlightColor = "blue" | "default" | "green" | "yellow";
export type FeatureHighlightColor = "blue" | "default" | "green" | "purple" | "yellow";
export type AgentControlHintKey =
| "agentControls.hints.thinking"
| "agentControls.hints.model"
@@ -48,6 +48,8 @@ export function getFeatureHighlightColor(featureId: string): FeatureHighlightCol
return "yellow";
case "auto_accept":
return "green";
case "ultracode":
return "purple";
case PLAN_MODE_FEATURE_ID:
return "blue";
default:
+20 -2
View File
@@ -22,6 +22,7 @@ import {
resolveEffectiveComposerThinkingOptionId,
type ProviderSelectionState,
} from "@/provider-selection/provider-selection";
import { findThinkingOptionReplacement } from "@/provider-selection/resolve-agent-form";
import { useDraftStore, type DraftInput } from "@/stores/draft-store";
import { AfterPaintPublication } from "@/composer/after-paint-publication";
import { useShallow } from "zustand/shallow";
@@ -293,6 +294,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
options: draftOptions,
shownOptions: draftShownOptions,
setOption: setDraftOption,
retainLegacyUltracode,
applyProfile: applyProfileOptions,
} = useDraftProviderOptions({
serverId: formState.selectedServerId,
@@ -312,6 +314,11 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
},
[applyProfileOptions, formState],
);
const setDraftThinking = useCallback(
(thinkingOptionId: string) =>
formState.setThinkingOptionFromUser(thinkingOptionId, retainLegacyUltracode()),
[formState, retainLegacyUltracode],
);
const commandDraft = useMemo(
() =>
@@ -330,8 +337,18 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
return null;
}
return {
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
const draftForm = {
...formState,
selectedThinkingOptionId:
findThinkingOptionReplacement(
formState.availableThinkingOptions,
formState.selectedThinkingOptionId,
) ?? formState.selectedThinkingOptionId,
setThinkingOptionFromUser: setDraftThinking,
};
return {
...draftForm,
workingDir,
effectiveModeId,
effectiveModelId,
@@ -339,7 +356,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
providerOptions: draftOptions,
metadata,
agentControls: buildDraftAgentControls({
formState,
formState: draftForm,
optionControls: draftOptionControls,
options: draftShownOptions,
onSetOption: setDraftOption,
@@ -360,6 +377,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
draftOptions,
draftShownOptions,
setDraftOption,
setDraftThinking,
applyDraftAgentProfile,
formState,
metadata,
@@ -4,6 +4,7 @@ import type {
AgentMode,
AgentModelDefinition,
AgentProvider,
ProviderOptions,
ProviderSnapshotEntry,
} from "@getpaseo/protocol/agent-types";
import { buildProviderDefinitions } from "@/utils/provider-definitions";
@@ -58,7 +59,7 @@ export interface UseAgentFormStateResult {
selectedModel: string;
setModelFromUser: (modelId: string) => void;
selectedThinkingOptionId: string;
setThinkingOptionFromUser: (thinkingOptionId: string) => void;
setThinkingOptionFromUser: (thinkingOptionId: string, retainedOptions?: ProviderOptions) => void;
workingDir: string;
providerDefinitions: AgentProviderDefinition[];
providerDefinitionMap: Map<AgentProvider, AgentProviderDefinition>;
@@ -419,7 +420,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
);
const setThinkingOptionFromUser = useCallback(
(thinkingOptionId: string) => {
(thinkingOptionId: string, retainedOptions?: ProviderOptions) => {
dispatch({ type: "SET_THINKING_OPTION_FROM_USER", thinkingOptionId });
const { provider, model: modelId } = formStore.getState().form;
if (provider && modelId) {
@@ -431,6 +432,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
thinkingByModel: {
[modelId]: thinkingOptionId,
},
options: retainedOptions,
},
}),
);
@@ -69,6 +69,14 @@ export function useDraftProviderOptions(input: {
[draftConfig, serverId],
);
const requestKey = JSON.stringify(queryKey);
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
const retainLegacyUltracode = useCallback(
() =>
thinkingOptionId === "ultracode"
? model.retainResolvedOption("ultracode", requestKey)
: undefined,
[model, requestKey, thinkingOptionId],
);
const { data } = useFetchQuery({
queryKey,
@@ -129,6 +137,7 @@ export function useDraftProviderOptions(input: {
options: ownOptions,
shownOptions,
setOption,
retainLegacyUltracode,
applyProfile: model.applyProfile,
};
}
@@ -167,6 +167,14 @@ function resolvePreferredThinkingOptionId(input: {
return "";
}
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18.
export function findThinkingOptionReplacement(
options: NonNullable<AgentModelDefinition["thinkingOptions"]>,
legacyId: string,
): string | undefined {
return options.find((option) => option.metadata?.replacesThinkingOptionId === legacyId)?.id;
}
export function resolveThinkingOptionId(args: {
availableModels: AgentModelDefinition[] | null;
modelId: string;
@@ -183,6 +191,9 @@ export function resolveThinkingOptionId(args: {
) {
return normalizedThinkingOptionId;
}
if (findThinkingOptionReplacement(thinkingOptions, normalizedThinkingOptionId)) {
return normalizedThinkingOptionId;
}
return effectiveModel?.defaultThinkingOptionId ?? thinkingOptions[0]?.id ?? "";
}
@@ -96,6 +96,7 @@ function scheduleOnHost(input: {
serverName: string;
cwd: string;
model: string;
provider?: string;
thinkingOptionId?: string | null;
cadence?: ScheduleSummary["cadence"];
}): TestSchedule {
@@ -109,7 +110,7 @@ function scheduleOnHost(input: {
target: {
type: "new-agent",
config: {
provider: "mock",
provider: input.provider ?? "mock",
cwd: input.cwd,
model: input.model,
modeId: "load-test",
@@ -186,6 +187,56 @@ function applyPreferences(form: ReturnType<typeof open>, preferences: FormPrefer
}
describe("schedule form model", () => {
it("keeps Ultra Code available in the schedule effort picker", () => {
const model = "claude-opus-4-8";
const form = open({
mode: "edit",
schedule: scheduleOnHost({
serverId: "host-a",
serverName: "Host A",
cwd: "/repo/a",
provider: "claude",
model,
thinkingOptionId: "ultracode",
}),
defaults: { serverId: null, projectTargets: PROJECT_TARGETS, preferences: {} },
});
form.applyProviderSnapshot("host-a", {
...providerSnapshot([]),
entries: [
{
provider: "claude",
status: "ready",
enabled: true,
models: [
{
provider: "claude",
id: model,
label: "Opus 4.8",
thinkingOptions: [
{ id: "high", label: "High" },
{
id: "xhigh",
label: "Extra high",
metadata: { replacesThinkingOptionId: "ultracode" },
},
],
},
],
},
],
});
expect(form.getState().selectedThinkingOptionId).toBe("ultracode");
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
"ultracode",
);
form.setThinking("high");
expect(form.getState().selectedThinkingOptionId).toBe("high");
expect(form.getState().availableThinkingOptions.map((option) => option.id)).toContain(
"ultracode",
);
});
it("opens edit from the schedule host snapshot and completes that host resolution", () => {
const previous = open({
mode: "edit",
@@ -14,6 +14,7 @@ import {
import { filterSelectableModels, findModelByReference } from "@/provider-selection/model-catalog";
import {
buildProviderDefinitionMapForStatuses,
findThinkingOptionReplacement,
INITIAL_USER_MODIFIED,
RESOLVABLE_PROVIDER_STATUSES,
resolveDefaultModelId,
@@ -273,7 +274,14 @@ function resolveThinkingOptions(
modelId: string,
): NonNullable<AgentModelDefinition["thinkingOptions"]> {
const model = resolveEffectiveModel(resolveAvailableModels(entries, provider), modelId);
return model?.thinkingOptions ?? [];
const options = model?.thinkingOptions ?? [];
// COMPAT(claudeUltracodePreference): added in v0.17.0, remove after 2027-05-18
// once schedules edit the Ultracode option independently.
// Schedules still use a single effort field.
return findThinkingOptionReplacement(options, "ultracode") &&
!options.some((option) => option.id === "ultracode")
? [...options, { id: "ultracode", label: "Ultra Code" }]
: options;
}
function resolveModelDisplay(input: {
@@ -92,7 +92,11 @@ const pinnedTheme = {
const testTheme = {
...lightTheme,
...pinnedTheme,
colors: { ...lightTheme.colors, ...pinnedTheme.colors },
colors: {
...lightTheme.colors,
...pinnedTheme.colors,
palette: { ...lightTheme.colors.palette, ...pinnedTheme.colors.palette },
},
};
type StyleFactory<T> = (theme: typeof testTheme) => T;
@@ -69,6 +69,7 @@ import {
applyProviderOptionsPatch,
exposeFeatureValuesToHook,
convertLegacyOptions,
convertLegacyClaudeUltracode,
MalformedLegacyOptionError,
resolveAdapter,
foldHookFeatureValues,
@@ -6194,7 +6195,15 @@ export class AgentManager {
private withConvertedOptions(config: AgentSessionConfig): AgentSessionConfig {
const providerOptions = this.convertLegacyOptions(config.provider, config.providerOptions);
return providerOptions === config.providerOptions ? config : { ...config, providerOptions };
return this.convertLegacySessionConfig(
providerOptions === config.providerOptions ? config : { ...config, providerOptions },
);
}
convertLegacySessionConfig<T extends Parameters<typeof convertLegacyClaudeUltracode>[0]>(
config: T,
): T {
return convertLegacyClaudeUltracode(config, this.adapterOf(config.provider));
}
private async prepareSessionConfig(
@@ -1,6 +1,19 @@
import { isDeepStrictEqual } from "node:util";
import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18
// once schedules stop writing the legacy effort and existing records have migrated.
export function convertLegacyClaudeUltracode<
T extends { provider: string; thinkingOptionId?: string; providerOptions?: ProviderOptions },
>(config: T, adapter = config.provider): T {
if (adapter !== "claude" || config.thinkingOptionId !== "ultracode") return config;
return {
...config,
thinkingOptionId: "xhigh",
providerOptions: { ultracode: true, ...config.providerOptions },
};
}
/**
* A patch over an agent's own options: top-level keys replace, `null` removes the key so the
* `config.json` default (or the provider's own default) applies again.
@@ -605,8 +605,6 @@ class ProviderRuntimeSession {
>();
private readonly activeTurnIds = new Set<string>();
private terminal = false;
// The provider ended this session with session.closed, so it has nothing left to close.
private closedByProvider = false;
private closePromise: Promise<void> | null = null;
config: ProviderConfigState = { models: [], modes: [], thinkingOptions: [] };
commands: Array<{ name: string; description: string; argumentHint?: string }> = [];
@@ -725,7 +723,7 @@ class ProviderRuntimeSession {
async close(): Promise<void> {
this.history.length = 0;
if (this.restoration === "parent" || this.closedByProvider) {
if (this.restoration === "parent") {
this.runtime.removeSession(this.id, this.providerSessionId);
return;
}
@@ -790,7 +788,6 @@ class ProviderRuntimeSession {
return;
}
if (event.type === "session.runtime_failed" || event.type === "session.closed") {
if (event.type === "session.closed") this.closedByProvider = true;
if (this.terminal) return;
this.terminal = true;
this.publish(event);
@@ -1548,7 +1548,7 @@ describe("model merging", () => {
models
.find((model) => model.id === "claude-sonnet-5")
?.thinkingOptions?.map((option) => option.id),
).toEqual(["off", "low", "medium", "high", "xhigh", "max", "ultracode"]);
).toEqual(["off", "low", "medium", "high", "xhigh", "max"]);
expect(models.find((model) => model.id === "claude-opus-5")?.thinkingOptions).toEqual([]);
expect(models.find((model) => model.id === "custom-explicit")).toMatchObject({
thinkingOptions: [{ id: "bespoke", label: "Bespoke", isDefault: true }],
@@ -26,6 +26,7 @@ import {
resolveSnapshotCwd,
} from "./provider-snapshot-manager.js";
import { OpenCodeAgentClient } from "./providers/opencode-agent.js";
import { getClaudeModels } from "./providers/claude/models.js";
const TEST_CAPABILITIES = {
supportsStreaming: false,
@@ -311,6 +312,29 @@ describe("ProviderSnapshotManager public surface", () => {
}
});
test("accepts a legacy Ultra Code choice on a model with an independent effort catalog", async () => {
const manager = new ProviderSnapshotManager({
logger: createTestLogger(),
extraClients: {
claude: createExtraClient("claude", {
isAvailable: async () => true,
fetchCatalog: async () => ({ models: getClaudeModels("2.1.284"), modes: [] }),
}),
},
});
try {
await expect(
manager.validateAgentConfiguration({
provider: "claude",
model: "claude-opus-4-8",
thinkingOptionId: "ultracode",
}),
).resolves.toEqual([]);
} finally {
manager.destroy();
}
});
test("reports an unavailable Hub agent provider at the authored provider field", async () => {
const manager = new ProviderSnapshotManager({ logger: createTestLogger() });
try {
@@ -51,6 +51,7 @@ import {
} from "./agent-configuration-validator.js";
import type { ProviderRegistration } from "@getpaseo/plugin/server/provider";
import { PluginAgentClientRegistry } from "./plugin-provider.js";
import { convertLegacyClaudeUltracode, resolveAdapter } from "./option-controls.js";
const DEFAULT_REFRESH_TIMEOUT_MS = 120_000;
const MAX_REFRESH_TIMEOUT_MS = 2_147_483_647;
@@ -516,7 +517,13 @@ export class ProviderSnapshotManager {
}
return validateAgentConfigurationAgainstProvider({
input,
input: convertLegacyClaudeUltracode(
input,
resolveAdapter({
provider: input.provider,
extendsOf: (id) => this.generation.definitions[id]?.derivedFromProviderId,
}),
),
provider,
});
}
@@ -2,6 +2,7 @@ import { expect, test } from "vitest";
import type { Query, SDKMessage } from "@anthropic-ai/claude-agent-sdk";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
import type { AgentStreamEvent } from "../../agent-sdk-types.js";
import { convertLegacyClaudeUltracode } from "../../option-controls.js";
import { ClaudeAgentClient } from "./agent.js";
import type { ClaudeQueryInput } from "./query.js";
@@ -18,6 +19,7 @@ function deferred<T>() {
class ForegroundQuery {
readonly work = deferred<void>();
readonly closed = deferred<void>();
readonly flagSettings: Parameters<Query["applyFlagSettings"]>[0][] = [];
private stopped = false;
private readonly output: AsyncGenerator<SDKMessage>;
@@ -72,6 +74,9 @@ class ForegroundQuery {
}
async setPermissionMode() {}
async setModel() {}
async applyFlagSettings(settings: Parameters<Query["applyFlagSettings"]>[0]) {
this.flagSettings.push(settings);
}
async supportedCommands() {
return [];
}
@@ -156,3 +161,122 @@ test.each(["mode", "model", "commands"] as const)(
}
},
);
test("Ultracode toggles at Medium and stays enabled when effort changes live", async () => {
const queries: ForegroundQuery[] = [];
const launchOptions: ClaudeQueryInput["options"][] = [];
const client = new ClaudeAgentClient({
logger: createTestLogger(),
resolveBinary: async () => "/test/claude",
resolveVersion: async () => "2.1.284",
queryFactory: (input) => {
const query = new ForegroundQuery(input);
queries.push(query);
launchOptions.push(input.options);
return query as unknown as Query;
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
model: "claude-opus-4-8",
thinkingOptionId: "medium",
providerOptions: { ultracode: false },
});
try {
expect(session.controls).toContainEqual(
expect.objectContaining({ key: "ultracode", type: "toggle" }),
);
await session.startTurn("Start at Medium");
expect(launchOptions[0]).toMatchObject({ effort: "medium", settings: { ultracode: false } });
await session.applyOptions?.({ ultracode: true });
await session.setThinkingOption?.("high");
await session.applyOptions?.({ ultracode: false });
expect(queries).toHaveLength(1);
expect(queries[0].flagSettings).toEqual([
{ fastMode: false, ultracode: false },
{ ultracode: true },
{ effortLevel: "high", ultracode: true },
{ ultracode: false },
]);
} finally {
await session.close();
}
});
test.each([
["xhigh", true],
["high", false],
] as const)("older Claude Code launches %s with Ultracode set to %s", async (effort, enabled) => {
const launchOptions: ClaudeQueryInput["options"][] = [];
const client = new ClaudeAgentClient({
logger: createTestLogger(),
resolveBinary: async () => "/test/claude",
resolveVersion: async () => "2.1.283",
queryFactory: (input) => {
launchOptions.push(input.options);
return new ForegroundQuery(input) as unknown as Query;
},
});
const session = await client.createSession({
provider: "claude",
cwd: process.cwd(),
model: "claude-opus-4-8",
thinkingOptionId: effort,
providerOptions: { ultracode: true },
});
try {
expect(session.controls?.some((control) => control.key === "ultracode")).toBe(false);
await session.startTurn("Start the agent");
expect(launchOptions[0]).toMatchObject({ effort, settings: { ultracode: enabled } });
} finally {
await session.close();
}
});
test("reopens an older Claude Code agent with Ultracode after choosing Ultra Code again", async () => {
const launchOptions: ClaudeQueryInput["options"][] = [];
const client = new ClaudeAgentClient({
logger: createTestLogger(),
resolveBinary: async () => "/test/claude",
resolveVersion: async () => "2.1.283",
queryFactory: (input) => {
launchOptions.push(input.options);
return new ForegroundQuery(input) as unknown as Query;
},
});
const config = {
provider: "claude",
cwd: process.cwd(),
model: "claude-opus-4-8",
thinkingOptionId: "xhigh",
providerOptions: { ultracode: true },
};
const session = await client.createSession(config);
let savedOptions = config.providerOptions;
session.subscribe((event) => {
if (event.type === "options_changed" && typeof event.patch.ultracode === "boolean") {
savedOptions = { ultracode: event.patch.ultracode };
}
});
try {
await session.setThinkingOption?.("high");
expect(savedOptions.ultracode).toBe(false);
await session.setThinkingOption?.("ultracode");
} finally {
await session.close();
}
const reopened = await client.createSession(
convertLegacyClaudeUltracode({
...config,
thinkingOptionId: "ultracode",
providerOptions: savedOptions,
}),
);
try {
await reopened.startTurn("Start the agent");
expect(launchOptions[0]).toMatchObject({ effort: "xhigh", settings: { ultracode: true } });
} finally {
await reopened.close();
}
});
@@ -543,21 +543,20 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
return models.find((model) => model.id === modelId)?.thinkingOptions?.map(({ id }) => id);
};
expect(getThinkingIds("claude-opus-5")).toContain("ultracode");
expect(getThinkingIds("claude-opus-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-mythos-5-1")).toEqual([
"low",
"medium",
"high",
"xhigh",
"max",
"ultracode",
]);
expect(getThinkingIds("claude-fable-5-1")).toContain("ultracode");
expect(getThinkingIds("claude-fable-5")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8[1m]")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8")).toContain("ultracode");
expect(getThinkingIds("claude-fable-5-1")).not.toContain("ultracode");
expect(getThinkingIds("claude-fable-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8[1m]")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-8")).not.toContain("ultracode");
expect(getThinkingIds("claude-sonnet-5")).toContain("xhigh");
expect(getThinkingIds("claude-sonnet-5")).toContain("ultracode");
expect(getThinkingIds("claude-sonnet-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-haiku-5-5")).toEqual([
"off",
"low",
@@ -565,12 +564,11 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
"high",
"xhigh",
"max",
"ultracode",
]);
expect(getThinkingIds("claude-sonnet-5-5")).toContain("xhigh");
expect(getThinkingIds("claude-sonnet-5-5")).not.toContain("off");
expect(getThinkingIds("claude-opus-4-7[1m]")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7[1m]")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7")).not.toContain("ultracode");
expect(getThinkingIds("claude-sonnet-4-6")).not.toContain("ultracode");
} finally {
await fs.rm(emptyConfigDir, { recursive: true, force: true });
@@ -1181,8 +1179,8 @@ describe("ClaudeAgentSession features", () => {
await session.close();
});
test("lists fast mode only for supported Opus models", async () => {
const client = new ClaudeAgentClient({ logger, resolveBinary: async () => "/test/claude/bin" });
test("lists Claude controls by model capability", async () => {
const client = new ClaudeAgentClient({ logger, resolveVersion: async () => "2.1.284" });
await expect(
client.listControls({
@@ -1191,7 +1189,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1202,7 +1203,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8[1m]",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1213,7 +1217,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8-20260101",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1224,7 +1231,10 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-5",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
options: {},
});
@@ -1234,7 +1244,10 @@ describe("ClaudeAgentSession features", () => {
cwd: process.cwd(),
model: "openrouter/anthropic/claude-opus-4-8",
}),
).resolves.toEqual({ controls: [], options: {} });
).resolves.toEqual({
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
options: {},
});
await expect(
client.listControls({
@@ -1242,7 +1255,10 @@ describe("ClaudeAgentSession features", () => {
cwd: process.cwd(),
model: "claude-sonnet-5",
}),
).resolves.toEqual({ controls: [], options: {} });
).resolves.toEqual({
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
options: {},
});
await expect(
client.listControls({
@@ -50,8 +50,10 @@ import {
import {
CLAUDE_DISABLED_THINKING_OPTION_ID,
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
claudeManifestModelSupportsUltracode,
parseClaudeCodeVersion,
resolveClaudeDisabledThinkingForModel,
supportsIndependentClaudeUltracode,
} from "./model-manifest.js";
import { expandTilde } from "../../../../utils/path.js";
import { parsePartialJsonObject } from "./partial-json.js";
@@ -496,6 +498,7 @@ interface ClaudeAgentSessionOptions {
logger: Logger;
queryFactory?: ClaudeQueryFactory;
resolveBinary: () => Promise<string>;
independentUltracode: boolean;
rewindSdk?: ClaudeRewindSdk;
}
@@ -1618,6 +1621,7 @@ export class ClaudeAgentClient implements AgentClient {
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly resolveVersion: (signal?: AbortSignal) => Promise<string>;
private version: Promise<string | undefined> | undefined;
private readonly rewindSdk: ClaudeRewindSdk;
private readonly scheduleImportDescriptors = createImportDescriptorScheduler(
(candidate: ClaudeSessionCandidate, signal) => this.readImportDescriptor(candidate, signal),
@@ -1661,6 +1665,7 @@ export class ClaudeAgentClient implements AgentClient {
logger: this.logger,
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
rewindSdk: this.rewindSdk,
});
}
@@ -1690,6 +1695,7 @@ export class ClaudeAgentClient implements AgentClient {
logger: this.logger,
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
rewindSdk: this.rewindSdk,
});
await session.ensureHistoryReady();
@@ -1714,6 +1720,7 @@ export class ClaudeAgentClient implements AgentClient {
} catch (error) {
this.logger.warn({ err: error }, "Failed to resolve Claude Code version for model catalog");
}
this.version = Promise.resolve(claudeCodeVersion);
const env = this.buildProviderEnv();
let discoveredModelIds = new Set<string>();
try {
@@ -1770,11 +1777,19 @@ export class ClaudeAgentClient implements AgentClient {
async listControls(config: AgentSessionConfig): Promise<AgentDraftControls> {
return {
controls: buildClaudeControls(this.assertConfig(config).model),
controls: buildClaudeControls(
this.assertConfig(config).model,
await this.supportsIndependentUltracode(),
),
options: config.providerOptions ?? {},
};
}
private async supportsIndependentUltracode(): Promise<boolean> {
this.version ??= this.resolveVersion().catch(() => undefined);
return supportsIndependentClaudeUltracode(await this.version);
}
async listImportableSessions(
options?: ListImportableSessionsOptions & { signal?: AbortSignal },
): Promise<ImportableProviderSession[]> {
@@ -2307,6 +2322,7 @@ class ClaudeAgentSession implements AgentSession {
private readonly logger: Logger;
private readonly queryFactory?: ClaudeQueryFactory;
private readonly resolveBinary: () => Promise<string>;
private readonly independentUltracode: boolean;
private query: Query | null = null;
private readonly runtimeSafety = new ClaudeRuntimeSafety();
private readonly backgroundStops = new Map<string, (outcome: string) => void>();
@@ -2444,6 +2460,7 @@ class ClaudeAgentSession implements AgentSession {
this.logger = options.logger.child({ agentId: this.agentId });
this.queryFactory = options.queryFactory;
this.resolveBinary = options.resolveBinary;
this.independentUltracode = options.independentUltracode;
this.rewindSdk = options.rewindSdk ?? realClaudeRewindSdk;
this.contextUsage = new ClaudeContextUsageState(
getClaudeContextWindowMaxTokens(this.config.model),
@@ -2481,6 +2498,16 @@ class ClaudeAgentSession implements AgentSession {
this.config.providerOptions = { ...config.providerOptions, fast_mode: false };
this.openOptionsPatch = { fast_mode: false };
}
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
// Direct adapter callers can still pass the combined choice.
if (
this.independentUltracode &&
config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
config.providerOptions.ultracode === undefined
) {
this.config.providerOptions = { ...config.providerOptions, ultracode: true };
this.openOptionsPatch.ultracode = true;
}
}
get id(): string | null {
@@ -2488,18 +2515,28 @@ class ClaudeAgentSession implements AgentSession {
}
get controls(): AgentOptionControl[] {
return buildClaudeControls(this.config.model);
return buildClaudeControls(this.config.model, this.independentUltracode);
}
async getRuntimeInfo(): Promise<AgentRuntimeInfo> {
if (this.cachedRuntimeInfo) {
return { ...this.cachedRuntimeInfo };
}
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
const info: AgentRuntimeInfo = {
provider: "claude",
sessionId: this.claudeSessionId,
model: this.lastOptionsModel ?? this.config.model ?? null,
modeId: this.currentMode ?? null,
...(this.independentUltracode &&
this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
? { thinkingOptionId: "xhigh" }
: {}),
...(!this.independentUltracode &&
this.config.thinkingOptionId === "xhigh" &&
this.config.providerOptions.ultracode === true
? { thinkingOptionId: CLAUDE_ULTRACODE_THINKING_OPTION_ID }
: {}),
...(this.lastRuntimeModel
? {
extra: {
@@ -2522,12 +2559,7 @@ class ClaudeAgentSession implements AgentSession {
reduceFinalText: appendOrReplaceGrowingAssistantMessage,
});
this.cachedRuntimeInfo = {
provider: "claude",
sessionId: this.claudeSessionId,
model: this.lastOptionsModel,
modeId: this.currentMode ?? null,
};
this.cachedRuntimeInfo = null;
if (!this.claudeSessionId) {
throw new Error("Session ID not set after run completed");
@@ -2816,9 +2848,14 @@ class ClaudeAgentSession implements AgentSession {
const normalizedModelId =
typeof modelId === "string" && modelId.trim().length > 0 ? modelId.trim() : null;
const activeQuery = await this.ensureQuery();
const previousUltracode = this.resolveUltracodeSetting();
await activeQuery.setModel(normalizedModelId ?? undefined);
this.config.model = normalizedModelId ?? undefined;
this.reconcileThinkingOptionForModel(normalizedModelId);
const ultracode = this.resolveUltracodeSetting();
if (previousUltracode !== ultracode && this.config.providerOptions.ultracode !== undefined) {
await activeQuery.applyFlagSettings({ ultracode: ultracode ?? false });
}
if (this.config.providerOptions.fast_mode) {
const supported = claudeModelSupportsFastMode(this.config.model);
await activeQuery.applyFlagSettings({ fastMode: supported });
@@ -2877,9 +2914,26 @@ class ClaudeAgentSession implements AgentSession {
} else if (isClaudeThinkingOption(normalizedThinkingOptionId)) {
assertClaudeThinkingOptionSupported(this.config.model, normalizedThinkingOptionId);
this.config.thinkingOptionId = normalizedThinkingOptionId;
if (
normalizedThinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
this.config.providerOptions.ultracode !== true
) {
this.config.providerOptions = { ...this.config.providerOptions, ultracode: true };
this.pushEvent({ type: "options_changed", provider: "claude", patch: { ultracode: true } });
}
} else {
throw new Error(`Unknown thinking option: ${normalizedThinkingOptionId}`);
}
this.cachedRuntimeInfo = null;
if (
!this.independentUltracode &&
normalizedThinkingOptionId !== CLAUDE_ULTRACODE_THINKING_OPTION_ID &&
this.config.providerOptions.ultracode === true
) {
this.config.providerOptions = { ...this.config.providerOptions, ultracode: false };
this.pushEvent({ type: "options_changed", provider: "claude", patch: { ultracode: false } });
this.queryRestartNeeded = true;
}
if (!(await this.applyEffortToRunningQuery(previousThinkingOptionId))) {
this.queryRestartNeeded = true;
}
@@ -2896,12 +2950,20 @@ class ClaudeAgentSession implements AgentSession {
previousThinkingOptionId: string | undefined,
): Promise<boolean> {
const effort = this.config.thinkingOptionId;
const previousEffort =
this.independentUltracode && previousThinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
? "xhigh"
: previousThinkingOptionId;
if (!this.query || this.queryRestartNeeded) return false;
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
if (!isClaudeThinkingEffort(previousEffort) || !isClaudeThinkingEffort(effort)) {
return false;
}
try {
await this.query.applyFlagSettings({ effortLevel: effort });
const ultracode = this.resolveUltracodeSetting();
await this.query.applyFlagSettings({
effortLevel: effort,
...(ultracode === undefined ? {} : { ultracode }),
});
return true;
} catch (error) {
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
@@ -2910,14 +2972,13 @@ class ClaudeAgentSession implements AgentSession {
}
async applyOptions(options: ProviderOptions): Promise<void> {
// Every option but Fast is read when the query is built, and replacing a started query would
// end its background work, so once it exists only Fast can change.
// Replacing a started query ends background work, so only flag settings can change live.
if (this.query || this.queryStarting) {
assertChangesAreLive({
provider: "claude",
patch: options,
current: this.config.providerOptions,
live: ["fast_mode"],
live: ["fast_mode", "ultracode"],
});
}
const providerOptions =
@@ -2933,14 +2994,34 @@ class ClaudeAgentSession implements AgentSession {
}
const fastModeChanged =
(providerOptions.fast_mode === true) !== (this.config.providerOptions.fast_mode === true);
if (fastModeChanged) {
await this.query?.applyFlagSettings({ fastMode: providerOptions.fast_mode === true });
const ultracodeChanged = providerOptions.ultracode !== this.config.providerOptions.ultracode;
if (ultracodeChanged) this.assertUltracodeChangeSupported(providerOptions.ultracode);
if (fastModeChanged || ultracodeChanged) {
await this.query?.applyFlagSettings({
...(fastModeChanged ? { fastMode: providerOptions.fast_mode === true } : {}),
...(ultracodeChanged ? { ultracode: providerOptions.ultracode ?? false } : {}),
});
this.cachedRuntimeInfo = null;
}
// Held until the runtime accepts, so a rejected change is retried instead of skipped.
this.config.providerOptions = providerOptions;
}
private assertUltracodeChangeSupported(value: boolean | undefined): void {
if (!this.independentUltracode) {
throw new Error("The Ultracode toggle requires Claude Code 2.1.284 or later");
}
if (this.query && value === undefined) {
// The SDK treats null as Off, so a running process cannot restore inherited settings.
throw new Error("Close the agent to reset Ultracode to Claude's default");
}
if (value === true && !claudeManifestModelSupportsUltracode(this.config.model)) {
throw new Error(
`Claude Ultracode is not available for model '${this.config.model ?? "default"}'`,
);
}
}
getPendingPermissions(): AgentPermissionRequest[] {
return Array.from(this.pendingPermissions.values()).map((entry) => entry.request);
}
@@ -3670,8 +3751,12 @@ class ClaudeAgentSession implements AgentSession {
);
this.queryStarting = false;
const fastMode = this.resolveFastModeSetting();
if (fastMode !== null) {
await this.query.applyFlagSettings({ fastMode });
const ultracode = this.independentUltracode ? this.resolveUltracodeSetting() : undefined;
if (fastMode !== null || ultracode !== undefined) {
await this.query.applyFlagSettings({
...(fastMode === null ? {} : { fastMode }),
...(ultracode === undefined ? {} : { ultracode }),
});
}
// Do not kick off background control-plane queries here. Methods like
// supportedCommands()/setPermissionMode() may execute immediately after
@@ -3729,7 +3814,6 @@ class ClaudeAgentSession implements AgentSession {
private resolveThinkingConfig(): {
thinking: ClaudeOptions["thinking"];
effort: ClaudeOptions["effort"];
ultracode: boolean;
} {
const thinkingOptionId =
this.config.thinkingOptionId && this.config.thinkingOptionId !== "default"
@@ -3737,23 +3821,21 @@ class ClaudeAgentSession implements AgentSession {
: undefined;
assertClaudeThinkingOptionSupported(this.config.model, thinkingOptionId);
if (thinkingOptionId === CLAUDE_DISABLED_THINKING_OPTION_ID) {
return { thinking: { type: "disabled" }, effort: undefined, ultracode: false };
return { thinking: { type: "disabled" }, effort: undefined };
}
if (thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID) {
return {
thinking: { type: "adaptive", display: "summarized" },
effort: "xhigh",
ultracode: true,
};
}
if (thinkingOptionId && isClaudeThinkingEffort(thinkingOptionId)) {
return {
thinking: { type: "adaptive", display: "summarized" },
effort: thinkingOptionId,
ultracode: false,
};
}
return { thinking: undefined, effort: undefined, ultracode: false };
return { thinking: undefined, effort: undefined };
}
private buildAppendedSystemPrompt(): string {
@@ -3790,12 +3872,15 @@ class ClaudeAgentSession implements AgentSession {
}
private async buildOptions(permissionMode: PermissionMode): Promise<ClaudeOptions> {
const { thinking, effort, ultracode } = this.resolveThinkingConfig();
const { thinking, effort } = this.resolveThinkingConfig();
const appendedSystemPrompt = this.buildAppendedSystemPrompt();
// `fast_mode` is a composer control the provider applies through flag settings.
const { fast_mode: _fastMode, ...sdkProviderOptions } = this.config.providerOptions;
const {
fast_mode: _fastMode,
ultracode: _ultracode,
...sdkProviderOptions
} = this.config.providerOptions;
const providerOptions = applyClaudeToolPolicy(sdkProviderOptions, this.config.toolPolicy);
const settingsOptions = await this.buildSettingsOptions(providerOptions, { ultracode });
const settingsOptions = await this.buildSettingsOptions(providerOptions);
const sdkEnv = this.harnessEnvironment;
assertClaudeModeCanRun(permissionMode, sdkEnv);
@@ -3882,18 +3967,18 @@ class ClaudeAgentSession implements AgentSession {
private async buildSettingsOptions(
providerOptions: ClaudeProviderOptions,
input: { ultracode: boolean },
): Promise<Pick<ClaudeOptions, "settings" | "extraArgs"> | Record<string, never>> {
const fastMode = this.resolveFastModeSetting();
const ultracode = this.resolveUltracodeSetting();
// Internal agents do daemon work such as naming a branch, so the user's and
// project's hooks must not run for them.
const disableAllHooks = this.config.internal === true;
if (fastMode === null && !input.ultracode && !disableAllHooks) {
if (fastMode === null && ultracode === undefined && !disableAllHooks) {
return {};
}
const updates = {
...(fastMode === null ? {} : { fastMode }),
...(input.ultracode ? { ultracode: true } : {}),
...(ultracode === undefined ? {} : { ultracode }),
...(disableAllHooks ? { disableAllHooks: true } : {}),
};
// The SDK replaces extraArgs.settings with Options.settings, so a user's
@@ -3909,6 +3994,18 @@ class ClaudeAgentSession implements AgentSession {
};
}
private resolveUltracodeSetting(): boolean | undefined {
const ultracode = this.config.providerOptions.ultracode;
if (!this.independentUltracode) {
return this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID
? true
: ultracode && this.config.thinkingOptionId === "xhigh";
}
if (ultracode === undefined) return undefined;
if (this.config.thinkingOptionId === CLAUDE_ULTRACODE_THINKING_OPTION_ID) return ultracode;
return ultracode && claudeManifestModelSupportsUltracode(this.config.model);
}
private resolveFastModeSetting(): boolean | null {
if (!claudeModelSupportsFastMode(this.config.model)) {
return null;
@@ -1,5 +1,8 @@
import type { AgentOptionControl, AgentOptionToggleControl } from "../../agent-sdk-types.js";
import { claudeManifestModelSupportsFastMode } from "./model-manifest.js";
import {
claudeManifestModelSupportsFastMode,
claudeManifestModelSupportsUltracode,
} from "./model-manifest.js";
export const CLAUDE_FAST_MODE_CONTROL: AgentOptionToggleControl = {
type: "toggle",
@@ -10,10 +13,26 @@ export const CLAUDE_FAST_MODE_CONTROL: AgentOptionToggleControl = {
icon: "zap",
};
const CLAUDE_ULTRACODE_CONTROL: AgentOptionToggleControl = {
type: "toggle",
key: "ultracode",
label: "Ultracode",
description: "Let Claude plan workflows for substantive tasks",
icon: "Workflow",
};
export function claudeModelSupportsFastMode(modelId: string | null | undefined): boolean {
return claudeManifestModelSupportsFastMode(modelId);
}
export function buildClaudeControls(modelId: string | null | undefined): AgentOptionControl[] {
return claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : [];
export function buildClaudeControls(
modelId: string | null | undefined,
independentUltracode: boolean,
): AgentOptionControl[] {
return [
...(claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : []),
...(independentUltracode && claudeManifestModelSupportsUltracode(modelId)
? [{ ...CLAUDE_ULTRACODE_CONTROL }]
: []),
];
}
@@ -226,25 +226,27 @@ function buildThinkingOptions(
effortLevels: readonly ClaudeEffortLevel[] | undefined,
supportsThinkingDisabled: boolean,
defaultThinkingOptionId: ClaudeEffortLevel,
independentUltracode: boolean,
): AgentSelectOption[] | undefined {
if (!effortLevels) {
return undefined;
}
const options: AgentSelectOption[] = [
return [
...(supportsThinkingDisabled ? [{ id: CLAUDE_DISABLED_THINKING_OPTION_ID, label: "Off" }] : []),
...effortLevels.map((id) => ({
id,
label: CLAUDE_EFFORT_LABELS[id],
...(id === defaultThinkingOptionId ? { isDefault: true } : {}),
// COMPAT(claudeUltracodeThinkingOption): added in v0.17.0, remove after 2027-05-18.
...(independentUltracode && id === "xhigh"
? { metadata: { replacesThinkingOptionId: CLAUDE_ULTRACODE_THINKING_OPTION_ID } }
: {}),
})),
...(!independentUltracode && effortLevels.includes("xhigh")
? [{ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" }]
: []),
];
if (effortLevels.includes("xhigh")) {
options.push({ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" });
}
return options;
}
export function getClaudeManifestModels(
@@ -270,6 +272,7 @@ export function getClaudeManifestModels(
model.effortLevels,
model.supportsThinkingDisabled === true,
getDefaultThinkingOptionId(model),
supportsIndependentClaudeUltracode(claudeCodeVersion),
);
const definition: AgentModelDefinition = {
provider: "claude",
@@ -340,6 +343,10 @@ export function parseClaudeCodeVersion(value: string): [number, number, number]
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
}
export function supportsIndependentClaudeUltracode(version: string | undefined): boolean {
return version === undefined || compareVersions(version, "2.1.284") >= 0;
}
export interface ClaudeDisabledThinkingResolution {
supported: boolean;
fallbackThinkingOptionId: string | undefined;
@@ -381,6 +388,14 @@ export function claudeManifestModelSupportsFastMode(modelId: string | null | und
);
}
export function claudeManifestModelSupportsUltracode(modelId: string | null | undefined): boolean {
const normalized = normalizeClaudeRuntimeModelId(modelId);
const model: ClaudeModelManifestEntry | undefined = CLAUDE_MODEL_MANIFEST.find(
(candidate) => candidate.id === normalized,
);
return model?.effortLevels?.includes("xhigh") === true;
}
/**
* Normalize first-party Claude model IDs for manifest capability checks. Provider-prefixed
* runtime IDs intentionally use normalizeClaudeRuntimeModelId instead.
@@ -8,7 +8,6 @@ import { createTestLogger } from "../../../../test-utils/test-logger.js";
import { ClaudeAgentClient } from "./agent.js";
import {
CLAUDE_DISABLED_THINKING_OPTION_ID,
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
claudeManifestModelSupportsFastMode,
normalizeClaudeManifestModelId,
parseClaudeCodeVersion,
@@ -190,7 +189,6 @@ describe("getClaudeModels", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(models.get("claude-sonnet-5")?.thinkingOptions?.map((option) => option.id)).toEqual([
CLAUDE_DISABLED_THINKING_OPTION_ID,
@@ -199,14 +197,7 @@ describe("getClaudeModels", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(
models
.get("claude-sonnet-5")
?.thinkingOptions?.find((option) => option.id === CLAUDE_ULTRACODE_THINKING_OPTION_ID)
?.label,
).toBe("Ultra Code");
expect(models.get("claude-sonnet-5")?.defaultThinkingOptionId).toBe("high");
expect(models.get("claude-sonnet-5[1m]")?.thinkingOptions).toEqual(
models.get("claude-sonnet-5")?.thinkingOptions,
@@ -219,7 +210,6 @@ describe("getClaudeModels", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(models.get("claude-sonnet-4-6")?.thinkingOptions?.map((option) => option.id)).toEqual([
CLAUDE_DISABLED_THINKING_OPTION_ID,
@@ -420,9 +410,12 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
{ id: "xhigh", label: "Extra High" },
{
id: "xhigh",
label: "Extra High",
metadata: { replacesThinkingOptionId: "ultracode" },
},
{ id: "max", label: "Max" },
{ id: CLAUDE_ULTRACODE_THINKING_OPTION_ID, label: "Ultra Code" },
];
const configDir = await createClaudeConfigDir({
model: "us.anthropic.claude-opus-4-7[1m]",
@@ -845,7 +838,6 @@ describe("Claude Fable 5.2 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(claudeManifestModelSupportsFastMode("claude-fable-5-2")).toBe(true);
});
@@ -887,7 +879,6 @@ describe("Claude Opus 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(opus55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -922,7 +913,6 @@ describe("Claude Sonnet 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(sonnet55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -959,7 +949,6 @@ describe("Claude Haiku 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(haiku55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -1016,7 +1005,6 @@ describe("Claude Mythos 5.1 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(
models[0].thinkingOptions?.filter((option) => option.isDefault).map((option) => option.id),
@@ -1088,7 +1076,6 @@ describe("Claude Mythos 5.2 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(claudeManifestModelSupportsFastMode("claude-mythos-5-2")).toBe(true);
});
@@ -45,8 +45,9 @@ const SandboxFilesystemSchema = z
// Claude Agent SDK Options, maintained against @anthropic-ai/claude-agent-sdk 0.3.246.
export const ClaudeProviderOptionsSchema = z
.object({
/** Composer control, not a Claude SDK option: the provider reads it and keeps it out of the SDK options. */
/** Composer controls applied through Claude flag settings. */
fast_mode: z.boolean().optional(),
ultracode: z.boolean().optional(),
allowedTools: z.array(z.string()).optional(),
disallowedTools: z.array(z.string()).optional(),
additionalDirectories: z.array(z.string()).optional(),
@@ -6,6 +6,7 @@ import {
} from "./persisted-config.js";
import { ProviderOverrideSchema } from "./agent/provider-launch-config.js";
import {
convertLegacyClaudeUltracode,
convertLegacyOptions,
foldProfileFeatureValues,
resolveAdapter,
@@ -194,13 +195,21 @@ function foldConfigProfiles<T extends { agentProfiles?: AgentProfile[] }>(input:
options,
});
const identity = (_provider: string, options: Record<string, unknown> | undefined) => options;
const foldWith = (profile: AgentProfile, convertWith: typeof convert) =>
foldProfileFeatureValues({
const foldWith = (profile: AgentProfile, convertWith: typeof convert) => {
const folded = foldProfileFeatureValues<
Pick<AgentProfile, "provider" | "options" | "featureValues">
>({
profile,
stored: held.find((candidate) => candidate.id === profile.id),
source,
convert: convertWith,
});
const { providerOptions, ...converted } = convertLegacyClaudeUltracode(
{ ...folded, thinkingOptionId: profile.thinkingOptionId, providerOptions: folded.options },
resolveAdapter({ provider: profile.provider, extendsOf: (id) => providers?.[id]?.extends }),
);
return { ...converted, options: providerOptions };
};
return {
...config,
agentProfiles: config.agentProfiles.map((profile) => {
@@ -1,193 +0,0 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, onTestFinished, test } from "vitest";
import { DaemonClient } from "../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
import { resolveDaemonVersion } from "../daemon-version.js";
const PROVIDER_ID = "closing-provider";
const PLUGIN_ID = "closing-provider-plugin";
// How the provider ends the session that ran the first turn.
type CloseMode =
// The first turn completes, then the provider closes the session on its own.
| "after-turn"
// The first turn fails and the provider closes the session with the failure.
| "after-failed-turn"
// The provider answers the second prompt by closing the session.
| "on-next-prompt";
async function createClosingProviderPlugin(root: string, mode: CloseMode): Promise<string> {
const directory = path.join(root, "plugin");
await mkdir(directory, { recursive: true });
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({
id: PLUGIN_ID,
requirements: { paseo: `>=${resolveDaemonVersion(import.meta.url)}` },
}),
);
await writeFile(
path.join(directory, "index.server.ts"),
`import type {
ProviderEvent,
ProviderInput,
ProviderRegistration,
} from "@getpaseo/plugin/server/provider";
const CAPABILITIES = ["prompt.message", "session.persistence"];
const MODE = ${JSON.stringify(mode)};
const provider: ProviderRegistration = {
id: ${JSON.stringify(PROVIDER_ID)},
label: "Closing provider",
async connect() {
let listener: ((event: ProviderEvent) => void) | null = null;
const emit = (event: ProviderEvent) => listener?.(event);
let turn = 0;
const closed = new Set<string>();
return {
version: 1,
capabilities: CAPABILITIES,
async send(input: ProviderInput) {
if (input.type === "catalog") {
emit({
type: "catalog",
requestId: input.requestId,
catalog: {
models: [{ id: "closing-model", label: "Closing model" }],
modes: [],
thinkingOptions: [],
defaultModel: "closing-model",
},
});
return;
}
if (input.type === "session.open") {
emit({
type: "session.opened",
requestId: input.requestId,
sessionId: input.sessionId,
capabilities: CAPABILITIES,
restoration: "core",
persistence: { version: 1, data: { token: "root" } },
cwd: input.config.cwd,
});
emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
return;
}
if (input.type === "session.prompt") {
turn += 1;
if (MODE === "on-next-prompt" && turn === 2) {
closed.add(input.sessionId);
emit({ type: "session.closed", sessionId: input.sessionId });
return;
}
const turnId = "turn-" + turn;
emit({
type: "session.prompt_result",
sessionId: input.sessionId,
clientMessageId: input.prompt.clientMessageId,
result: { type: "turn", turnId },
});
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "started" });
if (MODE === "after-failed-turn" && turn === 1) {
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "failed", error: { message: "Provider turn failed" } });
emit({ type: "session.closed", sessionId: input.sessionId, error: { message: "Provider turn failed" } });
return;
}
emit({
type: "timeline.item",
sessionId: input.sessionId,
item: { type: "assistant_message", id: "answer-" + turn, text: "Done " + turn },
});
emit({ type: "session.turn", sessionId: input.sessionId, turnId, state: "completed" });
if (MODE === "after-turn" && turn === 1) {
emit({ type: "session.closed", sessionId: input.sessionId });
}
return;
}
if (input.type === "session.close") {
if (!closed.has(input.sessionId)) emit({ type: "session.closed", sessionId: input.sessionId });
}
if ("requestId" in input) {
emit({ type: "request.completed", requestId: input.requestId });
}
},
onEvent(next: (event: ProviderEvent) => void) {
listener = next;
return () => {
if (listener === next) listener = null;
};
},
async close() {},
};
},
};
export default function contribute(server: { registerProvider(p: ProviderRegistration): void }) {
server.registerProvider(provider);
return () => undefined;
}`,
);
return directory;
}
test.each<CloseMode>(["after-turn", "after-failed-turn", "on-next-prompt"])(
"an agent whose provider session closed (%s) runs its next prompt",
async (mode) => {
const root = await mkdtemp(path.join(tmpdir(), "plugin-provider-closed-session-"));
onTestFinished(() =>
rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
);
const pluginDirectory = await createClosingProviderPlugin(root, mode);
const workspace = path.join(root, "workspace");
await mkdir(workspace, { recursive: true });
const daemon = await createTestPaseoDaemon({
paseoHomeRoot: path.join(root, "daemon"),
staticDir: path.join(root, "static"),
pluginsEnabled: true,
plugins: {
[PLUGIN_ID]: { source: "directory", path: pluginDirectory, enabled: true },
},
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.9.1",
});
onTestFinished(async () => {
await client.close();
await daemon.close();
});
await client.connect();
await client.fetchAgents({ subscribe: {} });
const agent = await client.createAgent({
provider: PROVIDER_ID,
model: "closing-model",
cwd: workspace,
title: "Closing provider agent",
});
await client.sendMessage(agent.id, "first");
await client.waitForFinish(agent.id, 30_000);
// Before the fix, reopening tried to close the session the provider had already
// closed, failed, and rejected this send with "Provider session <id> is stale".
await client.sendMessage(agent.id, "second");
expect((await client.waitForFinish(agent.id, 30_000)).status).toBe("idle");
const timeline = await client.fetchAgentTimeline(agent.id, {
direction: "tail",
limit: 0,
projection: "canonical",
});
const text = JSON.stringify(timeline.entries);
// In on-next-prompt the provider closed the session on prompt 2, so the reopened
// session answers the retried prompt as its third.
expect(text).toContain(mode === "on-next-prompt" ? "Done 3" : "Done 2");
expect(text).not.toMatch(/Provider session \S+ (closed|is stale)/);
},
60_000,
);
@@ -587,29 +587,6 @@ describe("WorkspaceGitServiceImpl", () => {
await service.dispose();
});
test("a client reconnecting within the release grace reuses the warm target", async () => {
const getCheckoutStatus = vi.fn(buildDefaultTestServiceDeps().getCheckoutStatus);
const service = createService({ getCheckoutStatus });
try {
const first = service.registerWorkspace({ cwd: REPO_CWD }, () => {});
const snapshot = await service.getSnapshot(REPO_CWD);
await waitForObservationToSettle(service, 1);
first.unsubscribe();
expect(service.getMetrics().workspaceTargetCount).toBe(1);
const reads = getCheckoutStatus.mock.calls.length;
const second = service.registerWorkspace({ cwd: REPO_CWD }, () => {});
await expect(service.getSnapshot(REPO_CWD)).resolves.toEqual(snapshot);
expect(getCheckoutStatus).toHaveBeenCalledTimes(reads);
second.unsubscribe();
await vi.advanceTimersByTimeAsync(90_000);
expect(service.getMetrics().workspaceTargetCount).toBe(0);
} finally {
await service.dispose();
}
});
test("onSnapshotUpdated delivers without workspace subscribers and can unsubscribe", async () => {
const service = createService();
const snapshots: WorkspaceGitRuntimeSnapshot[] = [];
@@ -646,7 +623,6 @@ describe("WorkspaceGitServiceImpl", () => {
const service = new WorkspaceGitServiceImpl({
logger: createLogger() as unknown as pino.Logger,
paseoHome: "/tmp/paseo-test",
releaseGraceMs: 0,
deps: {
...buildDefaultTestServiceDeps(),
getPullRequestStatus: async () => {
@@ -81,9 +81,6 @@ import { checkoutLiteFromGitSnapshot } from "./workspace-registry-model.js";
import { createWatcherLivenessCanary } from "./watcher-liveness-canary.js";
const WORKSPACE_GIT_WATCH_DEBOUNCE_MS = 1_000;
// A target outlives its last listener this long, so a reconnecting client reuses its snapshot
// and watchers instead of re-reading every checkout.
const WORKSPACE_GIT_RELEASE_GRACE_MS = 90_000;
export const BACKGROUND_GIT_FETCH_INTERVAL_MS = 180_000;
const FETCH_METADATA_ECHO_TTL_MS = 5_000;
export const WORKSPACE_GIT_OBSERVATION_REENSURE_INTERVAL_MS = 60_000;
@@ -444,8 +441,6 @@ interface WorkspaceGitServiceOptions {
worktreesRoot?: string;
fileObserver?: FileObserver;
deps?: Partial<WorkspaceGitServiceDependencies>;
/** How long a workspace target outlives its last listener; 0 releases it immediately. */
releaseGraceMs?: number;
}
class WorkspaceGitServiceDisposedError extends Error {
@@ -468,7 +463,6 @@ interface WorkspaceGitTarget {
gitDirPaths: GitObservationPaths | null;
cwd: string;
listeners: Set<WorkspaceGitListener>;
releaseTimer: NodeJS.Timeout | null;
workingTreeWatchTarget: WorkingTreeWatchTarget | null;
debounceTimer: NodeJS.Timeout | null;
pendingDebounceRequest: WorkspaceGitRefreshRequest | null;
@@ -663,7 +657,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private readonly logger: pino.Logger;
private readonly paseoHome: string;
private readonly worktreesRoot: string | undefined;
private readonly releaseGraceMs: number;
private readonly fileObserver: FileObserver;
private readonly deps: WorkspaceGitServiceDependencies;
private readonly forgeResolver: ForgeResolver;
@@ -717,7 +710,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
this.logger = options.logger.child({ module: "workspace-git-service" });
this.paseoHome = options.paseoHome;
this.worktreesRoot = options.worktreesRoot;
this.releaseGraceMs = options.releaseGraceMs ?? WORKSPACE_GIT_RELEASE_GRACE_MS;
this.fileObserver = options.fileObserver ?? createFileObserver();
this.deps = resolveWorkspaceGitServiceDeps(
this.fileObserver.subscribe.bind(this.fileObserver),
@@ -741,7 +733,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
this.assertNotDisposed();
const cwd = resolve(params.cwd);
const target = this.ensureWorkspaceTarget(cwd);
this.cancelWorkspaceRelease(target);
target.listeners.add(listener);
if (target.folderMissing) {
void this.resumeWorkspaceIfFolderRestored(target);
@@ -1327,7 +1318,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
gitDirPaths: null,
cwd,
listeners: new Set(),
releaseTimer: null,
workingTreeWatchTarget: null,
debounceTimer: null,
pendingDebounceRequest: null,
@@ -3075,9 +3065,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (!target || target.closed || this.workspaceTargets.get(target.cwd) !== target) {
return;
}
if (options.origin === "observation" && this.releaseChangedWarmTarget(target)) {
return;
}
const request = this.buildScheduledRefreshRequest(options);
target.pendingDebounceRequest = this.mergeRefreshRequests(
@@ -3364,9 +3351,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
if (target.closed || this.workspaceTargets.get(target.cwd) !== target) {
return;
}
if (request.origin === "observation" && this.releaseChangedWarmTarget(target)) {
return;
}
try {
await this.requestWorkspaceSnapshot(target, request);
} catch (error) {
@@ -4120,52 +4104,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
return;
}
if (this.releaseGraceMs <= 0 || !this.isWorkspaceObservationEstablished(target)) {
this.removeWorkspaceTarget(target);
return;
}
// Keep the snapshot and watchers warm for a reconnecting client; stop forge polling now.
this.stopForgePrStatusPollForTarget(target);
this.cancelWorkspaceRelease(target);
target.releaseTimer = setTimeout(() => {
target.releaseTimer = null;
if (
!target.closed &&
target.listeners.size === 0 &&
this.workspaceTargets.get(target.cwd) === target
) {
this.removeWorkspaceTarget(target);
}
}, this.releaseGraceMs);
target.releaseTimer.unref?.();
}
/** Only a fully watched target stays warm; one still recovering a watcher is released now. */
private isWorkspaceObservationEstablished(target: WorkspaceGitTarget): boolean {
const repoTarget = target.repoGitRoot ? this.repoTargets.get(target.repoGitRoot) : undefined;
return Boolean(
target.latestSnapshot &&
!target.folderMissing &&
target.workingTreeWatchTarget?.subscription &&
repoTarget?.subscription,
);
}
/** A change seen while nobody listens ends the grace: the next consumer re-reads, nobody pays now. */
private releaseChangedWarmTarget(target: WorkspaceGitTarget): boolean {
if (target.listeners.size > 0 || !target.releaseTimer) {
return false;
}
this.cancelWorkspaceRelease(target);
this.removeWorkspaceTarget(target);
return true;
}
private cancelWorkspaceRelease(target: WorkspaceGitTarget): void {
if (target.releaseTimer) {
clearTimeout(target.releaseTimer);
target.releaseTimer = null;
}
}
private removeWorkspaceTarget(target: WorkspaceGitTarget): void {
@@ -4232,7 +4171,6 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
private closeWorkspaceTarget(target: WorkspaceGitTarget): void {
target.closed = true;
this.cancelWorkspaceRelease(target);
this.stopWorkspaceObservation(target);
target.listeners.clear();
}
File diff suppressed because one or more lines are too long
-6
View File
@@ -86,12 +86,6 @@ const patchedPackages = [
nodeModulesPath: "node_modules/@mattermost/react-native-paste-input",
patchPrefix: "@mattermost+react-native-paste-input+",
},
// Backport of https://github.com/mermaid-js/mermaid/pull/8459 (lexer half): a flowchart label
// with an "@" parses. The patch header has the details. Remove when the app uses mermaid 12.
{
nodeModulesPath: "node_modules/mermaid",
patchPrefix: "mermaid+",
},
{
nodeModulesPath: "packages/server/node_modules/@opencode-ai/sdk",
patchPrefix: "@opencode-ai+sdk+",