Compare commits

..
Author SHA1 Message Date
bcf52f93b1 fix(app): draw Mermaid flowcharts whose labels contain an @ (#10165)
Mermaid 11's lexer reads an edge id (`e1@-->`) from any run of
non-space characters ending in "@". In `F[@mention] --> G` that run
starts at the node id and crosses the label's opening bracket, so the
parse fails and the card falls back to the source. Backport the lexer
half of mermaid-js/mermaid#8459, which stops the edge id at the node
shape characters, onto the pinned mermaid 11.16.0 and rebuild the
runtime. Moving to mermaid 12 instead changes the default layout and
look of every diagram and raises the browser floor, so it stays a
separate decision.

Closes #10157

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: monarchmaisuriya <37824914+monarchmaisuriya@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 21:52:18 +00:00
paseo-bot[bot]andClaude Opus 5.5 d8c98400fb fix(server): reopen a plugin agent whose provider closed its session (#10153)
When a plugin provider closed a session with session.closed, the next
prompt went stale and Paseo tried to reopen the agent. The reopen first
closes the old session, and that close sent session.close for a session
the plugin runtime had already forgotten. The send failed with "Unknown
provider session", the reopen stopped, and the prompt was rejected with
"Provider session <id> is stale after its plugin reloaded". Every later
prompt failed the same way.

A session that the provider closed now skips the native close and only
drops its routing, so the reopen continues and the prompt runs.

Closes #10151

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 20:45:55 +00:00
VladimirGVPandVladimirGVP 77392d3c1b perf(workspace-git): retain warm targets across short reconnects (#10142)
Co-authored-by: VladimirGVP <322008768+VladimirGVP@users.noreply.github.com>
2026-11-18 20:18:30 +00:00
paseo-bot[bot] 8edccf0503 test(app): press a fork trigger again when a streamed line moves it (#10156)
"forks a streaming assistant turn without interrupting it" pressed the
in-flight turn's fork trigger once and waited for the menu. While the
chat is shorter than the viewport, each streamed line moves the trigger
down. A line that arrives between the press and the release moves the
trigger out from under the pointer, the press opens nothing, and the
wait for "Fork in a new tab" timed out.

openForkMenu now presses the trigger until its menu shows.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-18 18:51:59 +00:00
Okan YILDIRIM ac633eb096 fix(markdown): wait for the host before reading a chat image (#10111)
When the app opens straight into a chat on a host it hasn't connected to yet,
such as a page reload or a cold start on an agent route, it renders the cached
messages before the host's client exists. useMarkdownSource enabled the image
read anyway, with no client to read through, so it failed with "Image
unavailable". The query's retries cover a host that connects within about
seven seconds. After that the read stays failed and the image collapses to its
alt text. The query key doesn't include the client, so the client's arrival
never starts another read, and the image stays as alt text after the host
connects.

Markdown that belongs to a host, which has a serverId, now waits for that
host's client before it reads. Until the host connects the image keeps its
pending placeholder, and once the client arrives the query runs and reads the
file. Markdown with no host, such as the changelog, has no client to wait for
and still falls back to its alt text.
2026-11-18 15:59:10 +00:00
40 changed files with 556 additions and 591 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 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
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
`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,11 +56,20 @@ 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> {
await trigger.click();
await expect(page.getByRole("menuitem", { name: "Fork in a new tab" })).toBeVisible({
timeout: 10_000,
});
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 });
}
export async function openMostRecentAssistantForkMenu(page: Page): Promise<void> {
@@ -30,25 +30,6 @@ 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,7 +47,6 @@ 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;
}
@@ -113,17 +112,6 @@ 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,6 +215,32 @@ 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")}`;
@@ -0,0 +1,103 @@
// @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,7 +81,10 @@ export function useMarkdownSource(
const results = useFetchQueries(
acquisitions.map((acquisition, index) => ({
queryKey: ["markdownImage", acquisition?.key ?? sources[index]],
enabled: acquisition !== null,
// 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),
immutableWhen: () => true,
dataShape: "value",
gcTime: 0,
@@ -82,10 +82,10 @@ describe("ComposerControls", () => {
expect(trigger.textContent).not.toContain("Large");
});
it("keeps the toolbar toggle name and flips it on press", () => {
it("flips a toggle on press in the toolbar", () => {
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,12 +94,6 @@ 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(
@@ -163,8 +157,6 @@ describe("ComposerControls", () => {
});
const FAST_ON = { fast_mode: true };
const ULTRACODE_ON = { ultracode: true };
const ignoreOption = () => undefined;
describe("provider option controls", () => {
const fastMode: AgentOptionControl = {
@@ -181,11 +173,7 @@ describe("provider option controls", () => {
onSetOption: (key: string, value: unknown) => void;
}) {
const optionControls = React.useMemo(
() => ({
controls: [fastMode, { key: "ultracode", label: "Ultracode", type: "toggle" as const }],
options,
onSetOption,
}),
() => ({ controls: [fastMode], options, onSetOption }),
[onSetOption, options],
);
const items = useAgentControlItems({
@@ -209,9 +197,4 @@ 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" | "purple" | "yellow";
highlight?: "blue" | "green" | "yellow";
/** Defaults to the title, or to "title: choice" on an icon-only select. */
tooltip?: string;
/** Defaults to the tooltip. */
@@ -393,7 +393,6 @@ 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,8 +33,6 @@ function getFeatureHighlight(
function toFeatureItem(
control: AgentOptionControl,
optionControls: ComposerOptionControls,
surface: ComposerControlSurface,
t: TFunction,
): ComposerControlItem {
const { options, onSetOption } = optionControls;
const base = {
@@ -45,15 +43,11 @@ 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:
control.tooltip ??
(surface === "toolbar" ? `${control.label}: ${stateLabel}` : control.label),
value: enabled,
tooltip: getControlTooltip(control),
value: readToggleOption(control, options),
onChange: (value) => onSetOption(control.key, value),
};
}
@@ -98,11 +92,9 @@ export function useAgentControlItems({
const features = useMemo(
() =>
optionControls
? optionControls.controls.map((control) =>
toFeatureItem(control, optionControls, surface, t),
)
? optionControls.controls.map((control) => toFeatureItem(control, optionControls))
: [],
[optionControls, surface, t],
[optionControls],
);
return { thinking: thinkingItem, features };
}
@@ -1316,7 +1316,8 @@ export function DraftAgentControls({
return toThinkingControlOptions(thinkingOptions);
}, [thinkingOptions]);
const effectiveSelectedThinkingOption = selectedThinkingOptionId || mappedThinkingOptions[0]?.id;
const effectiveSelectedThinkingOption =
selectedThinkingOptionId || mappedThinkingOptions[0]?.id || undefined;
const modelOptions = useMemo<AgentControlOption[]>(
() =>
@@ -20,7 +20,6 @@ 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" | "purple" | "yellow";
export type FeatureHighlightColor = "blue" | "default" | "green" | "yellow";
export type AgentControlHintKey =
| "agentControls.hints.thinking"
| "agentControls.hints.model"
@@ -48,8 +48,6 @@ 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:
+2 -20
View File
@@ -22,7 +22,6 @@ 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";
@@ -294,7 +293,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
options: draftOptions,
shownOptions: draftShownOptions,
setOption: setDraftOption,
retainLegacyUltracode,
applyProfile: applyProfileOptions,
} = useDraftProviderOptions({
serverId: formState.selectedServerId,
@@ -314,11 +312,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
},
[applyProfileOptions, formState],
);
const setDraftThinking = useCallback(
(thinkingOptionId: string) =>
formState.setThinkingOptionFromUser(thinkingOptionId, retainLegacyUltracode()),
[formState, retainLegacyUltracode],
);
const commandDraft = useMemo(
() =>
@@ -337,18 +330,8 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
return null;
}
// 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,
...formState,
workingDir,
effectiveModeId,
effectiveModelId,
@@ -356,7 +339,7 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
providerOptions: draftOptions,
metadata,
agentControls: buildDraftAgentControls({
formState: draftForm,
formState,
optionControls: draftOptionControls,
options: draftShownOptions,
onSetOption: setDraftOption,
@@ -377,7 +360,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
draftOptions,
draftShownOptions,
setDraftOption,
setDraftThinking,
applyDraftAgentProfile,
formState,
metadata,
@@ -4,7 +4,6 @@ import type {
AgentMode,
AgentModelDefinition,
AgentProvider,
ProviderOptions,
ProviderSnapshotEntry,
} from "@getpaseo/protocol/agent-types";
import { buildProviderDefinitions } from "@/utils/provider-definitions";
@@ -59,7 +58,7 @@ export interface UseAgentFormStateResult {
selectedModel: string;
setModelFromUser: (modelId: string) => void;
selectedThinkingOptionId: string;
setThinkingOptionFromUser: (thinkingOptionId: string, retainedOptions?: ProviderOptions) => void;
setThinkingOptionFromUser: (thinkingOptionId: string) => void;
workingDir: string;
providerDefinitions: AgentProviderDefinition[];
providerDefinitionMap: Map<AgentProvider, AgentProviderDefinition>;
@@ -420,7 +419,7 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
);
const setThinkingOptionFromUser = useCallback(
(thinkingOptionId: string, retainedOptions?: ProviderOptions) => {
(thinkingOptionId: string) => {
dispatch({ type: "SET_THINKING_OPTION_FROM_USER", thinkingOptionId });
const { provider, model: modelId } = formStore.getState().form;
if (provider && modelId) {
@@ -432,7 +431,6 @@ export function useAgentFormState(options: UseAgentFormStateOptions): UseAgentFo
thinkingByModel: {
[modelId]: thinkingOptionId,
},
options: retainedOptions,
},
}),
);
@@ -69,14 +69,6 @@ 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,
@@ -137,7 +129,6 @@ export function useDraftProviderOptions(input: {
options: ownOptions,
shownOptions,
setOption,
retainLegacyUltracode,
applyProfile: model.applyProfile,
};
}
@@ -167,14 +167,6 @@ 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;
@@ -191,9 +183,6 @@ export function resolveThinkingOptionId(args: {
) {
return normalizedThinkingOptionId;
}
if (findThinkingOptionReplacement(thinkingOptions, normalizedThinkingOptionId)) {
return normalizedThinkingOptionId;
}
return effectiveModel?.defaultThinkingOptionId ?? thinkingOptions[0]?.id ?? "";
}
@@ -96,7 +96,6 @@ function scheduleOnHost(input: {
serverName: string;
cwd: string;
model: string;
provider?: string;
thinkingOptionId?: string | null;
cadence?: ScheduleSummary["cadence"];
}): TestSchedule {
@@ -110,7 +109,7 @@ function scheduleOnHost(input: {
target: {
type: "new-agent",
config: {
provider: input.provider ?? "mock",
provider: "mock",
cwd: input.cwd,
model: input.model,
modeId: "load-test",
@@ -187,56 +186,6 @@ 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,7 +14,6 @@ import {
import { filterSelectableModels, findModelByReference } from "@/provider-selection/model-catalog";
import {
buildProviderDefinitionMapForStatuses,
findThinkingOptionReplacement,
INITIAL_USER_MODIFIED,
RESOLVABLE_PROVIDER_STATUSES,
resolveDefaultModelId,
@@ -274,14 +273,7 @@ function resolveThinkingOptions(
modelId: string,
): NonNullable<AgentModelDefinition["thinkingOptions"]> {
const model = resolveEffectiveModel(resolveAvailableModels(entries, provider), modelId);
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;
return model?.thinkingOptions ?? [];
}
function resolveModelDisplay(input: {
@@ -92,11 +92,7 @@ const pinnedTheme = {
const testTheme = {
...lightTheme,
...pinnedTheme,
colors: {
...lightTheme.colors,
...pinnedTheme.colors,
palette: { ...lightTheme.colors.palette, ...pinnedTheme.colors.palette },
},
colors: { ...lightTheme.colors, ...pinnedTheme.colors },
};
type StyleFactory<T> = (theme: typeof testTheme) => T;
@@ -69,7 +69,6 @@ import {
applyProviderOptionsPatch,
exposeFeatureValuesToHook,
convertLegacyOptions,
convertLegacyClaudeUltracode,
MalformedLegacyOptionError,
resolveAdapter,
foldHookFeatureValues,
@@ -6195,15 +6194,7 @@ export class AgentManager {
private withConvertedOptions(config: AgentSessionConfig): AgentSessionConfig {
const providerOptions = this.convertLegacyOptions(config.provider, 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));
return providerOptions === config.providerOptions ? config : { ...config, providerOptions };
}
private async prepareSessionConfig(
@@ -1,19 +1,6 @@
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,6 +605,8 @@ 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 }> = [];
@@ -723,7 +725,7 @@ class ProviderRuntimeSession {
async close(): Promise<void> {
this.history.length = 0;
if (this.restoration === "parent") {
if (this.restoration === "parent" || this.closedByProvider) {
this.runtime.removeSession(this.id, this.providerSessionId);
return;
}
@@ -788,6 +790,7 @@ 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"]);
).toEqual(["off", "low", "medium", "high", "xhigh", "max", "ultracode"]);
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,7 +26,6 @@ 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,
@@ -312,29 +311,6 @@ 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,7 +51,6 @@ 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;
@@ -517,13 +516,7 @@ export class ProviderSnapshotManager {
}
return validateAgentConfigurationAgainstProvider({
input: convertLegacyClaudeUltracode(
input,
resolveAdapter({
provider: input.provider,
extendsOf: (id) => this.generation.definitions[id]?.derivedFromProviderId,
}),
),
input,
provider,
});
}
@@ -2,7 +2,6 @@ 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";
@@ -19,7 +18,6 @@ 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>;
@@ -74,9 +72,6 @@ class ForegroundQuery {
}
async setPermissionMode() {}
async setModel() {}
async applyFlagSettings(settings: Parameters<Query["applyFlagSettings"]>[0]) {
this.flagSettings.push(settings);
}
async supportedCommands() {
return [];
}
@@ -161,122 +156,3 @@ 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,20 +543,21 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
return models.find((model) => model.id === modelId)?.thinkingOptions?.map(({ id }) => id);
};
expect(getThinkingIds("claude-opus-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-5")).toContain("ultracode");
expect(getThinkingIds("claude-mythos-5-1")).toEqual([
"low",
"medium",
"high",
"xhigh",
"max",
"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-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-sonnet-5")).toContain("xhigh");
expect(getThinkingIds("claude-sonnet-5")).not.toContain("ultracode");
expect(getThinkingIds("claude-sonnet-5")).toContain("ultracode");
expect(getThinkingIds("claude-haiku-5-5")).toEqual([
"off",
"low",
@@ -564,11 +565,12 @@ 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]")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7")).not.toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7[1m]")).toContain("ultracode");
expect(getThinkingIds("claude-opus-4-7")).toContain("ultracode");
expect(getThinkingIds("claude-sonnet-4-6")).not.toContain("ultracode");
} finally {
await fs.rm(emptyConfigDir, { recursive: true, force: true });
@@ -1179,8 +1181,8 @@ describe("ClaudeAgentSession features", () => {
await session.close();
});
test("lists Claude controls by model capability", async () => {
const client = new ClaudeAgentClient({ logger, resolveVersion: async () => "2.1.284" });
test("lists fast mode only for supported Opus models", async () => {
const client = new ClaudeAgentClient({ logger, resolveBinary: async () => "/test/claude/bin" });
await expect(
client.listControls({
@@ -1189,10 +1191,7 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8",
}),
).resolves.toEqual({
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
options: {},
});
@@ -1203,10 +1202,7 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8[1m]",
}),
).resolves.toEqual({
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
options: {},
});
@@ -1217,10 +1213,7 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-4-8-20260101",
}),
).resolves.toEqual({
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
options: {},
});
@@ -1231,10 +1224,7 @@ describe("ClaudeAgentSession features", () => {
model: "claude-opus-5",
}),
).resolves.toEqual({
controls: [
expect.objectContaining({ key: "fast_mode", type: "toggle" }),
expect.objectContaining({ key: "ultracode", type: "toggle" }),
],
controls: [expect.objectContaining({ key: "fast_mode", type: "toggle" })],
options: {},
});
@@ -1244,10 +1234,7 @@ describe("ClaudeAgentSession features", () => {
cwd: process.cwd(),
model: "openrouter/anthropic/claude-opus-4-8",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
options: {},
});
).resolves.toEqual({ controls: [], options: {} });
await expect(
client.listControls({
@@ -1255,10 +1242,7 @@ describe("ClaudeAgentSession features", () => {
cwd: process.cwd(),
model: "claude-sonnet-5",
}),
).resolves.toEqual({
controls: [expect.objectContaining({ key: "ultracode", type: "toggle" })],
options: {},
});
).resolves.toEqual({ controls: [], options: {} });
await expect(
client.listControls({
@@ -50,10 +50,8 @@ 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";
@@ -498,7 +496,6 @@ interface ClaudeAgentSessionOptions {
logger: Logger;
queryFactory?: ClaudeQueryFactory;
resolveBinary: () => Promise<string>;
independentUltracode: boolean;
rewindSdk?: ClaudeRewindSdk;
}
@@ -1621,7 +1618,6 @@ 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),
@@ -1665,7 +1661,6 @@ export class ClaudeAgentClient implements AgentClient {
logger: this.logger,
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
rewindSdk: this.rewindSdk,
});
}
@@ -1695,7 +1690,6 @@ export class ClaudeAgentClient implements AgentClient {
logger: this.logger,
queryFactory: this.queryFactory,
resolveBinary: this.resolveBinary,
independentUltracode: await this.supportsIndependentUltracode(),
rewindSdk: this.rewindSdk,
});
await session.ensureHistoryReady();
@@ -1720,7 +1714,6 @@ 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 {
@@ -1777,19 +1770,11 @@ export class ClaudeAgentClient implements AgentClient {
async listControls(config: AgentSessionConfig): Promise<AgentDraftControls> {
return {
controls: buildClaudeControls(
this.assertConfig(config).model,
await this.supportsIndependentUltracode(),
),
controls: buildClaudeControls(this.assertConfig(config).model),
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[]> {
@@ -2322,7 +2307,6 @@ 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>();
@@ -2460,7 +2444,6 @@ 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),
@@ -2498,16 +2481,6 @@ 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 {
@@ -2515,28 +2488,18 @@ class ClaudeAgentSession implements AgentSession {
}
get controls(): AgentOptionControl[] {
return buildClaudeControls(this.config.model, this.independentUltracode);
return buildClaudeControls(this.config.model);
}
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: {
@@ -2559,7 +2522,12 @@ class ClaudeAgentSession implements AgentSession {
reduceFinalText: appendOrReplaceGrowingAssistantMessage,
});
this.cachedRuntimeInfo = null;
this.cachedRuntimeInfo = {
provider: "claude",
sessionId: this.claudeSessionId,
model: this.lastOptionsModel,
modeId: this.currentMode ?? null,
};
if (!this.claudeSessionId) {
throw new Error("Session ID not set after run completed");
@@ -2848,14 +2816,9 @@ 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 });
@@ -2914,26 +2877,9 @@ 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;
}
@@ -2950,20 +2896,12 @@ 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(previousEffort) || !isClaudeThinkingEffort(effort)) {
if (!isClaudeThinkingEffort(previousThinkingOptionId) || !isClaudeThinkingEffort(effort)) {
return false;
}
try {
const ultracode = this.resolveUltracodeSetting();
await this.query.applyFlagSettings({
effortLevel: effort,
...(ultracode === undefined ? {} : { ultracode }),
});
await this.query.applyFlagSettings({ effortLevel: effort });
return true;
} catch (error) {
this.logger.warn({ err: error, effort }, "Claude did not take a live effort change");
@@ -2972,13 +2910,14 @@ class ClaudeAgentSession implements AgentSession {
}
async applyOptions(options: ProviderOptions): Promise<void> {
// Replacing a started query ends background work, so only flag settings can change live.
// 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.
if (this.query || this.queryStarting) {
assertChangesAreLive({
provider: "claude",
patch: options,
current: this.config.providerOptions,
live: ["fast_mode", "ultracode"],
live: ["fast_mode"],
});
}
const providerOptions =
@@ -2994,34 +2933,14 @@ class ClaudeAgentSession implements AgentSession {
}
const fastModeChanged =
(providerOptions.fast_mode === true) !== (this.config.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 } : {}),
});
if (fastModeChanged) {
await this.query?.applyFlagSettings({ fastMode: providerOptions.fast_mode === true });
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);
}
@@ -3751,12 +3670,8 @@ class ClaudeAgentSession implements AgentSession {
);
this.queryStarting = false;
const fastMode = this.resolveFastModeSetting();
const ultracode = this.independentUltracode ? this.resolveUltracodeSetting() : undefined;
if (fastMode !== null || ultracode !== undefined) {
await this.query.applyFlagSettings({
...(fastMode === null ? {} : { fastMode }),
...(ultracode === undefined ? {} : { ultracode }),
});
if (fastMode !== null) {
await this.query.applyFlagSettings({ fastMode });
}
// Do not kick off background control-plane queries here. Methods like
// supportedCommands()/setPermissionMode() may execute immediately after
@@ -3814,6 +3729,7 @@ class ClaudeAgentSession implements AgentSession {
private resolveThinkingConfig(): {
thinking: ClaudeOptions["thinking"];
effort: ClaudeOptions["effort"];
ultracode: boolean;
} {
const thinkingOptionId =
this.config.thinkingOptionId && this.config.thinkingOptionId !== "default"
@@ -3821,21 +3737,23 @@ class ClaudeAgentSession implements AgentSession {
: undefined;
assertClaudeThinkingOptionSupported(this.config.model, thinkingOptionId);
if (thinkingOptionId === CLAUDE_DISABLED_THINKING_OPTION_ID) {
return { thinking: { type: "disabled" }, effort: undefined };
return { thinking: { type: "disabled" }, effort: undefined, ultracode: false };
}
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 };
return { thinking: undefined, effort: undefined, ultracode: false };
}
private buildAppendedSystemPrompt(): string {
@@ -3872,15 +3790,12 @@ class ClaudeAgentSession implements AgentSession {
}
private async buildOptions(permissionMode: PermissionMode): Promise<ClaudeOptions> {
const { thinking, effort } = this.resolveThinkingConfig();
const { thinking, effort, ultracode } = this.resolveThinkingConfig();
const appendedSystemPrompt = this.buildAppendedSystemPrompt();
const {
fast_mode: _fastMode,
ultracode: _ultracode,
...sdkProviderOptions
} = this.config.providerOptions;
// `fast_mode` is a composer control the provider applies through flag settings.
const { fast_mode: _fastMode, ...sdkProviderOptions } = this.config.providerOptions;
const providerOptions = applyClaudeToolPolicy(sdkProviderOptions, this.config.toolPolicy);
const settingsOptions = await this.buildSettingsOptions(providerOptions);
const settingsOptions = await this.buildSettingsOptions(providerOptions, { ultracode });
const sdkEnv = this.harnessEnvironment;
assertClaudeModeCanRun(permissionMode, sdkEnv);
@@ -3967,18 +3882,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 && ultracode === undefined && !disableAllHooks) {
if (fastMode === null && !input.ultracode && !disableAllHooks) {
return {};
}
const updates = {
...(fastMode === null ? {} : { fastMode }),
...(ultracode === undefined ? {} : { ultracode }),
...(input.ultracode ? { ultracode: true } : {}),
...(disableAllHooks ? { disableAllHooks: true } : {}),
};
// The SDK replaces extraArgs.settings with Options.settings, so a user's
@@ -3994,18 +3909,6 @@ 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,8 +1,5 @@
import type { AgentOptionControl, AgentOptionToggleControl } from "../../agent-sdk-types.js";
import {
claudeManifestModelSupportsFastMode,
claudeManifestModelSupportsUltracode,
} from "./model-manifest.js";
import { claudeManifestModelSupportsFastMode } from "./model-manifest.js";
export const CLAUDE_FAST_MODE_CONTROL: AgentOptionToggleControl = {
type: "toggle",
@@ -13,26 +10,10 @@ 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,
independentUltracode: boolean,
): AgentOptionControl[] {
return [
...(claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : []),
...(independentUltracode && claudeManifestModelSupportsUltracode(modelId)
? [{ ...CLAUDE_ULTRACODE_CONTROL }]
: []),
];
export function buildClaudeControls(modelId: string | null | undefined): AgentOptionControl[] {
return claudeModelSupportsFastMode(modelId) ? [{ ...CLAUDE_FAST_MODE_CONTROL }] : [];
}
@@ -226,27 +226,25 @@ function buildThinkingOptions(
effortLevels: readonly ClaudeEffortLevel[] | undefined,
supportsThinkingDisabled: boolean,
defaultThinkingOptionId: ClaudeEffortLevel,
independentUltracode: boolean,
): AgentSelectOption[] | undefined {
if (!effortLevels) {
return undefined;
}
return [
const options: AgentSelectOption[] = [
...(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(
@@ -272,7 +270,6 @@ export function getClaudeManifestModels(
model.effortLevels,
model.supportsThinkingDisabled === true,
getDefaultThinkingOptionId(model),
supportsIndependentClaudeUltracode(claudeCodeVersion),
);
const definition: AgentModelDefinition = {
provider: "claude",
@@ -343,10 +340,6 @@ 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;
@@ -388,14 +381,6 @@ 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,6 +8,7 @@ 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,
@@ -189,6 +190,7 @@ 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,
@@ -197,7 +199,14 @@ 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,
@@ -210,6 +219,7 @@ 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,
@@ -410,12 +420,9 @@ describe("ClaudeAgentClient.fetchCatalog", () => {
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium" },
{ id: "high", label: "High", isDefault: true },
{
id: "xhigh",
label: "Extra High",
metadata: { replacesThinkingOptionId: "ultracode" },
},
{ id: "xhigh", label: "Extra High" },
{ 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]",
@@ -838,6 +845,7 @@ describe("Claude Fable 5.2 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(claudeManifestModelSupportsFastMode("claude-fable-5-2")).toBe(true);
});
@@ -879,6 +887,7 @@ describe("Claude Opus 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(opus55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -913,6 +922,7 @@ describe("Claude Sonnet 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(sonnet55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -949,6 +959,7 @@ describe("Claude Haiku 5.5 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(haiku55?.defaultThinkingOptionId).toBe("medium");
expect(
@@ -1005,6 +1016,7 @@ 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),
@@ -1076,6 +1088,7 @@ describe("Claude Mythos 5.2 catalog", () => {
"high",
"xhigh",
"max",
CLAUDE_ULTRACODE_THINKING_OPTION_ID,
]);
expect(claudeManifestModelSupportsFastMode("claude-mythos-5-2")).toBe(true);
});
@@ -45,9 +45,8 @@ const SandboxFilesystemSchema = z
// Claude Agent SDK Options, maintained against @anthropic-ai/claude-agent-sdk 0.3.246.
export const ClaudeProviderOptionsSchema = z
.object({
/** Composer controls applied through Claude flag settings. */
/** Composer control, not a Claude SDK option: the provider reads it and keeps it out of the SDK options. */
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,7 +6,6 @@ import {
} from "./persisted-config.js";
import { ProviderOverrideSchema } from "./agent/provider-launch-config.js";
import {
convertLegacyClaudeUltracode,
convertLegacyOptions,
foldProfileFeatureValues,
resolveAdapter,
@@ -195,21 +194,13 @@ 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) => {
const folded = foldProfileFeatureValues<
Pick<AgentProfile, "provider" | "options" | "featureValues">
>({
const foldWith = (profile: AgentProfile, convertWith: typeof convert) =>
foldProfileFeatureValues({
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) => {
@@ -0,0 +1,193 @@
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,6 +587,29 @@ 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[] = [];
@@ -623,6 +646,7 @@ describe("WorkspaceGitServiceImpl", () => {
const service = new WorkspaceGitServiceImpl({
logger: createLogger() as unknown as pino.Logger,
paseoHome: "/tmp/paseo-test",
releaseGraceMs: 0,
deps: {
...buildDefaultTestServiceDeps(),
getPullRequestStatus: async () => {
@@ -81,6 +81,9 @@ 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;
@@ -441,6 +444,8 @@ 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 {
@@ -463,6 +468,7 @@ interface WorkspaceGitTarget {
gitDirPaths: GitObservationPaths | null;
cwd: string;
listeners: Set<WorkspaceGitListener>;
releaseTimer: NodeJS.Timeout | null;
workingTreeWatchTarget: WorkingTreeWatchTarget | null;
debounceTimer: NodeJS.Timeout | null;
pendingDebounceRequest: WorkspaceGitRefreshRequest | null;
@@ -657,6 +663,7 @@ 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;
@@ -710,6 +717,7 @@ 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),
@@ -733,6 +741,7 @@ 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);
@@ -1318,6 +1327,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
gitDirPaths: null,
cwd,
listeners: new Set(),
releaseTimer: null,
workingTreeWatchTarget: null,
debounceTimer: null,
pendingDebounceRequest: null,
@@ -3065,6 +3075,9 @@ 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(
@@ -3351,6 +3364,9 @@ 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) {
@@ -4104,7 +4120,52 @@ 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 {
@@ -4171,6 +4232,7 @@ 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,6 +86,12 @@ 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+",