From a0a51a63cb05eb683243d7e5bd2b428e52e1a424 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 19 Nov 2026 18:28:32 +0800 Subject: [PATCH 01/16] feat(vcs): open a push dialog file's diff in its own window (#4490) Double-click or Enter on a file in the push dialog opens its diff in a separate diff window (Show Diff in New Window), as IDEA's push dialog does; closing it returns to the dialog. Before, the diff was only shown in a split inside the small modal dialog. Selecting a file still shows the diff in the dialog. --- src/features/vcs/ComparisonTree.tsx | 5 +++- src/features/vcs/PushChanges.tsx | 8 +++++-- .../vcs/__tests__/pushChanges.test.tsx | 23 ++++++++++++++++++- 3 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/features/vcs/ComparisonTree.tsx b/src/features/vcs/ComparisonTree.tsx index 5defe247f0..9aa5ecc0e6 100644 --- a/src/features/vcs/ComparisonTree.tsx +++ b/src/features/vcs/ComparisonTree.tsx @@ -19,6 +19,7 @@ export function ComparisonTree({ getColor, onOpen, inlineDiff = true, + openDiff = (diff) => void openVcsDiff(diff), }: { tree: FileTreeNode[]; current: F | null; @@ -32,6 +33,8 @@ export function ComparisonTree({ onOpen?: () => void; /** Show the selected file's diff beside the tree; off where there is no room (a sidebar). */ inlineDiff?: boolean; + /** With `openOnActivate`: where a double-clicked file's diff opens (default: an editor tab). */ + openDiff?: (diff: DiffData) => void; }) { const [selected, setSelected] = useState>(new Set()); const [expanded, setExpanded] = useState | null>(null); @@ -58,7 +61,7 @@ export function ComparisonTree({ onSelect(entry); const diff = diffFor(entry); if (openOnActivate && diff) { - void openVcsDiff(diff); + openDiff(diff); onOpen?.(); } }} diff --git a/src/features/vcs/PushChanges.tsx b/src/features/vcs/PushChanges.tsx index aae1d9b787..b3e1cc481c 100644 --- a/src/features/vcs/PushChanges.tsx +++ b/src/features/vcs/PushChanges.tsx @@ -1,10 +1,12 @@ /** * Push dialog: the files changed by the outgoing commits (the selected commit's, or all of - * them), with the selected file's diff beside the tree. The diff stays inside the dialog, - * which is modal. A single commit also shows its message, author and time. + * them), with the selected file's diff beside the tree. Double-click or Enter opens the diff in + * its own window, as IDEA does, since the dialog is modal and small. A single commit also shows + * its message, author and time. */ import { useEffect, useMemo, useState } from "react"; import type { ChangedFile, Commit, RevisionChange } from "@/bindings"; +import { executeAction } from "@/platform/actions"; import { call, commands } from "@/platform/ipc"; import { tx } from "@/platform/i18n"; import { Button, IconButton, Spinner, SplitGroup, SplitHandle, SplitPanel, T } from "@/ui"; @@ -94,6 +96,8 @@ export function PushChanges({ }} diffFor={(c) => c.diff} inlineDiff={!onSelectFile} + openOnActivate + openDiff={(diff) => void executeAction("vcs.showDiffInNewWindow", diff)} getColor={(c) => KIND_COLOR[c.kind === "untracked" ? "added" : c.kind]} ariaLabel="Changed files" renderDetails={(n) => diff --git a/src/features/vcs/__tests__/pushChanges.test.tsx b/src/features/vcs/__tests__/pushChanges.test.tsx index b400a332ad..f32e7b25bf 100644 --- a/src/features/vcs/__tests__/pushChanges.test.tsx +++ b/src/features/vcs/__tests__/pushChanges.test.tsx @@ -2,7 +2,16 @@ import { describe, expect, it, vi } from "vitest"; import { fireEvent, render, screen } from "@testing-library/react"; import type { Commit } from "@/bindings"; -const { files, combined } = vi.hoisted(() => ({ files: vi.fn(), combined: vi.fn() })); +const { files, combined, executeAction } = vi.hoisted(() => ({ + files: vi.fn(), + combined: vi.fn(), + executeAction: vi.fn(async () => true), +})); + +vi.mock("@/platform/actions", async (importOriginal) => ({ + ...(await importOriginal()), + executeAction, +})); vi.mock("@/platform/ipc", async (importOriginal) => { const real = await importOriginal(); @@ -76,6 +85,18 @@ describe("Push dialog changes", () => { expect(localStorage.getItem("openidea.vcs.push.groupByDirectory")).toBe("false"); }); + it("opens a double-clicked file's diff in its own window and keeps the selection's diff in the dialog", async () => { + files.mockResolvedValue({ status: "ok", data: [{ path: "a.txt", oldPath: null, kind: "modified" }] }); + const select = vi.fn(); + render(); + fireEvent.doubleClick(await screen.findByText("a.txt")); + expect(select).toHaveBeenLastCalledWith(expect.objectContaining({ path: "a.txt" })); + expect(executeAction).toHaveBeenCalledWith( + "vcs.showDiffInNewWindow", + expect.objectContaining({ path: expect.stringContaining("a.txt") }), + ); + }); + it("shows no commit details for several commits", async () => { combined.mockResolvedValue({ status: "ok", data: [] }); render(); From 0f355c286d44a3cc15ebf4339c6b16739a9b9f2b Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 19 Nov 2026 19:05:18 +0800 Subject: [PATCH 02/16] fix(format): keep the caret when a language server replaces the whole file (#4497) Vue's language server answers Reformat Code with one edit replacing the whole document, which moved the caret and the view to the top of the file. Multi-line LSP formatting edits are now reduced to one edit per changed region via Document::diff, which covers every server that formats this way. --- crates/ide-host/src/formatter.rs | 48 +++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/crates/ide-host/src/formatter.rs b/crates/ide-host/src/formatter.rs index ca4fd05b6d..d61c23b009 100644 --- a/crates/ide-host/src/formatter.rs +++ b/crates/ide-host/src/formatter.rs @@ -119,6 +119,29 @@ fn php_cs_fixer_edits( .collect()) } +/// Some language servers (Vue's, for one) answer Reformat Code with one edit replacing the +/// whole file; applied as is, it moves the caret and the view to the top of the file. The same +/// result as one edit per changed region keeps them where they were. +fn minimal_edits(text: &str, edits: Vec) -> Vec { + if !edits.iter().any(|e| e.range.end.line > e.range.start.line) { + return edits; + } + let original = ide_text::Document::new(text); + let mut formatted = original.clone(); + if formatted.apply_edits(&edits).is_err() { + return edits; + } + original + .diff(&formatted.text()) + .changes + .into_iter() + .map(|c| TextEdit { + range: Range::new(original.offset_to_pos(c.from), original.offset_to_pos(c.to)), + new_text: c.insert, + }) + .collect() +} + pub async fn format( host: &Host, window: &str, @@ -292,7 +315,11 @@ async fn provider_edits( if options.on_save && !settings.editor.format_on_save { return Ok(None); } - return project.lsp.format(doc, range, options).await.map(Some); + let edits = project.lsp.format(doc, range, options).await?; + let text = snap.text; + return tokio::task::spawn_blocking(move || Some(minimal_edits(&text, edits))) + .await + .map_err(|e| IdeError::internal(e.to_string())); }; let tool_settings = settings.languages.formatter(selected); if options.on_save && !tool_settings.run_on_save { @@ -523,6 +550,25 @@ mod tests { const ALIGN: PhpAlignment = PhpAlignment { key_value_pairs: true, assignments: true }; + #[test] + fn a_whole_file_edit_becomes_one_edit_per_changed_region() { + let text = "a\n b\nc\nd\n e\n"; + let formatted = "a\nb\nc\nd\ne\n"; + let whole = vec![TextEdit { range: Range::new(Pos::new(0, 0), Pos::new(5, 0)), new_text: formatted.into() }]; + let edits = minimal_edits(text, whole); + assert_eq!( + edits, + [ + TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }, + TextEdit { range: Range::new(Pos::new(4, 0), Pos::new(4, 2)), new_text: String::new() }, + ] + ); + assert_eq!(after(text, &edits), formatted); + // Single-line edits are already minimal and pass through. + let small = vec![TextEdit { range: Range::new(Pos::new(1, 0), Pos::new(1, 2)), new_text: String::new() }]; + assert_eq!(minimal_edits(text, small.clone()), small); + } + #[test] fn php_alignment_is_off_unless_the_php_code_style_turns_it_on() { let php = LanguageId::new("php"); From 58585e106484fbd6bc0601b2f38721b6e5779d83 Mon Sep 17 00:00:00 2001 From: l0ng-ai Date: Thu, 19 Nov 2026 19:15:53 +0800 Subject: [PATCH 03/16] feat(vcs): choose the agent, model and effort for Generate Commit Message (#4504) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings › Version Control › Commit › Commit Message Generation gets Agent, Model and Effort dropdowns (vcs.commit.agent / agentModel / agentEffort). Automatic keeps the agent of the latest task on its model; a chosen agent runs on the chosen model and thinking level when it offers them, independent of the chat's model. The lists come from the agent's model catalog. --- crates/ide-core/src/workflow_settings.rs | 9 ++ crates/ide-workspace/src/settings.rs | 3 + src/bindings.ts | 6 ++ src/features/agents/commitMessage.test.ts | 67 ++++++++++++ src/features/agents/commitMessage.ts | 71 +++++++++++-- src/features/settings/pages/vcs.tsx | 118 ++++++++++++++++++++++ src/platform/locales/text/en.json | 6 +- src/platform/locales/text/zh.json | 6 +- src/platform/workflowSettings.ts | 12 +++ 9 files changed, 287 insertions(+), 11 deletions(-) diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index 06c41a2a3a..816a0281a6 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -170,6 +170,12 @@ pub struct CommitSettings { pub double_click_opens_diff: Option, /// Team conventions for Generate Commit Message with Agent, added to its prompt. pub agent_instructions: String, + /// The coding agent Generate Commit Message with Agent uses; empty follows the latest task's agent. + pub agent: String, + /// That agent's model for commit messages; empty keeps the model the agent would use. + pub agent_model: String, + /// That model's thinking level for commit messages; empty keeps the agent's. + pub agent_effort: String, } impl Default for CommitSettings { @@ -192,6 +198,9 @@ impl Default for CommitSettings { disabled_plugin_checks: Vec::new(), double_click_opens_diff: None, agent_instructions: String::new(), + agent: String::new(), + agent_model: String::new(), + agent_effort: String::new(), } } } diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rs index d6b1526e35..f2e0132435 100644 --- a/crates/ide-workspace/src/settings.rs +++ b/crates/ide-workspace/src/settings.rs @@ -847,6 +847,9 @@ mod tests { "disabledPluginChecks": [], "doubleClickOpensDiff": null, "agentInstructions": "", + "agent": "", + "agentModel": "", + "agentEffort": "", }) ); } diff --git a/src/bindings.ts b/src/bindings.ts index 9e7361bded..1b71849586 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -3745,6 +3745,12 @@ export type CommitSettings = { doubleClickOpensDiff?: boolean | null, /** Team conventions for Generate Commit Message with Agent, added to its prompt. */ agentInstructions?: string, + /** The coding agent Generate Commit Message with Agent uses; empty follows the latest task's agent. */ + agent?: string, + /** That agent's model for commit messages; empty keeps the model the agent would use. */ + agentModel?: string, + /** That model's thinking level for commit messages; empty keeps the agent's. */ + agentEffort?: string, }; export type Commit_Deserialize = { diff --git a/src/features/agents/commitMessage.test.ts b/src/features/agents/commitMessage.test.ts index 8e604e5c6a..5650be3534 100644 --- a/src/features/agents/commitMessage.test.ts +++ b/src/features/agents/commitMessage.test.ts @@ -274,6 +274,73 @@ describe("pickAgent", () => { }); }); +describe("pickAgent with an agent chosen for commit messages", () => { + const effort: AgentConfigOption = { + id: "effort", + name: "Effort", + description: null, + category: "thought_level", + current: "high", + values: ["low", "high"].map((value) => ({ value, name: value, description: null })), + via: "option", + }; + const claude = { ...provider("claude", true, [modelOption("smart")]), thoughtLevels: { fast: [effort] } }; + const tasks = [ + task("a", "claude", { updatedMs: 1, config: [modelOption("smart")] }), + task("b", "codex", { updatedMs: 5 }), + ]; + const prefer = (agent: string, model = "", level = "") => ({ agent, agentModel: model, agentEffort: level }); + + it("uses that agent over the latest task's, on the model of its own latest task", () => { + expect(pickAgent(tasks, [claude, provider("codex")], draft("codex"), prefer("claude"))).toEqual({ + provider: "claude", + config: [{ id: "model", value: "smart" }], + }); + }); + + it("runs the chosen model at the chosen effort", () => { + expect(pickAgent(tasks, [claude, provider("codex")], draft("codex"), prefer("claude", "fast", "low"))).toEqual({ + provider: "claude", + config: [ + { id: "model", value: "fast" }, + { id: "effort", value: "low" }, + ], + }); + }); + + it("reads the models from the agent's refreshed catalog", () => { + const catalog = { + config: [{ ...modelOption("smart"), values: [{ value: "mini", name: "mini", description: null }] }], + thoughtLevels: { mini: [effort] }, + }; + expect( + pickAgent([], [claude], draft("claude"), prefer("claude", "mini", "low"), new Map([["claude", catalog]])), + ).toEqual({ + provider: "claude", + config: [ + { id: "model", value: "mini" }, + { id: "effort", value: "low" }, + ], + }); + }); + + it("keeps the agent's model and effort for values it doesn't offer", () => { + expect(pickAgent([], [claude], draft("claude"), prefer("claude", "gone", "low"))).toEqual({ + provider: "claude", + config: [{ id: "model", value: "smart" }], + }); + }); + + it("follows the latest task when the chosen agent isn't installed", () => { + expect( + pickAgent(tasks, [provider("claude", false), provider("codex")], draft("codex"), prefer("claude", "fast")), + ).toEqual({ + provider: "codex", + config: [], + }); + }); +}); + describe("generateCommitMessage", () => { const changes = { revision: 3, roots: ["/p"], patch: PATCH }; const notified = () => backend.notify.mock.calls.map(([n]) => n as { level: string; title: string; body?: string }); diff --git a/src/features/agents/commitMessage.ts b/src/features/agents/commitMessage.ts index d940e6b4d4..356d2dd70d 100644 --- a/src/features/agents/commitMessage.ts +++ b/src/features/agents/commitMessage.ts @@ -3,7 +3,14 @@ * changes about to be committed and writes their message. It runs as a short task that * is deleted once the message is in the commit field. */ -import type { AgentConfigChoice, AgentConfigOption, AgentEntry, AgentProvider, AgentTask } from "@/bindings"; +import type { + AgentConfigChoice, + AgentConfigOption, + AgentEntry, + AgentModelCatalog, + AgentProvider, + AgentTask, +} from "@/bindings"; import { executeAction } from "@/platform/actions"; import { tx } from "@/platform/i18n"; import { call, commands } from "@/platform/ipc"; @@ -139,28 +146,74 @@ export function askingChoices(options: readonly AgentConfigOption[]): AgentConfi const choicesFor = (options: readonly AgentConfigOption[]) => [...modelChoice(options), ...askingChoices(options)]; +/** Settings › Version Control › Commit: the agent, model and thinking level to generate with; empty follows the agent. */ +export interface CommitAgentPreference { + agent: string; + agentModel: string; + agentEffort: string; +} + +type ModelCatalog = Pick; + /** * The agent that wrote the code: the one of the project's latest task, on the model it - * ran with. Without a task, the one the New Task page has selected. + * ran with. Without a task, the one the New Task page has selected. An agent chosen in + * the settings replaces it, on the model and thinking level chosen there when it offers them. */ export function pickAgent( tasks: Iterable, providers: readonly AgentProvider[], draft: Draft, + preference?: CommitAgentPreference, + catalogs?: ReadonlyMap, ): CommitAgent | null { const installed = providers.filter((p) => p.installed); + const chosen = preference?.agent ? installed.find((p) => p.id === preference.agent) : undefined; + const candidates = chosen ? [chosen] : installed; const latest = [...tasks] - .filter((t) => t.status !== "archived" && installed.some((p) => p.id === t.provider)) + .filter((t) => t.status !== "archived" && candidates.some((p) => p.id === t.provider)) .sort((a, b) => (b.updatedMs ?? 0) - (a.updatedMs ?? 0))[0]; - if (latest) return { provider: latest.provider, config: choicesFor(latest.config) }; - const provider = installed.find((p) => p.id === draft.provider) ?? installed[0]; + const provider = latest + ? installed.find((p) => p.id === latest.provider)! + : (chosen ?? installed.find((p) => p.id === draft.provider) ?? installed[0]); if (!provider) return null; + const options = latest + ? latest.config + : provider.id === draft.provider + ? draftConfig(provider, draft) + : provider.config; + if (!chosen || !preference || (!preference.agentModel && !preference.agentEffort)) { + return { provider: provider.id, config: choicesFor(options) }; + } return { provider: provider.id, - config: choicesFor(provider.id === draft.provider ? draftConfig(provider, draft) : provider.config), + config: [...preferredModel(options, provider, preference, catalogs?.get(provider.id)), ...askingChoices(options)], }; } +/** The model and thinking level of `preference` that the agent offers, else the ones it would run with. */ +function preferredModel( + options: readonly AgentConfigOption[], + provider: AgentProvider, + preference: CommitAgentPreference, + catalog: ModelCatalog | undefined, +): AgentConfigChoice[] { + const offered = (catalog?.config ?? provider.config).find((o) => o.category === "model"); + const fallback = modelChoice(options); + const model = + offered && preference.agentModel && offered.values.some((v) => v.value === preference.agentModel) + ? { id: offered.id, value: preference.agentModel } + : fallback[0]; + if (!model) return []; + const levels = (catalog?.thoughtLevels ?? provider.thoughtLevels)?.[model.value] ?? []; + const level = levels.find((o) => o.category === "thought_level"); + const effort = + level && preference.agentEffort && level.values.some((v) => v.value === preference.agentEffort) + ? [{ id: level.id, value: preference.agentEffort }] + : []; + return [model, ...effort]; +} + /** Resolves when the task's turn ends; rejects when it can't produce an answer. */ function turnEnd(task: string): Promise { return new Promise((resolve, reject) => { @@ -243,8 +296,9 @@ async function generate(): Promise { notify({ level: "info", title: "No changes to describe", body: "Include changes in the commit first." }); return; } - const { tasks, providers, draft } = useAgents.getState(); - const agent = pickAgent(tasks.values(), providers, draft); + const { commit } = workflowSettings().vcs; + const { tasks, providers, draft, modelCatalogs } = useAgents.getState(); + const agent = pickAgent(tasks.values(), providers, draft, commit, modelCatalogs); if (!agent) { notify({ level: "warning", @@ -255,7 +309,6 @@ async function generate(): Promise { return; } - const { commit } = workflowSettings().vcs; const subjects = await recentSubjects(changes.roots[0]); const prompt = commitMessagePrompt( changes.patch, diff --git a/src/features/settings/pages/vcs.tsx b/src/features/settings/pages/vcs.tsx index 4ef1239f87..d27ff8cf8b 100644 --- a/src/features/settings/pages/vcs.tsx +++ b/src/features/settings/pages/vcs.tsx @@ -14,6 +14,7 @@ import { Button, Icon, IconButton, Input, Select, type SelectOption, T } from "@ import { choosePath } from "@/platform/choosePath"; import { Row, SettingSelect } from "../components/Form"; import { useSetting } from "../components/context"; +import type { AgentModelCatalog, AgentProvider } from "@/bindings"; import type { PageSpec } from "./spec"; import { BoundToggle, Grid, Indented, RadioRow, TableEditor, ToggleNumber } from "./workflowControls"; import styles from "./Workflow.module.css"; @@ -378,6 +379,117 @@ function MessageLimits() { ); } +const AUTOMATIC = ""; + +/** The installed coding agents, as the agents feature reports them; empty where agents can't run. */ +function useInstalledAgents(): AgentProvider[] { + const [agents, setAgents] = useState([]); + useEffect(() => { + if (!isTauri()) return; + let live = true; + call(commands.agentProviders()) + .then((all) => live && setAgents(all.filter((p) => p.installed))) + .catch(() => {}); + return () => { + live = false; + }; + }, []); + return agents; +} + +type ModelCatalog = Pick; + +/** The models `agent` offers, from its catalog; asks the agent for it once when it hasn't reported one. */ +function useModelCatalog(agent: AgentProvider | undefined): ModelCatalog | undefined { + const [catalog, setCatalog] = useState<{ provider: string } & ModelCatalog>(); + const id = agent?.id; + useEffect(() => { + if (!id) return; + let live = true; + let timer: ReturnType | undefined; + let polls = 0; + const load = () => + call(commands.agentRefreshModels(id, false, null)) + .then((c) => { + if (!live) return; + setCatalog(c); + if (c.refreshing && ++polls < CATALOG_POLLS) timer = setTimeout(load, CATALOG_POLL_MS); + }) + .catch(() => {}); + void load(); + return () => { + live = false; + clearTimeout(timer); + }; + }, [id]); + if (!agent) return undefined; + const fresh = catalog?.provider === agent.id && catalog.config.some((o) => o.category === "model"); + return fresh ? catalog : { config: agent.config, thoughtLevels: agent.thoughtLevels ?? {} }; +} + +const CATALOG_POLL_MS = 1_500; +const CATALOG_POLLS = 40; + +/** `values` as options after `automatic`, keeping a saved value the agent no longer lists. */ +function choiceOptions( + automatic: string, + values: readonly { value: string; name: string }[], + saved: string, +): SelectOption[] { + const options = [{ value: AUTOMATIC, label: automatic }, ...values.map((v) => ({ value: v.value, label: v.name }))]; + return saved && !values.some((v) => v.value === saved) ? [...options, { value: saved, label: saved }] : options; +} + +function CommitAgentRows() { + const agents = useInstalledAgents(); + const [agent, setAgent] = useSetting("vcs.commit.agent"); + const [model, setModel] = useSetting("vcs.commit.agentModel"); + const [effort, setEffort] = useSetting("vcs.commit.agentEffort"); + const catalog = useModelCatalog(agents.find((p) => p.id === agent)); + const models = catalog?.config.find((o) => o.category === "model"); + const shown = model || models?.current; + const levels = (shown ? catalog?.thoughtLevels[shown] : undefined)?.find((o) => o.category === "thought_level"); + const agentOptions = choiceOptions( + tx("Automatic (the agent of the latest task)"), + agents.map((p) => ({ value: p.id, name: p.name })), + agent, + ); + const pick = (next: string) => { + if (next === agent) return; + setAgent(next); + setModel(AUTOMATIC); + setEffort(AUTOMATIC); + }; + return ( + <> + + { + setModel(next); + setEffort(AUTOMATIC); + }} + disabled={!agent} + aria-label={tx("Model")} + /> + + + apply(e.target.value)} + /> + + +
+ { + setHex(e.target.value); + if (HEX_COLOR.test(e.target.value)) apply(e.target.value.toLowerCase()); + }} + /> + +
+ + ); +} diff --git a/src/workbench/WindowGroupTabs.module.css b/src/workbench/WindowGroupTabs.module.css index d815ee2653..d54286cf9d 100644 --- a/src/workbench/WindowGroupTabs.module.css +++ b/src/workbench/WindowGroupTabs.module.css @@ -50,6 +50,18 @@ background: var(--bg-island); color: var(--fg); } +/* Only a user-chosen colour tints the tab; the default keeps the plain surface. */ +.item[data-tinted] { + --tab-tint-mix: color-mix(in srgb, var(--project-color) 12%, transparent); + background: var(--tab-tint-mix); +} +.item[data-tinted]:hover { + background: linear-gradient(var(--bg-hover), var(--bg-hover)), var(--tab-tint-mix); +} +.selected[data-tinted], +.selected[data-tinted]:hover { + background: color-mix(in srgb, var(--project-color) 25%, var(--bg-island)); +} .tab { display: flex; align-items: center; diff --git a/src/workbench/WindowGroupTabs.test.tsx b/src/workbench/WindowGroupTabs.test.tsx index 5e7803e964..14fad1b1d0 100644 --- a/src/workbench/WindowGroupTabs.test.tsx +++ b/src/workbench/WindowGroupTabs.test.tsx @@ -3,6 +3,8 @@ import { fireEvent, render, screen } from "@testing-library/react"; import { executeAction } from "@/platform/actions"; import { useWindowGroup } from "@/platform/windowGroups"; import { useContextMenuStore } from "@/ui/Menu"; +import { projectColorVars } from "./projectColor"; +import { setTabColorOverride } from "./tabColors"; import { WindowGroupTabs } from "./WindowGroupTabs"; vi.mock("@/platform/actions", async (importOriginal) => ({ @@ -12,6 +14,7 @@ vi.mock("@/platform/actions", async (importOriginal) => ({ beforeEach(() => { vi.mocked(executeAction).mockClear(); + localStorage.clear(); useWindowGroup.setState({ tabs: [ { label: "main", name: "Frontend", root: "/front", current: true }, @@ -85,3 +88,26 @@ it("offers Move Tab to New Window for every tab in its context menu", () => { void item.run?.(); expect(executeAction).toHaveBeenLastCalledWith("window.detachTab", "project-1"); }); + +it("offers Tab Color… in the context menu", () => { + render(); + fireEvent.contextMenu(screen.getByRole("tab", { name: "Backend" })); + const item = useContextMenuStore + .getState() + .menu!.items.find((i) => "label" in i && i.label === "Change Project Color…") as { + run?: () => unknown; + }; + void item.run?.(); + expect(executeAction).toHaveBeenLastCalledWith("window.setTabColor", "project-1"); +}); + +it("tints only tabs with a stored colour override", () => { + setTabColorOverride("/back", "#112233"); + render(); + const front = screen.getByRole("tab", { name: "Frontend" }).parentElement!; + const back = screen.getByRole("tab", { name: "Backend" }).parentElement!; + expect(front.style.getPropertyValue("--project-color")).toBe(projectColorVars("Frontend")["--project-color"]); + expect(front.hasAttribute("data-tinted")).toBe(false); + expect(back.style.getPropertyValue("--project-color")).toBe("#112233"); + expect(back.hasAttribute("data-tinted")).toBe(true); +}); diff --git a/src/workbench/WindowGroupTabs.tsx b/src/workbench/WindowGroupTabs.tsx index 74698f2ba8..484d6b8218 100644 --- a/src/workbench/WindowGroupTabs.tsx +++ b/src/workbench/WindowGroupTabs.tsx @@ -1,9 +1,11 @@ -import { useLayoutEffect, useRef, useState } from "react"; +import { useLayoutEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from "react"; import { executeAction } from "@/platform/actions"; import { useTx } from "@/platform/i18n"; import { reorderedTabs, useWindowGroup } from "@/platform/windowGroups"; import { IconButton, showContextMenu } from "@/ui"; import { notifications } from "./contributions"; +import { subscribeTabColors, tabColorOverride, tabColorVars, tabColorsVersion } from "./tabColors"; +import { TabColorPicker } from "./TabColorPicker"; import styles from "./WindowGroupTabs.module.css"; function run(work: Promise) { @@ -18,6 +20,7 @@ function run(work: Promise) { export function WindowGroupTabs() { const tabs = useWindowGroup((state) => state.tabs); + useSyncExternalStore(subscribeTabColors, tabColorsVersion); const drag = useRef<{ label: string; x: number; moved: boolean } | null>(null); const [dragging, setDragging] = useState(null); const tx = useTx(); @@ -60,6 +63,8 @@ export function WindowGroupTabs() { className={`${styles.item} ${tab.current ? styles.selected : ""} ${dragging === tab.label ? styles.dragging : ""}`} key={tab.label} data-project-tab={tab.label} + data-tinted={tab.root && tabColorOverride(tab.root) ? "" : undefined} + style={tabColorVars(tab.name, tab.root ? tabColorOverride(tab.root) : null) as CSSProperties} onPointerDown={(e) => { drag.current = null; if (e.button === 0 && (e.target as Element).closest('[role="tab"]')) @@ -104,6 +109,10 @@ export function WindowGroupTabs() { label: "Move Tab to New Window", run: () => executeAction("window.detachTab", tab.label), }, + { + label: tx("Change Project Color…"), + run: () => executeAction("window.setTabColor", tab.label), + }, { kind: "separator" }, { label: "Close Tab", @@ -165,6 +174,7 @@ export function WindowGroupTabs() { ))} + ); } diff --git a/src/workbench/Workbench.tsx b/src/workbench/Workbench.tsx index 11dc5d7454..45901e7f8f 100644 --- a/src/workbench/Workbench.tsx +++ b/src/workbench/Workbench.tsx @@ -4,6 +4,7 @@ * overlay layer. Without an open project the welcome view replaces the frame, * or, editing loose files (LightEdit), a frame with the editor only. */ +import { useSyncExternalStore } from "react"; import { useEditorRegistry } from "@/editor/api"; import { Breadcrumbs } from "@/editor/core"; import { basename, useProject } from "@/platform/project"; @@ -14,7 +15,7 @@ import projectMark from "../../src-tauri/icons/source/openidea-mark.svg"; import { useDistractionFree } from "./distractionFree"; import { EditorArea } from "./EditorArea"; import { OverlayHost } from "./OverlayHost"; -import { projectColorVars } from "./projectColor"; +import { subscribeTabColors, tabColorOverride, tabColorVars, tabColorsVersion } from "./tabColors"; import { StatusBar } from "./StatusBar"; import { TitleBar } from "./TitleBar"; import { WindowGroupTabs } from "./WindowGroupTabs"; @@ -80,6 +81,7 @@ function ProjectOpening({ path }: { path: string }) { export function Workbench() { useApplyTheme(); + useSyncExternalStore(subscribeTabColors, tabColorsVersion); const banners = useContributions((s) => s.workbenchBanners); const project = useProject((s) => s.project); const lightEdit = useProject((s) => s.lightEdit); @@ -95,7 +97,7 @@ export function Workbench() { return (
{project ? ( diff --git a/src/workbench/projectColor.ts b/src/workbench/projectColor.ts index 74e36c18d0..4c9e8e2928 100644 --- a/src/workbench/projectColor.ts +++ b/src/workbench/projectColor.ts @@ -56,7 +56,11 @@ const FALLBACK: Record = { }; export function projectColorVars(name: string): Record { - const n = projectColorIndex(name); + return projectColorSlotVars(projectColorIndex(name)); +} + +/** CSS vars for an explicit slot, e.g. a user-chosen tab colour. */ +export function projectColorSlotVars(n: number): Record { const [start, end] = FALLBACK[n]!; return { "--project-color": `var(--project-color-${n}, ${start})`, diff --git a/src/workbench/tabColors.test.ts b/src/workbench/tabColors.test.ts new file mode 100644 index 0000000000..ca17ab9bc3 --- /dev/null +++ b/src/workbench/tabColors.test.ts @@ -0,0 +1,66 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { projectColorVars } from "./projectColor"; +import { setTabColorOverride, subscribeTabColors, tabColorOverride, tabColorVars } from "./tabColors"; + +beforeEach(() => localStorage.clear()); +afterEach(() => localStorage.clear()); + +it("falls back to the name-hashed project colour without an override", () => { + expect(tabColorVars("databus-plugins", null)).toEqual(projectColorVars("databus-plugins")); +}); + +it("resolves a preset slot override to that theme slot", () => { + const vars = tabColorVars("databus-plugins", "4"); + expect(vars["--project-color"]).toContain("--project-color-4"); + expect(vars["--project-color-end"]).toContain("--project-color-4-end"); +}); + +it("resolves a hex override to a flat colour", () => { + expect(tabColorVars("openidea", "#aabbcc")).toEqual({ + "--project-color": "#aabbcc", + "--project-color-end": "#aabbcc", + }); +}); + +it("persists overrides per project root", () => { + setTabColorOverride("/front", "3"); + setTabColorOverride("/back", "#112233"); + expect(tabColorOverride("/front")).toBe("3"); + expect(tabColorOverride("/back")).toBe("#112233"); + expect(tabColorOverride("/other")).toBeNull(); +}); + +it("clears the override back to the default", () => { + setTabColorOverride("/front", "3"); + setTabColorOverride("/front", null); + expect(tabColorOverride("/front")).toBeNull(); +}); + +it("ignores invalid stored values", () => { + localStorage.setItem("openidea.tabColor.v1:/front", "not-a-colour"); + localStorage.setItem("openidea.tabColor.v1:/back", "10"); + localStorage.setItem("openidea.tabColor.v1:/docs", "#abc"); + expect(tabColorOverride("/front")).toBeNull(); + expect(tabColorOverride("/back")).toBeNull(); + expect(tabColorOverride("/docs")).toBeNull(); +}); + +it("notifies subscribers on a local change", () => { + const listener = vi.fn(); + const off = subscribeTabColors(listener); + setTabColorOverride("/front", "5"); + expect(listener).toHaveBeenCalledTimes(1); + off(); + setTabColorOverride("/front", null); + expect(listener).toHaveBeenCalledTimes(1); +}); + +it("notifies subscribers on a cross-window storage event for a tab colour key", () => { + const listener = vi.fn(); + const off = subscribeTabColors(listener); + window.dispatchEvent(new StorageEvent("storage", { key: "openidea.tabColor.v1:/front" })); + expect(listener).toHaveBeenCalledTimes(1); + window.dispatchEvent(new StorageEvent("storage", { key: "openidea.layout.v1:/front" })); + expect(listener).toHaveBeenCalledTimes(1); + off(); +}); diff --git a/src/workbench/tabColors.ts b/src/workbench/tabColors.ts new file mode 100644 index 0000000000..2bedb93679 --- /dev/null +++ b/src/workbench/tabColors.ts @@ -0,0 +1,57 @@ +/** + * Per-project tab colour overrides, persisted per project root in localStorage + * (like the tool window layout). A value is a preset slot "1"–"9" or "#rrggbb"; + * without one the tab keeps the name-hashed project colour. + */ +import { PROJECT_COLOR_COUNT, projectColorSlotVars, projectColorVars } from "./projectColor"; + +const KEY_PREFIX = "openidea.tabColor.v1:"; +const HEX_COLOR = /^#[0-9a-f]{6}$/; + +function valid(value: string | null): string | null { + if (value === null) return null; + if (HEX_COLOR.test(value)) return value; + const slot = Number(value); + return Number.isInteger(slot) && slot >= 1 && slot <= PROJECT_COLOR_COUNT ? value : null; +} + +export function tabColorOverride(root: string): string | null { + return valid(localStorage.getItem(KEY_PREFIX + root)); +} + +export function setTabColorOverride(root: string, value: string | null): void { + if (value === null) localStorage.removeItem(KEY_PREFIX + root); + else localStorage.setItem(KEY_PREFIX + root, value.toLowerCase()); + emit(); +} + +const listeners = new Set<() => void>(); +let version = 0; + +function emit() { + version++; + for (const listener of listeners) listener(); +} + +/** Bumped on every local or cross-window change; a useSyncExternalStore snapshot. */ +export function tabColorsVersion(): number { + return version; +} + +export function subscribeTabColors(listener: () => void): () => void { + listeners.add(listener); + const onStorage = (e: StorageEvent) => { + if (e.key === null || e.key.startsWith(KEY_PREFIX)) emit(); + }; + window.addEventListener("storage", onStorage); + return () => { + listeners.delete(listener); + window.removeEventListener("storage", onStorage); + }; +} + +export function tabColorVars(name: string, override: string | null): Record { + if (override === null) return projectColorVars(name); + if (override.startsWith("#")) return { "--project-color": override, "--project-color-end": override }; + return projectColorSlotVars(Number(override)); +} From bd27eb5474a796b457126ea87766bf4144b49462 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:25:08 +0200 Subject: [PATCH 06/16] fix(agents): preserve effort for pending model switches (#4487) In an existing chat, a model that only appeared after Refresh models could be selected but its effort levels stayed unavailable until a message was sent, because the refreshed catalog listed the model without the settings a session reports for it. Selecting such a model now discovers its settings without a prompt and keeps the model and chosen effort as a pending switch; the next message reloads the same session, applies the model and the effort, then sends. If either is rejected, the previous selection is restored and nothing is sent. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- crates/ide-agent/src/catalogs.rs | 32 ++ crates/ide-agent/src/catalogs/tests.rs | 218 +++++++-- crates/ide-agent/src/lib.rs | 421 +++++++++++++----- crates/ide-agent/src/tests.rs | 2 +- docs/en/guide/agents.mdx | 2 +- docs/zh/guide/agents.mdx | 2 +- e2e/agentCycleEffort.spec.ts | 58 ++- .../agents/session/SessionComposer.tsx | 39 +- 8 files changed, 617 insertions(+), 157 deletions(-) diff --git a/crates/ide-agent/src/catalogs.rs b/crates/ide-agent/src/catalogs.rs index 8fd948c84e..46f6d1c8ea 100644 --- a/crates/ide-agent/src/catalogs.rs +++ b/crates/ide-agent/src/catalogs.rs @@ -256,6 +256,38 @@ impl AgentCatalogs { .cloned() } + pub(super) async fn load_levels( + self: &Arc, + shared: &Arc, + provider: &str, + model: &str, + ) -> Result, String> { + if let Some(levels) = self.levels(shared, provider, model) { + return Ok(levels); + } + let unavailable = || "The agent did not report settings for the selected model".to_owned(); + let spec = shared.spec(provider).ok_or_else(unavailable)?; + let (_, flight) = self.request(shared, spec, false, Some(model)); + if let Some(mut ready) = flight { + while !*ready.borrow_and_update() { + if ready.changed().await.is_err() { + break; + } + } + } + self.levels(shared, provider, model).ok_or_else(|| { + let state = self.state.lock(); + state + .entries + .get(&Self::key(shared, provider)) + .and_then(|entry| { + entry.model_failures.get(model).map(|failure| &failure.error).or(entry.error.as_ref()) + }) + .cloned() + .unwrap_or_else(unavailable) + }) + } + pub(crate) fn evict_if_idle(&self, shared: &Shared, provider: &str) { let key = Self::key(shared, provider); let mut state = self.state.lock(); diff --git a/crates/ide-agent/src/catalogs/tests.rs b/crates/ide-agent/src/catalogs/tests.rs index 703f52e4dc..cdd749b9ea 100644 --- a/crates/ide-agent/src/catalogs/tests.rs +++ b/crates/ide-agent/src/catalogs/tests.rs @@ -323,6 +323,36 @@ async fn discovered_model_can_be_selected_while_the_session_is_not_running() { switch_chat_model(ChatSwitch::Idle).await; } +#[tokio::test] +async fn discovered_model_effort_is_discovered_persisted_and_applied_before_the_first_reply() { + switch_chat_model(ChatSwitch::Uncached).await; +} + +#[tokio::test] +async fn discovered_model_with_no_effort_can_be_selected() { + switch_chat_model(ChatSwitch::NoEffort).await; +} + +#[tokio::test] +async fn discovered_model_settings_failure_leaves_the_chat_unchanged() { + switch_chat_model(ChatSwitch::DiscoveryFails).await; +} + +#[tokio::test] +async fn discovered_model_withdrawn_effort_prevents_sending() { + switch_chat_model(ChatSwitch::EffortUnavailable).await; +} + +#[tokio::test] +async fn discovered_model_rejected_effort_prevents_sending() { + switch_chat_model(ChatSwitch::EffortRejected).await; +} + +#[tokio::test] +async fn discovered_model_lookup_does_not_overwrite_a_newer_selection() { + switch_chat_model(ChatSwitch::Superseded).await; +} + #[derive(Clone, Copy)] enum ChatSwitch { Live, @@ -330,6 +360,12 @@ enum ChatSwitch { ResumeFails, Unavailable, Idle, + Uncached, + NoEffort, + DiscoveryFails, + EffortUnavailable, + EffortRejected, + Superseded, } async fn switch_chat_model(scenario: ChatSwitch) { @@ -376,7 +412,21 @@ async fn switch_chat_model(scenario: ChatSwitch) { } let before_entries = serde_json::to_value(manager.entries(&task.id, None).unwrap()).unwrap(); let before_config = manager.task(&task.id).unwrap().state.lock().task.config.clone(); - if matches!(scenario, ChatSwitch::Idle) { + let offline = matches!(scenario, ChatSwitch::Idle | ChatSwitch::Uncached | ChatSwitch::Superseded); + let missing_settings = matches!( + scenario, + ChatSwitch::Uncached | ChatSwitch::NoEffort | ChatSwitch::DiscoveryFails | ChatSwitch::Superseded + ); + let no_effort = matches!(scenario, ChatSwitch::NoEffort); + let effort_error = match scenario { + ChatSwitch::EffortUnavailable => Some("no longer offers effort value thorough"), + ChatSwitch::EffortRejected => Some("effort rejected by the agent"), + _ => None, + }; + let choose_effort = matches!(scenario, ChatSwitch::Uncached) || effort_error.is_some(); + let (catalog_models, catalog_effort): (&[&str], &[&str]) = + if missing_settings { (&["old", "new"], &["low", "high"]) } else { (&["new", "old"], &["quick", "thorough"]) }; + if offline { manager.shutdown(); manager = make_manager(tmp.path(), Arc::default(), &harness); } @@ -385,41 +435,122 @@ async fn switch_chat_model(scenario: ChatSwitch) { assert!(manager.refresh_models(PROVIDER, false, None).unwrap().refreshing); let next = harness.next().await; assert_eq!((next.launch, next.method.as_str()), (1, "session/new")); - next.reply.send(Ok(response(&["new", "old"], &["catalog-only"]))).unwrap(); - assert_eq!(model_values(&completed(&mut events).await), ["new", "old"]); + next.reply.send(Ok(response(catalog_models, catalog_effort))).unwrap(); + let catalog = completed(&mut events).await; + assert_eq!(model_values(&catalog), catalog_models); + if missing_settings { + assert!(!catalog.thought_levels.contains_key("new")); + } assert_eq!(manager.task(&task.id).unwrap().state.lock().task.config, before_config); let live = matches!(scenario, ChatSwitch::Live); - let offline = matches!(scenario, ChatSwitch::Idle); + let resumed_launch = if missing_settings { 3 } else { 2 }; let load_fails = matches!(scenario, ChatSwitch::ResumeFails); let unavailable = matches!(scenario, ChatSwitch::Unavailable); - let switching = manager.set_config(&task.id, "model", "new".into()); - tokio::pin!(switching); - if !offline { - let next = next_chat_request(&mut harness, switching.as_mut()).await; - assert_eq!((next.launch, next.method.as_str()), (0, "session/set_config_option")); - assert_eq!(next.params, json!({"sessionId": "saved-chat", "configId": "model", "value": "new"})); - if live { - next.reply.send(Ok(response(&["new", "old"], &["session-only"]))).unwrap(); - } else { - next.reply.send(Err("not in this process's model list".into())).unwrap(); + { + let switching = manager.set_config(&task.id, "model", "new".into()); + tokio::pin!(switching); + if !offline { + let next = next_chat_request(&mut harness, switching.as_mut()).await; + assert_eq!((next.launch, next.method.as_str()), (0, "session/set_config_option")); + assert_eq!(next.params, json!({"sessionId": "saved-chat", "configId": "model", "value": "new"})); + if live { + next.reply.send(Ok(response(&["new", "old"], &["session-only"]))).unwrap(); + } else { + next.reply.send(Err("not in this process's model list".into())).unwrap(); + } + } + if missing_settings { + let discovery = next_chat_request(&mut harness, switching.as_mut()).await; + assert_eq!((discovery.launch, discovery.method.as_str()), (2, "session/new")); + discovery.reply.send(Ok(response(catalog_models, catalog_effort))).unwrap(); + let set = next_chat_request(&mut harness, switching.as_mut()).await; + assert_eq!(set.params, json!({"sessionId": "discovery-only", "configId": "model", "value": "new"})); + assert_eq!(set.method, "session/set_config_option"); + assert!( + manager + .prompt(&task.id, AgentPrompt { text: "too early".into(), ..Default::default() }, false) + .await + .is_err() + ); + if matches!(scenario, ChatSwitch::DiscoveryFails) { + set.reply.send(Err("Sign in required".into())).unwrap(); + let error = switching.await.unwrap_err().to_string(); + assert!(error.contains("Sign in required"), "{error}"); + assert_eq!(manager.subscribe(Arc::new(|_| {})).remove(0).config, before_config); + assert!(harness.pending.try_recv().is_err()); + manager.shutdown(); + return; + } + if matches!(scenario, ChatSwitch::Superseded) { + manager.set_config(&task.id, "model", "old".into()).await.unwrap(); + set.reply.send(Ok(response(&["new", "old"], &["quick", "thorough"]))).unwrap(); + switching.await.unwrap(); + let task = manager.subscribe(Arc::new(|_| {})).remove(0); + assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old")); + assert_eq!(task.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("low")); + assert!(harness.pending.try_recv().is_err()); + manager.shutdown(); + return; + } + let levels: &[&str] = if no_effort { &[] } else { &["quick", "thorough"] }; + set.reply.send(Ok(response(&["new", "old"], levels))).unwrap(); + } + tokio::select! { + result = &mut switching => result.unwrap(), + request = harness.next() => panic!("selection must not reopen the chat or send: {request:?}"), } } - // A fallback selection settles without waiting for a new process. - tokio::select! { - result = &mut switching => result.unwrap(), - request = harness.next() => panic!("selection must not open another session: {request:?}"), - } assert_eq!(serde_json::to_value(manager.entries(&task.id, None).unwrap()).unwrap(), before_entries); + if matches!(scenario, ChatSwitch::Uncached) { + let update = tokio::time::timeout(Duration::from_secs(5), async { + loop { + if let AgentEvent::Task { task: update } = events.recv().await.unwrap() + && update.id == task.id + { + break update; + } + } + }) + .await + .unwrap(); + let effort = update.config.iter().find(|o| o.id == "effort").unwrap(); + assert_eq!(effort.values.iter().map(|v| v.value.as_str()).collect::>(), ["quick", "thorough"]); + } let snapshot = |manager: &AgentManager| manager.subscribe(Arc::new(|_| {})).remove(0); let current = snapshot(&manager); assert_eq!(current.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("new")); assert_eq!(current.model.as_deref(), Some(if live { "new" } else { "old" })); + let effort = + |task: &crate::AgentTask| task.config.iter().find(|o| o.id == "effort").and_then(|o| o.current.clone()); + assert_eq!( + effort(¤t).as_deref(), + if live { + Some("session-only") + } else if no_effort { + None + } else { + Some("quick") + }, + "the new model's effort must be available before sending" + ); + if choose_effort { + assert!(manager.set_config(&task.id, "effort", "high".into()).await.is_err()); + manager.set_config(&task.id, "effort", "thorough".into()).await.unwrap(); + assert_eq!(effort(&snapshot(&manager)).as_deref(), Some("thorough")); + if matches!(scenario, ChatSwitch::Uncached) { + manager.shutdown(); + manager = make_manager(tmp.path(), Arc::default(), &harness); + let restored = snapshot(&manager); + assert_eq!(restored.id, task.id); + assert_eq!(effort(&restored).as_deref(), Some("thorough")); + } + } manager.prompt(&task.id, AgentPrompt { text: "next".into(), ..Default::default() }, false).await.unwrap(); if !live { let load = harness.next().await; - assert_eq!((load.launch, load.method.as_str()), (2, "session/load")); + assert_eq!((load.launch, load.method.as_str()), (resumed_launch, "session/load")); assert_eq!(load.params["sessionId"], "saved-chat"); load.notifications .send(json!({"jsonrpc": "2.0", "method": "session/update", "params": { @@ -447,6 +578,7 @@ async fn switch_chat_model(scenario: ChatSwitch) { let task = snapshot(&manager); assert_eq!(task.model.as_deref(), Some("old")); assert_eq!(task.config.iter().find(|o| o.id == "model").unwrap().current.as_deref(), Some("old")); + assert_eq!(effort(&task).as_deref(), Some("low")); let expected = if load_fails { "cannot resume saved-chat" } else { "does not offer model new" }; assert!(task.error.as_deref().unwrap().contains(expected), "{:?}", task.error); assert!(harness.pending.try_recv().is_err(), "must not send on the previous model or create a session"); @@ -472,24 +604,60 @@ async fn switch_chat_model(scenario: ChatSwitch) { return; } let set = harness.next().await; - assert_eq!((set.launch, set.method.as_str()), (2, "session/set_config_option")); + assert_eq!((set.launch, set.method.as_str()), (resumed_launch, "session/set_config_option")); assert_eq!(set.params, json!({"sessionId": "saved-chat", "configId": "model", "value": "new"})); - set.reply.send(Ok(response(&["new", "old"], &["session-only"]))).unwrap(); + let levels: &[&str] = match scenario { + ChatSwitch::NoEffort => &[], + ChatSwitch::EffortUnavailable => &["session-only", "quick"], + _ if choose_effort => &["session-only", "thorough"], + _ => &["session-only"], + }; + set.reply.send(Ok(response(&["new", "old"], levels))).unwrap(); let set = harness.next().await; - assert_eq!((set.launch, set.method.as_str()), (2, "session/set_mode")); + assert_eq!((set.launch, set.method.as_str()), (resumed_launch, "session/set_mode")); assert_eq!(set.params, json!({"sessionId": "saved-chat", "modeId": "ask"})); set.reply.send(Ok(json!({}))).unwrap(); + if choose_effort && !matches!(scenario, ChatSwitch::EffortUnavailable) { + let set = harness.next().await; + assert_eq!((set.launch, set.method.as_str()), (resumed_launch, "session/set_config_option")); + assert_eq!(set.params, json!({"sessionId": "saved-chat", "configId": "effort", "value": "thorough"})); + let reply = if effort_error.is_some() { + Err("effort rejected by the agent".into()) + } else { + Ok(response(&["new", "old"], &["thorough", "session-only"])) + }; + set.reply.send(reply).unwrap(); + } + if let Some(expected) = effort_error { + wait_for_chat(&manager, &task.id, AgentStatus::Failed).await; + let current = snapshot(&manager); + assert_eq!(current.model.as_deref(), Some("old")); + assert_eq!(effort(¤t).as_deref(), Some("low")); + assert!(current.error.as_deref().unwrap().contains(expected), "{:?}", current.error); + assert!(harness.pending.try_recv().is_err(), "must not send using a fallback effort"); + manager.shutdown(); + return; + } } let next = harness.next().await; assert_eq!( (next.launch, next.method.as_str(), &next.params["sessionId"]), - (if live { 0 } else { 2 }, "session/prompt", &json!("saved-chat")) + (if live { 0 } else { resumed_launch }, "session/prompt", &json!("saved-chat")) ); next.reply.send(Ok(json!({"stopReason": "end_turn"}))).unwrap(); wait_for_chat(&manager, &task.id, AgentStatus::Ready).await; let current = snapshot(&manager); assert_eq!(current.model.as_deref(), Some("new")); - assert_eq!(current.config.iter().find(|o| o.id == "effort").unwrap().current.as_deref(), Some("session-only")); + assert_eq!( + effort(¤t).as_deref(), + if choose_effort { + Some("thorough") + } else if no_effort { + None + } else { + Some("session-only") + } + ); assert_eq!(current.config.iter().find(|o| o.id == "mode").unwrap().current.as_deref(), Some("ask")); manager.shutdown(); } diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 0e401130ad..a0eb4e4c8d 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -357,9 +357,11 @@ struct TaskFile { /// Settings the user chose, re-applied to every new or reloaded session. #[serde(default)] wanted: Vec, - /// Option id of a discovered model in `wanted` that still needs a same-session reload. - #[serde(default, skip_serializing_if = "Option::is_none")] + /// Pending model option id in task files saved before pending settings were stored separately. + #[serde(default, skip_serializing)] pending_model: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pending_switch: Option, /// In the project's own checkout: files already changed when the task started. #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] before: BTreeMap, @@ -384,6 +386,26 @@ struct TaskFile { title_renamed: bool, } +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +struct PendingModel { + model: AgentConfigChoice, + candidate: Option, + options: Vec, + choices: Vec, +} + +impl PendingModel { + fn apply(&self, wanted: &mut Vec, confirmed: &[AgentConfigOption]) { + wanted.retain(|choice| { + choice.id != self.model.id + && !self.options.iter().any(|o| o.id == choice.id) + && !confirmed.iter().any(|o| o.id == choice.id && config::is_per_model_option(o)) + }); + wanted.push(self.model.clone()); + wanted.extend(self.choices.iter().cloned()); + } +} + /// The changed files of a checkout, stamped. type Snapshot = BTreeMap; @@ -392,8 +414,9 @@ struct TaskState { session_id: Option, conversation: Conversation, wanted: Vec, - pending_model: Option, + pending_model: Option, model_choice: u64, + discovering_model: Option, before: Arc>, saved: Option, /// See `TaskFile::touched`. @@ -415,23 +438,43 @@ struct TaskState { } impl TaskState { - fn pending_model(&self) -> Option<&AgentConfigChoice> { - let id = self.pending_model.as_deref()?; - self.wanted.iter().find(|c| c.id == id) - } - fn snapshot(&self) -> AgentTask { let mut task = self.task.clone(); - if let Some(choice) = self.pending_model() - && let Some(model) = task.config.iter_mut().find(|o| o.id == choice.id) + if let Some(pending) = &self.pending_model + && let Some(model) = task.config.iter_mut().find(|o| o.id == pending.model.id) { - model.current = Some(choice.value.clone()); + model.current = Some(pending.model.value.clone()); + if let Some(candidate) = &pending.candidate + && !model.values.iter().any(|v| v.value == candidate.value) + { + model.values.push(candidate.clone()); + } task.config.retain(|o| !config::is_per_model_option(o)); + task.config.extend(pending.options.iter().cloned().map(|mut option| { + if let Some(choice) = pending.choices.iter().find(|choice| choice.id == option.id) { + option.current = Some(choice.value.clone()); + } + option + })); } task } } +struct DiscoveringModel<'a> { + state: &'a Mutex, + generation: u64, +} + +impl Drop for DiscoveringModel<'_> { + fn drop(&mut self) { + let mut s = self.state.lock(); + if s.discovering_model == Some(self.generation) { + s.discovering_model = None; + } + } +} + /// A running agent and its session. #[derive(Clone)] struct Live { @@ -796,6 +839,7 @@ impl AgentManager { entries: Vec::new(), wanted: Vec::new(), pending_model: None, + pending_switch: None, before: BTreeMap::new(), saved: None, touched: Some(BTreeSet::new()), @@ -912,6 +956,7 @@ impl AgentManager { entries: Vec::new(), wanted: req.config, pending_model: None, + pending_switch: None, before, saved, touched: (req.isolation == Isolation::Local).then(BTreeSet::new), @@ -949,6 +994,9 @@ impl AgentManager { if s.task.status == AgentStatus::Archived { return Err(IdeError::invalid("the task is archived")); } + if s.discovering_model.is_some() { + return Err(IdeError::unavailable("Model settings are still loading")); + } if s.busy { let item = AgentQueued { id: uuid::Uuid::new_v4().simple().to_string(), prompt }; if now { @@ -1068,6 +1116,24 @@ impl AgentManager { let task = self.task(id)?; let (target, change) = { let mut s = task.state.lock(); + let busy = s.busy; + let archived = s.task.status == AgentStatus::Archived; + if let Some(pending) = &mut s.pending_model + && let Some(target) = pending.options.iter().find(|o| o.id == option) + { + if archived || busy { + return Err(IdeError::invalid("The pending model settings cannot be changed now")); + } + if !target.values.iter().any(|v| v.value == value) { + return Err(IdeError::invalid(format!("{} has no value {value}", target.name))); + } + pending.choices.retain(|c| c.id != option); + pending.choices.push(AgentConfigChoice { id: option.to_owned(), value }); + drop(s); + task.persist(); + task.emit_task(); + return Ok(()); + } let target = s .task .config @@ -1075,6 +1141,9 @@ impl AgentManager { .find(|o| o.id == option) .ok_or_else(|| IdeError::not_found("no such setting"))? .clone(); + if s.pending_model.is_some() && config::is_per_model_option(&target) { + return Err(IdeError::invalid("This setting is not available on the selected model")); + } if !target.values.iter().any(|v| v.value == value) { if target.category.as_deref() != Some("model") { return Err(IdeError::invalid(format!("{} has no value {value}", target.name))); @@ -1083,8 +1152,12 @@ impl AgentManager { } else { let switching_model = target.category.as_deref() == Some("model"); if switching_model { + if s.pending_model.is_some() && s.busy { + return Err(IdeError::invalid("The pending model settings cannot be changed now")); + } s.model_choice += 1; s.pending_model = None; + s.discovering_model = None; } let previous_levels = (switching_model && target.current.as_deref() != Some(value.as_str())) .then(|| s.task.config.extract_if(.., |o| config::is_per_model_option(o)).collect::>()); @@ -1116,33 +1189,19 @@ impl AgentManager { && (previous.as_deref() != Some(value.as_str()) || !model_options) { let provider = task.state.lock().task.provider.clone(); - let mut levels = self.shared.paths.catalogs.levels(&self.shared, &provider, &value); - let mut error = None; - if levels.is_none() - && let Some(spec) = self.shared.spec(&provider) - { - let (catalog, flight) = self.shared.paths.catalogs.request(&self.shared, spec, false, Some(&value)); - error = catalog.error; - if let Some(mut ready) = flight { - while !*ready.borrow_and_update() { - if ready.changed().await.is_err() { - break; - } - } - } - levels = self.shared.paths.catalogs.levels(&self.shared, &provider, &value); - } + let levels = self.shared.paths.catalogs.load_levels(&self.shared, &provider, &value).await; // Another selection may have superseded this discovery while it was waiting. if task.state.lock().model_choice != model_choice { return Ok(()); } - let Some(levels) = levels else { - restore_config_choice(&task, &target, &value, previous.as_deref(), model_choice, previous_levels); - task.persist(); - task.emit_task(); - return Err(IdeError::unavailable( - error.unwrap_or_else(|| "The agent did not report settings for the selected model".into()), - )); + let levels = match levels { + Ok(levels) => levels, + Err(error) => { + restore_config_choice(&task, &target, &value, previous.as_deref(), model_choice, previous_levels); + task.persist(); + task.emit_task(); + return Err(IdeError::unavailable(error)); + } }; let mut s = task.state.lock(); if s.model_choice != model_choice { @@ -1265,6 +1324,7 @@ impl AgentManager { entries, wanted: s.wanted.clone(), pending_model: None, + pending_switch: None, before: (*s.before).clone(), saved: s.saved.clone(), touched: s.touched.as_deref().cloned(), @@ -1310,6 +1370,8 @@ impl AgentManager { }; s.session_id = None; s.pending_model = None; + s.model_choice += 1; + s.discovering_model = None; s.conversation = Conversation::default(); // The fresh session reports its own usage; nothing carries over. s.task.usage = None; @@ -1908,6 +1970,24 @@ impl Task { let mut task = file.task; config::add_client_options(&task.provider, &mut task.config); let conversation = Conversation::restore(file.entries, file.subagents); + let mut wanted = file.wanted; + let pending_model = file.pending_switch.or_else(|| { + let id = file.pending_model?; + let index = wanted.iter().position(|choice| choice.id == id)?; + let model = wanted.remove(index); + if let Some(value) = task.model.clone() { + wanted.push(AgentConfigChoice { id, value }); + } + let catalog = shared.paths.catalogs.cached(&shared, &task.provider); + let candidate = catalog + .config + .iter() + .find(|o| o.category.as_deref() == Some("model")) + .and_then(|o| o.values.iter().find(|v| v.value == model.value)) + .cloned(); + let options = catalog.thought_levels.get(&model.value).cloned().unwrap_or_default(); + Some(PendingModel { model, candidate, options, choices: Vec::new() }) + }); Arc::new(Self { id: task.id.clone(), shared, @@ -1915,9 +1995,10 @@ impl Task { task, session_id: file.session_id, conversation, - wanted: file.wanted, - pending_model: file.pending_model, + wanted, + pending_model, model_choice: 0, + discovering_model: None, before: Arc::new(file.before), saved: file.saved, touched: file.touched.map(Arc::new), @@ -2111,7 +2192,8 @@ impl Task { session_id: s.session_id.clone(), entries: s.conversation.main.entries.clone(), wanted: s.wanted.clone(), - pending_model: s.pending_model.clone(), + pending_model: None, + pending_switch: s.pending_model.clone(), before: (*s.before).clone(), saved: s.saved.clone(), touched: s.touched.as_deref().cloned(), @@ -2264,13 +2346,18 @@ impl Task { let candidate = self.shared.paths.catalogs.fresh_model(&self.shared, &spec, &value).ok_or_else(|| { IdeError::invalid(format!("{} has no value {value} in the current model catalog", target.name)) })?; - let model_choice = { + let selection = { let mut s = self.state.lock(); + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("the task is archived")); + } s.model_choice += 1; - s.model_choice + s.discovering_model = Some(s.model_choice); + DiscoveringModel { state: &self.state, generation: s.model_choice } }; + let model_choice = selection.generation; // A prompt starting during the switch must not grab the peer we're about to recycle. - let _connecting = self.connecting.lock().await; + let connecting = self.connecting.lock().await; { let s = self.state.lock(); if s.model_choice != model_choice { @@ -2293,16 +2380,16 @@ impl Task { Ok(None) }; - let accepted = { - let mut s = self.state.lock(); - if s.model_choice != model_choice { - return Ok(()); - } - if s.task.status == AgentStatus::Archived { - return Err(IdeError::invalid("the task is archived")); - } - let pending = match result { - Ok(Some(reply)) => { + let refused = match result { + Ok(Some(reply)) => { + let (config, model) = { + let mut s = self.state.lock(); + if s.model_choice != model_choice { + return Ok(()); + } + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("the task is archived")); + } if let Some(options) = reply.get("configOptions") { config::merge_update(&mut s.task.config, options); } else if s.task.model.as_deref() != Some(value.as_str()) { @@ -2321,36 +2408,66 @@ impl Task { model.current = Some(value.clone()); s.task.model = Some(value.clone()); sync_usage_context_size(&mut s.task); - false - } - refused => { - if s.session_id.is_none() - || live.as_ref().is_some_and(|l| !l.resumable) - || self.start_fresh.load(Ordering::Acquire) - { - return Err(IdeError::unavailable( - refused.err().unwrap_or_else(|| "The agent does not support resuming this session.".into()), - )); - } - if s.busy || !s.background_tasks.is_empty() || !self.permissions.lock().is_empty() { - return Err(IdeError::invalid("wait until the agent is done")); - } - true - } - }; - s.wanted.retain(|c| c.id != target.id); - s.pending_model = pending.then(|| target.id.clone()); - s.wanted.push(AgentConfigChoice { id: target.id, value }); - (!pending).then(|| { - let model = s.task.model.clone().filter(|_| s.task.config.iter().any(config::is_per_model_option)); - (s.task.config.clone(), model) - }) + s.pending_model = None; + s.wanted.retain(|c| c.id != target.id); + s.wanted.push(AgentConfigChoice { id: target.id, value }); + let model = s.task.model.clone().filter(|_| s.task.config.iter().any(config::is_per_model_option)); + (s.task.config.clone(), model) + }; + self.shared.remember(&provider, Some(&config), None, model.as_deref()); + self.persist(); + self.emit_task(); + return Ok(()); + } + refused => refused, }; - if let Some((config, model)) = accepted { - self.shared.remember(&provider, Some(&config), None, model.as_deref()); - } else { - self.recycle_resumable_session(); + { + let s = self.state.lock(); + if s.model_choice != model_choice { + return Ok(()); + } + if s.session_id.is_none() + || live.as_ref().is_some_and(|l| !l.resumable) + || self.start_fresh.load(Ordering::Acquire) + { + return Err(IdeError::unavailable( + refused.err().unwrap_or_else(|| "The agent does not support resuming this session.".into()), + )); + } + if s.busy || !s.background_tasks.is_empty() || !self.permissions.lock().is_empty() { + return Err(IdeError::invalid("wait until the agent is done")); + } } + // Catalog discovery never owns the chat session. Let a newer model choice supersede it. + drop(connecting); + let options = self.shared.paths.catalogs.load_levels(&self.shared, &provider, &value).await; + let _connecting = self.connecting.lock().await; + { + let mut s = self.state.lock(); + if s.model_choice != model_choice { + return Ok(()); + } + if s.task.status == AgentStatus::Archived { + return Err(IdeError::invalid("the task is archived")); + } + if s.busy || !s.background_tasks.is_empty() || !self.permissions.lock().is_empty() { + return Err(IdeError::invalid("wait until the agent is done")); + } + let options = options.map_err(IdeError::unavailable)?; + let choices = s + .pending_model + .take() + .filter(|pending| pending.model.value == value) + .map(|pending| pending.choices) + .unwrap_or_default(); + s.pending_model = Some(PendingModel { + model: AgentConfigChoice { id: target.id, value }, + candidate: Some(candidate), + options, + choices, + }); + } + self.recycle_resumable_session(); self.persist(); self.emit_task(); Ok(()) @@ -2612,10 +2729,9 @@ impl Task { } let (provider_id, cwd, saved, pending) = { let s = self.state.lock(); - let pending = s.pending_model().map(|choice| (choice.clone(), s.task.model.clone())); - (s.task.provider.clone(), s.task.cwd.0.clone(), s.session_id.clone(), pending) + (s.task.provider.clone(), s.task.cwd.0.clone(), s.session_id.clone(), s.pending_model.clone()) }; - let pending_model = pending.as_ref().map(|(choice, _)| choice); + let pending_model = pending.as_ref(); let raw_spec = self.shared.spec(&provider_id).ok_or_else(|| format!("unknown agent {provider_id}"))?; let can_fallback = raw_spec.driver == provider::Driver::Copilot && !self.shared.uses_copilot_acp_fallback(&raw_spec); @@ -2641,22 +2757,12 @@ impl Task { let live = match opened { Ok(live) => live, Err(err) => { - if let Some((choice, previous)) = pending { - let mut s = self.state.lock(); - if s.pending_model() == Some(&choice) { - s.pending_model = None; - s.wanted.retain(|c| c.id != choice.id); - if let Some(model) = s.task.config.iter_mut().find(|o| o.id == choice.id) { - model.current.clone_from(&previous); - } - s.task.model.clone_from(&previous); - if let Some(value) = previous { - s.wanted.push(AgentConfigChoice { id: choice.id, value }); - } - drop(s); - self.persist(); - self.emit_task(); - } + let mut s = self.state.lock(); + if pending.is_some() && s.pending_model == pending { + s.pending_model = None; + drop(s); + self.persist(); + self.emit_task(); } return Err(err.message); } @@ -2671,7 +2777,7 @@ impl Task { spec: provider::ProviderSpec, cwd: &Path, saved: Option, - pending_model: Option<&AgentConfigChoice>, + pending_model: Option<&PendingModel>, ) -> Result { let launch_cwd = cwd.to_path_buf(); let mut spec = tokio::task::spawn_blocking(move || spec.resolve_for_launch(&launch_cwd)) @@ -2697,14 +2803,15 @@ impl Task { } }); // Speaks ACP v1 or v2, whichever the agent chooses; the task sees v1 either way. - let client = acp::Dialect::wrap(Arc::new(Client { task: Arc::downgrade(self) })); + let client = Client::new(self, saved.as_deref().filter(|_| pending_model.is_some())); + let handler = acp::Dialect::wrap(client.clone()); let raw_peer = - (self.shared.connector)(&spec, cwd, client.clone(), on_stderr).map_err(|e| SessionOpenError { + (self.shared.connector)(&spec, cwd, handler.clone(), on_stderr).map_err(|e| SessionOpenError { message: format!("Couldn't start {} (`{}`): {e}", spec.name, spec.command), allow_acp_fallback: !native::copilot::is_missing_binary_error(&e), })?; let mut stop_on_err = KillOnDrop(Some(raw_peer.clone())); - let peer = acp::Conn::new(raw_peer, client); + let peer = acp::Conn::new(raw_peer, handler); let init = peer.initialize(&client_info()).await.map_err(|e| { let is_auth = matches!(&e, RpcError::Server { code, message, .. } if acp::auth_required(*code, message)); @@ -2803,7 +2910,13 @@ impl Task { // The session's settings, then the user's choices on top. // A session that reports none keeps the last known ones, but what is set is unknown. - let reported = config::options_of(&result); + let mut reported = config::options_of(&result); + if let Some(update) = client.take_opening_config() + && let Some(config) = update.get("configOptions") + && reported.iter().all(|o| o.category.as_deref() != Some("model")) + { + config::merge_update(&mut reported, config); + } let known = !reported.is_empty(); if known { self.shared.remember(provider_id, Some(&reported), None, model_of(&reported).as_deref()); @@ -2811,19 +2924,33 @@ impl Task { let (mut options, mut wanted) = { let s = self.state.lock(); let options = if known { reported } else { s.task.config.clone() }; - let wanted = s.wanted.clone(); + let mut wanted = s.wanted.clone(); + if let Some(pending) = pending_model { + pending.apply(&mut wanted, &s.task.config); + } (options, wanted) }; config::add_client_options(provider_id, &mut options); // Changing model can replace the effort / context-tier choices; validate those only afterwards. - wanted.sort_by_key(|c| match options.iter().find(|o| o.id == c.id) { - Some(o) if o.category.as_deref() == Some("model") => 0, - Some(o) if config::is_per_model_option(o) => 2, - _ => 1, + wanted.sort_by_key(|c| { + if let Some(pending) = pending_model { + if c == &pending.model { + return 0; + } + if pending.choices.contains(c) { + return 2; + } + } + match options.iter().find(|o| o.id == c.id) { + Some(o) if o.category.as_deref() == Some("model") => 0, + Some(o) if config::is_per_model_option(o) => 2, + _ => 1, + } }); let mut model_options = known; for choice in &wanted { - let pending = pending_model == Some(choice); + let pending = pending_model.is_some_and(|p| &p.model == choice); + let explicit = pending_model.is_some_and(|p| p.choices.contains(choice)); if pending && !options.iter().any(|o| { o.id == choice.id @@ -2836,6 +2963,19 @@ impl Task { allow_acp_fallback: false, }); } + if explicit + && (!model_options + || !options.iter().any(|o| { + o.id == choice.id + && config::is_per_model_option(o) + && o.values.iter().any(|v| v.value == choice.value) + })) + { + return Err(SessionOpenError { + message: format!("The selected model no longer offers {} value {}.", choice.id, choice.value), + allow_acp_fallback: false, + }); + } // An option the session doesn't offer yet is set once it does (`apply_late_choices`). let Some(o) = options.iter().find(|o| o.id == choice.id).cloned() else { continue }; if o.id == config::CURSOR_APPROVAL { @@ -2847,7 +2987,7 @@ impl Task { if config::is_per_model_option(&o) && !model_options { continue; } - let already = known && o.current.as_deref() == Some(choice.value.as_str()); + let already = (known || explicit) && o.current.as_deref() == Some(choice.value.as_str()); if already || !o.values.iter().any(|v| v.value == choice.value) { continue; } @@ -2856,14 +2996,30 @@ impl Task { params["sessionId"] = json!(session_id); match peer.request::<_, Value>(method, params, None).await { Ok(reply) => { - if pending && !config::accepts_model(&reply, &o.id, &choice.value) { + let observed = client.take_opening_config(); + let report = + if reply.get("configOptions").is_some() { &reply } else { observed.as_ref().unwrap_or(&reply) }; + if pending && !config::accepts_model(report, &o.id, &choice.value) { return Err(SessionOpenError { message: format!("The reloaded session did not switch to model {}.", choice.value), allow_acp_fallback: false, }); } - if let Some(fresh) = reply.get("configOptions") { + if let Some(fresh) = report.get("configOptions") { config::merge_update(&mut options, fresh); + if explicit + && !options.iter().any(|option| { + option.id == choice.id && option.current.as_deref() == Some(choice.value.as_str()) + }) + { + return Err(SessionOpenError { + message: format!( + "The selected model did not accept {} value {}.", + choice.id, choice.value + ), + allow_acp_fallback: false, + }); + } model_options = true; } else if o.category.as_deref() == Some("model") { if o.current.as_deref() != Some(choice.value.as_str()) { @@ -2875,7 +3031,7 @@ impl Task { o.current = Some(choice.value.clone()); } } - Err(e) if pending => { + Err(e) if pending || explicit => { return Err(SessionOpenError { message: self.describe(e), allow_acp_fallback: false }); } Err(e) => tracing::warn!("agent task {}: setting {} to {} failed: {e}", self.id, o.id, choice.value), @@ -2885,6 +3041,16 @@ impl Task { self.shared.remember(provider_id, Some(&options), None, model.as_deref()); { let mut s = self.state.lock(); + if let Some(pending) = pending_model { + if s.pending_model.as_ref() != Some(pending) { + return Err(SessionOpenError { + message: "The pending model settings changed while reopening the session.".into(), + allow_acp_fallback: false, + }); + } + let TaskState { task, wanted, .. } = &mut *s; + pending.apply(wanted, &task.config); + } s.task.model = model_of(&options).or(s.task.model.take()); s.task.config = options; s.pending_model = None; @@ -2894,6 +3060,7 @@ impl Task { // The (re)started process runs nothing yet: whatever it reports next is all of it. s.background_tasks = Vec::new(); s.task.background.clear(); + *client.opening_config.lock() = None; } self.persist(); self.emit_task(); @@ -3361,6 +3528,28 @@ impl Task { /// Answers the agent's requests on behalf of one task. struct Client { task: Weak, + opening_config: Mutex>, +} + +/// Config replays belong to the candidate connection until its model and settings are confirmed. +struct OpeningConfig { + session: String, + options: Option, +} + +impl Client { + fn new(task: &Arc, opening_session: Option<&str>) -> Arc { + Arc::new(Self { + task: Arc::downgrade(task), + opening_config: Mutex::new( + opening_session.map(|id| OpeningConfig { session: id.to_owned(), options: None }), + ), + }) + } + + fn take_opening_config(&self) -> Option { + self.opening_config.lock().as_mut()?.options.take() + } } impl Handler for Client { @@ -3377,6 +3566,14 @@ impl Handler for Client { if method == "session/update" && let (Some(task), Some(update)) = (self.task.upgrade(), params.get("update")) { + if update.get("sessionUpdate").and_then(Value::as_str) == Some("config_option_update") + && let Some(opening) = self.opening_config.lock().as_mut() + { + if params.get("sessionId").and_then(Value::as_str) == Some(opening.session.as_str()) { + opening.options = Some(update.clone()); + } + return; + } task.on_update(params.get("sessionId").and_then(Value::as_str), update); } } diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index c644cf44fb..25d2016c89 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -1935,7 +1935,7 @@ async fn startup_warnings_survive_replay_and_restart_without_failing_the_task() let handle = mgr.task(&task.id).unwrap(); handle.replaying.store(true, Ordering::Release); handle.turn_started.store(false, Ordering::Release); - let client = Client { task: Arc::downgrade(&handle) }; + let client = Client::new(&handle, None); client.on_notification(WARNING_NOTIFICATION, json!({"message": "Project MCP config is disabled until trusted."})); client.on_notification(WARNING_NOTIFICATION, json!({"message": " "})); client.on_notification(WARNING_NOTIFICATION, json!({})); diff --git a/docs/en/guide/agents.mdx b/docs/en/guide/agents.mdx index 039c2c7584..bbbc00f822 100644 --- a/docs/en/guide/agents.mdx +++ b/docs/en/guide/agents.mdx @@ -78,7 +78,7 @@ The task tab shows the conversation: your messages, the agent's replies, its rea On your own messages you can **Edit** (the messages after it are replaced; files already changed stay as they are) or **Retract Message**. On replies you can **Copy Markdown**, **Quote Reply**, **Regenerate Response** and **Branch Conversation from Here**, which starts a new task from that point. -In an existing chat, open **Model › Refresh models** to discover newly available models without sending a message or changing the selection. If the agent can't switch in place, the choice stays pending until your next message reopens the same session. If the session can't be reopened or doesn't accept the model, OpenIDEA restores the previous selection and reports the error without sending the message. +In an existing chat, open **Model › Refresh models** to discover newly available models without sending a message or changing the selection. If the agent can't switch in place, the choice stays pending. You can choose an effort level as soon as the provider reports the new model's options. On your next message, OpenIDEA reopens the same session and applies the model and any effort you selected before sending. If the session can't be reopened or rejects either choice, OpenIDEA restores the previous selection and reports the error without sending the message. **Focus Agent Input** defaults to `⌘L` on macOS and `Ctrl+L` on Windows / Linux in every built-in keymap. When focus is inside your writable task conversation, in either an editor tab or the tool window, it returns focus to the message input without changing your draft, caret position or selection—even when pressed repeatedly. It does not send a message or jump through message history. diff --git a/docs/zh/guide/agents.mdx b/docs/zh/guide/agents.mdx index f720026904..227786cbfc 100644 --- a/docs/zh/guide/agents.mdx +++ b/docs/zh/guide/agents.mdx @@ -78,7 +78,7 @@ Codex 有自己的项目信任设置。如果它禁用了当前项目的 `.codex 在你自己的消息上可以 **编辑**(其后的消息会被替换,已经改动的文件保持不变)或 **撤回消息**。在回复上可以 **复制 Markdown**、**引用回复**、**重新生成回复**,以及 **从此处创建分支对话**,从这一点开始一个新任务。 -在已有对话中,打开**模型 › 刷新模型**即可查找新上线的模型,不会发送消息或更改当前选择。如果 agent 无法直接切换,所选模型会在下一条消息重新打开原会话时才应用。如果无法恢复会话,或原会话不接受所选模型,OpenIDEA 会还原之前的选择并提示错误,不会发送该消息。 +在已有对话中,打开**模型 › 刷新模型**即可查找新上线的模型,不会发送消息或更改当前选择。如果 agent 无法直接切换,所选模型会保持待应用状态。提供商返回新模型支持的思考强度后,你就可以选择强度。发送下一条消息时,OpenIDEA 会先恢复原会话并应用所选模型和思考强度,再发送消息。如果无法恢复会话,或原会话不接受其中任何一项,OpenIDEA 会还原之前的选择并提示错误,不会发送该消息。 所有内置按键映射中,**聚焦 Agent 输入框** 的默认快捷键都是 macOS 上的 `⌘L`、Windows / Linux 上的 `Ctrl+L`。焦点位于你自己的可输入任务对话中时,无论对话显示在编辑器标签页还是工具窗口中,它都会将焦点移回消息输入框,保留草稿、光标位置和选区;重复按下也不会改变这些内容。它不会发送消息,也不会跳转消息历史。 diff --git a/e2e/agentCycleEffort.spec.ts b/e2e/agentCycleEffort.spec.ts index 2a665bc1f3..a79aa93c10 100644 --- a/e2e/agentCycleEffort.spec.ts +++ b/e2e/agentCycleEffort.spec.ts @@ -108,15 +108,23 @@ async function seed( surface: "new" | "task" = "task", model = "atlas", status: AgentTask["status"] = "ready", + catalogOnly = false, ) { await stubDesktop(page); await page.evaluate( - async ({ placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId }) => { + async ({ placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId, catalogOnly }) => { // In-memory sample tasks belong to Vite's browser realm. Static Node imports create a different store and cannot seed the workbench. const storePath = "/src/features/agents/store.ts"; const store = await import(storePath); + const initialCatalog = { + ...provider, + config: provider.config.map((entry) => ({ + ...entry, + values: entry.values.filter((value) => value.value !== "swift"), + })), + }; const configFor = (model: string) => [ - { ...provider.config[0]!, current: model }, + { ...(catalogOnly && model !== "swift" ? initialCatalog : provider).config[0]!, current: model }, ...(provider.thoughtLevels?.[model] ?? []), ]; const tasks = new Map( @@ -150,10 +158,10 @@ async function seed( channel = onEvent; return [...tasks.values()]; }; - handlers.agent_providers = () => [provider]; - handlers.agent_refresh_models = () => ({ + handlers.agent_providers = () => [catalogOnly ? initialCatalog : provider]; + handlers.agent_refresh_models = ({ force }) => ({ provider: provider.id, - config: provider.config, + config: (catalogOnly && !force ? initialCatalog : provider).config, thoughtLevels: provider.thoughtLevels, refreshing: false, refreshedAtMs: Date.now(), @@ -170,9 +178,15 @@ async function seed( handlers.vcs_branches = () => []; handlers.agent_set_config = async ({ task: id, option, value }) => { const previous = tasks.get(String(id))!; + const pendingModel = catalogOnly && option === modelId && value === "swift"; + if (pendingModel) { + const { promise, resolve } = Promise.withResolvers(); + document.addEventListener("test:chat-model-settings-ready", () => resolve(), { once: true }); + await promise; + } const updated = option === modelId - ? { ...previous, model: String(value), config: configFor(String(value)) } + ? { ...previous, model: pendingModel ? previous.model : String(value), config: configFor(String(value)) } : { ...previous, config: previous.config.map((entry) => @@ -204,7 +218,7 @@ async function seed( if (surface === "new") store.openHome(); else store.openTask(firstTask.id); }, - { placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId }, + { placement, surface, provider, firstTask, secondTask, subagent, model, status, modelId, catalogOnly }, ); await expect(box(page)).toBeVisible(); await page.evaluate(() => document.fonts.ready); @@ -602,3 +616,33 @@ test("New Task discovers uncached model effort before the first prompt", async ( await page.screenshot({ path: testInfo.outputPath("uncached-model-effort.png") }); } }); + +test("an existing chat can choose effort for a refreshed model before sending", async ({ workbench: page }) => { + await seed(page, "editor", "task", "atlas", "ready", true); + await box(page).fill(draft); + await expectEffort(page, "Gentle"); + await modelButton(page).click(); + const swiftModel = page.getByRole("option", { name: /^Swift\b/ }); + await expect(swiftModel).toHaveCount(0); + await page.getByRole("button", { name: "Refresh models", exact: true }).click(); + await swiftModel.click(); + + const loading = page.getByRole("status").filter({ hasText: "Loading model settings…" }); + const send = page.getByRole("button", { name: "Send", exact: true }); + await expect(loading).toBeVisible(); + await expect(send).toBeDisabled(); + await expect(modelButton(page)).toHaveAttribute("title", /^Model: Atlas\b/); + await page.evaluate(() => document.dispatchEvent(new Event("test:chat-model-settings-ready"))); + await expect(loading).toHaveCount(0); + await expect(modelButton(page)).toHaveAttribute("title", /^Model: Swift\b/); + await expectEffort(page, "Quick"); + await modelButton(page).click(); + const efforts = page.getByRole("radiogroup", { name: "Effort Level", exact: true }); + await expect(efforts.getByRole("radio", { name: "Gentle", exact: true })).toHaveCount(0); + await efforts.getByRole("radio", { name: "Thorough", exact: true }).click(); + await page.keyboard.press("Escape"); + await expectEffort(page, "Thorough"); + await expect(send).toBeEnabled(); + await expect(box(page)).toHaveText(draft); + await expectNoSubmission(page); +}); diff --git a/src/features/agents/session/SessionComposer.tsx b/src/features/agents/session/SessionComposer.tsx index 1239fee9fa..441c3ef0d8 100644 --- a/src/features/agents/session/SessionComposer.tsx +++ b/src/features/agents/session/SessionComposer.tsx @@ -173,6 +173,8 @@ export function SessionComposer({ return task.config.map((o) => (o === model ? pickerModel : o)); }, [task.config, model, candidateModels]); const [sending, setSending] = useState(false); + const configChange = useRef<{ loadingModel: boolean } | null>(null); + const [configuring, setConfiguring] = useState(null); const [mcpOpenRequest, setMcpOpenRequest] = useState(0); const [assetFocus, setAssetFocus] = useState(0); const agentCommands = useAgentCommands(task.provider, task.id, task.commands); @@ -191,7 +193,7 @@ export function SessionComposer({ task.status === "running" && (composer.images.length === 0 || !!task.capabilities.images); const send = (now: boolean) => { - if (!canSend(composer) || sending || task.status === "archived") return; + if (!canSend(composer) || sending || configChange.current || task.status === "archived") return; setSending(true); sendMessage(task.id, now && (whileRunning !== "steer" || steers)) .catch((e: unknown) => @@ -203,14 +205,30 @@ export function SessionComposer({ ) .finally(() => setSending(false)); }; - const setOption = (id: string, value: string) => - void setTaskConfig(task.id, id, value).catch((e: unknown) => - notifications().notify({ - level: "error", - title: "Couldn't change the setting", - body: String(e), - }), - ); + const setOption = (id: string, value: string) => { + const changingModel = id === model?.id; + const loadingModel = changingModel && !model.values.some((v) => v.value === value); + const pendingModel = model?.current != null && model.current !== task.model; + const change = loadingModel || (changingModel && configChange.current) || pendingModel ? { loadingModel } : null; + if (change) { + configChange.current = change; + setConfiguring(change); + } + void setTaskConfig(task.id, id, value) + .catch((e: unknown) => + notifications().notify({ + level: "error", + title: "Couldn't change the setting", + body: String(e), + }), + ) + .finally(() => { + if (change && configChange.current === change) { + configChange.current = null; + setConfiguring(null); + } + }); + }; const openMcp = () => setMcpOpenRequest((n) => n + 1); const shown = useEditorShown(); const effortAnnouncement = useEffortFocus(focusRoot, shown && task.status !== "archived", task.config, setOption); @@ -269,6 +287,7 @@ export function SessionComposer({ canRefreshModels ? { refreshing: requestingModels || (catalog?.refreshing ?? false), + loadingSettings: configuring?.loadingModel, retryAtMs: catalog?.retryAtMs ?? null, error: requestingModels ? null : (catalog?.error ?? null), onOpen: () => void refreshTaskModels(task.id, false), @@ -303,7 +322,7 @@ export function SessionComposer({ label={busy ? "Queue" : "Send"} pending={sending} variant={busy ? "secondary" : "primary"} - disabled={!canSend(composer) || sending || task.status === "archived"} + disabled={!canSend(composer) || sending || configuring !== null || task.status === "archived"} onClick={() => send(false)} /> From ae604b7933bef0436240f51f41656fa611f59c79 Mon Sep 17 00:00:00 2001 From: Vadim Lazuk Date: Thu, 19 Nov 2026 14:25:53 +0300 Subject: [PATCH 07/16] fix(editor): keep target indentation when pasting onto a blank line (#4500) Pasting onto a blank line in YAML placed the text at column 0, turning a nested key into a root key, even with Reformat on paste. @lezer/yaml has no indent strategy, so the indent engine reports 0 and the blank target line looked already correct. On a blank target line where the engine gives no indent (null or 0), the paste filter now uses the indentation of the nearest non-empty line above, in both reformat modes. Closes #4474 Co-authored-by: Inf1mum <8135225+Inf1mum@users.noreply.github.com> --- src/editor/core/cm/ideaParity.test.ts | 14 ++++++++++++++ src/editor/core/cm/prefs.ts | 15 ++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/editor/core/cm/ideaParity.test.ts b/src/editor/core/cm/ideaParity.test.ts index bad82ca408..e998fcbb0a 100644 --- a/src/editor/core/cm/ideaParity.test.ts +++ b/src/editor/core/cm/ideaParity.test.ts @@ -66,6 +66,7 @@ function show(view: EditorView): string { } const javascript = await languages.find((l) => l.name === "JavaScript")!.load(); +const yaml = await languages.find((l) => l.name === "YAML")!.load(); describe("Move Statement", () => { it("moves a multi-line statement as a whole, never one of its lines", () => { @@ -203,6 +204,19 @@ describe("paste reformatting", () => { paste(v, "a();\n b();\n c();"); expect(v.state.doc.toString()).toBe("if {\n a();\n b();\n c();\n}"); }); + + it("pastes onto a blank line at the previous line's indent when the language has no indent engine", () => { + const doc = "service:\n database:\n query-timeout: 30\n pool:\n validation-query: SELECT 1\n"; + const v = make(doc + "|", [yaml, pasteReindentFilter("indentEachLine")]); + paste(v, "query-timeout: 30"); + expect(v.state.doc.toString()).toBe(doc + " query-timeout: 30"); + }); + + it("pastes a block onto a blank line at the indent of the nearest non-empty line above", () => { + const v = make("outer:\n key: 1\n\n|\ntrailing: 2", [yaml, pasteReindentFilter("indentBlock")]); + paste(v, "a: 1\n b: 2"); + expect(v.state.doc.toString()).toBe("outer:\n key: 1\n\n a: 1\n b: 2\ntrailing: 2"); + }); }); describe("closing quotes", () => { diff --git a/src/editor/core/cm/prefs.ts b/src/editor/core/cm/prefs.ts index 831fa54c98..f364bafe52 100644 --- a/src/editor/core/cm/prefs.ts +++ b/src/editor/core/cm/prefs.ts @@ -222,6 +222,15 @@ function leadingColumns(text: string, tabSize: number): number { return col; } +/** Indentation of the nearest non-empty line above `line` (1-based), for pastes onto a blank line in languages without an indent engine. */ +function previousLineIndent(state: EditorState, line: number): number | null { + for (let n = line - 1; n >= 1; n--) { + const prev = state.doc.line(n); + if (/\S/.test(prev.text)) return leadingColumns(prev.text, state.tabSize); + } + return null; +} + /** Reformat on paste › Indent Block: re-indents a pasted block to the caret's indentation. */ export function indentPastedText( text: string, @@ -277,7 +286,11 @@ export function pasteReindentFilter(mode: "indentBlock" | "indentEachLine") { let targetCol = leadingColumns(atIndent ? before : line.text, tabSize); let prefix = ""; if (atIndent) { - const proper = getIndentation(start, line.from); + let proper = getIndentation(start, line.from); + if (!targetCol && !proper) { + const above = previousLineIndent(start, line.number); + if (above) proper = above; + } if (proper !== null && proper !== targetCol) { targetCol = proper; prefix = indentString(start, proper); From e93ac42489c0bac3f5ccfefa09d44f84d054edfa Mon Sep 17 00:00:00 2001 From: Vadim Lazuk Date: Thu, 19 Nov 2026 14:28:02 +0300 Subject: [PATCH 08/16] fix(workbench): coalesce system toasts for external edit bursts (#4502) Every balloon raised while OpenIDEA was in the background became its own OS toast, so an external agent editing many files produced a stream of toasts. The first toast still shows at once; balloons that follow within a 3-second quiet period become one toast naming the last balloon and how many more arrived, and a steady stream raises such a summary at most every 30 seconds. In-IDE balloons and the Notifications tool window keep every notification. Closes #4466 Co-authored-by: Inf1mum <8135225+Inf1mum@users.noreply.github.com> --- src/platform/locales/text/en.json | 2 + src/platform/locales/text/zh.json | 2 + src/workbench/notificationStore.test.ts | 78 +++++++++++++++++++++++++ src/workbench/notificationStore.ts | 50 +++++++++++++++- 4 files changed, 130 insertions(+), 2 deletions(-) create mode 100644 src/workbench/notificationStore.test.ts diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 0f77d3fe7b..cfb1961311 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -1258,6 +1258,8 @@ "Plan {done}/{length}": "Plan {done}/{length}", "1 changed file": "1 changed file", "{count} changed files": "{count} changed files", + "{count} more notification": "{count} more notification", + "{count} more notifications": "{count} more notifications", "Send into the agent's turn": "Send into the agent's turn", "Queue a message for when the agent is done (⌘⇧↵ sends it now)": "Queue a message for when the agent is done (⌘⇧↵ sends it now)", "Queue a message for when the agent is done": "Queue a message for when the agent is done", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 300ec741fe..8ac4d7965e 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -7648,6 +7648,8 @@ "Plan {done}/{length}": "计划 {done}/{length}", "1 changed file": "改动 1 个文件", "{count} changed files": "改动 {count} 个文件", + "{count} more notification": "还有 {count} 条新通知", + "{count} more notifications": "还有 {count} 条新通知", "Send into the agent's turn": "发送到当前回合", "Queue a message for when the agent is done (⌘⇧↵ sends it now)": "排队一条消息,agent 做完后发送(⌘⇧↵ 立即发送)", "Queue a message for when the agent is done": "排队一条消息,agent 做完后发送", diff --git a/src/workbench/notificationStore.test.ts b/src/workbench/notificationStore.test.ts new file mode 100644 index 0000000000..4f06099688 --- /dev/null +++ b/src/workbench/notificationStore.test.ts @@ -0,0 +1,78 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { notify } from "./notificationStore"; + +const { showSystemNotification } = vi.hoisted(() => ({ + showSystemNotification: vi.fn(async (_title: string, _body: string) => ({ status: "ok", data: null })), +})); + +vi.mock("@/platform/ipc", async (orig) => { + const actual = await orig(); + return { ...actual, isTauri: () => true, commands: { ...actual.commands, showSystemNotification } }; +}); + +beforeEach(() => { + vi.useFakeTimers(); + showSystemNotification.mockClear(); +}); + +afterEach(() => { + vi.runAllTimers(); + vi.useRealTimers(); +}); + +describe("system toast coalescing", () => { + it("shows the first toast at once and the rest of a burst as one, naming the last and how many more", () => { + notify({ level: "info", title: "File a.ts changed" }); + expect(showSystemNotification).toHaveBeenCalledTimes(1); + expect(showSystemNotification.mock.calls[0]).toEqual(["File a.ts changed", ""]); + notify({ level: "info", title: "File b.ts changed", body: "written by an agent" }); + notify({ level: "info", title: "File c.ts changed", body: "written by an agent" }); + expect(showSystemNotification).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(3000); + expect(showSystemNotification).toHaveBeenCalledTimes(2); + expect(showSystemNotification.mock.calls[1]).toEqual([ + "File c.ts changed", + "written by an agent\n1 more notification", + ]); + }); + + it("shows a lone balloon's toast as written, without waiting", () => { + notify({ level: "info", title: "Git refresh failed", body: "no remote" }); + expect(showSystemNotification).toHaveBeenCalledTimes(1); + expect(showSystemNotification.mock.calls[0]).toEqual(["Git refresh failed", "no remote"]); + vi.advanceTimersByTime(10_000); + expect(showSystemNotification).toHaveBeenCalledTimes(1); + }); + + it("keeps waiting while balloons keep arriving", () => { + notify({ level: "info", title: "First" }); + notify({ level: "info", title: "Second" }); + vi.advanceTimersByTime(2000); + notify({ level: "info", title: "Third" }); + vi.advanceTimersByTime(2000); + expect(showSystemNotification).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(1000); + expect(showSystemNotification).toHaveBeenCalledTimes(2); + expect(showSystemNotification.mock.calls[1]).toEqual(["Third", "1 more notification"]); + }); + + it("still summarises a steady stream every 30 seconds", () => { + notify({ level: "info", title: "Start" }); + for (let i = 0; i < 30; i++) { + vi.advanceTimersByTime(1000); + notify({ level: "info", title: `Edit ${i}` }); + } + expect(showSystemNotification).toHaveBeenCalledTimes(1); + vi.advanceTimersByTime(1000); + expect(showSystemNotification).toHaveBeenCalledTimes(2); + expect(showSystemNotification.mock.calls[1]![0]).toBe("Edit 29"); + }); + + it("falls back to the count alone when a balloon has no body", () => { + notify({ level: "warning", title: "Cannot reload Maven projects" }); + notify({ level: "warning", title: "Cannot reload Gradle projects" }); + notify({ level: "warning", title: "Cannot reload sbt projects" }); + vi.advanceTimersByTime(3000); + expect(showSystemNotification.mock.calls[1]).toEqual(["Cannot reload sbt projects", "1 more notification"]); + }); +}); diff --git a/src/workbench/notificationStore.ts b/src/workbench/notificationStore.ts index 9748a65352..da85a52ed3 100644 --- a/src/workbench/notificationStore.ts +++ b/src/workbench/notificationStore.ts @@ -3,7 +3,7 @@ import type { ReactNode } from "react"; import { create } from "zustand"; import { call, commands, isTauri, onIdeEvent } from "@/platform/ipc"; import { buildToolRecovery } from "@/platform/buildToolRecovery"; -import { txTemplate } from "@/platform/i18n"; +import { tx, txTemplate } from "@/platform/i18n"; import { useProject } from "@/platform/project"; import type { NotificationService } from "./contributions"; @@ -127,6 +127,52 @@ export function balloonTimeout(n: Pick | undefined; +let toastBatch: Array<{ title: string; body: string }> = []; +let toastBatchStart = 0; + +function showToast(title: string, body: string) { + void call(commands.showSystemNotification(title, body)).catch(() => {}); +} + +/** Ends a quiet period: the toasts held back during it, as one. */ +function flushToasts() { + const batch = toastBatch; + toastBatch = []; + if (!batch.length) { + toastTimer = undefined; + return; + } + const last = batch[batch.length - 1]!; + const more = batch.length - 1; + const count = more === 1 ? tx`${more} more notification` : tx`${more} more notifications`; + showToast(last.title, more === 0 ? last.body : [last.body, count].filter(Boolean).join("\n")); + // What arrives right after the summary joins the next one. + toastTimer = setTimeout(flushToasts, SYSTEM_TOAST_QUIET_MS); +} + +function systemToast(title: string, body: string) { + if (toastTimer === undefined) { + showToast(title, body); + toastTimer = setTimeout(flushToasts, SYSTEM_TOAST_QUIET_MS); + return; + } + if (!toastBatch.length) toastBatchStart = Date.now(); + toastBatch.push({ title, body }); + clearTimeout(toastTimer); + const waited = Date.now() - toastBatchStart; + toastTimer = setTimeout(flushToasts, Math.max(0, Math.min(SYSTEM_TOAST_QUIET_MS, SYSTEM_TOAST_MAX_WAIT_MS - waited))); +} + export function notify(n: Parameters[0]): number { const id = ++seq; const group = groupOf(n); @@ -163,7 +209,7 @@ export function notify(n: Parameters[0]): number // In the UI language, as the balloon shows it; a plugin's own text stays as written. const shown = (text: string) => (n.verbatim ? text : txTemplate(text)); const plain = typeof n.body === "string" ? shown(n.body) : ""; - void call(commands.showSystemNotification(shown(n.title), plain)).catch(() => {}); + systemToast(shown(n.title), plain); } return id; } From 22a5e4c9e6043f9c458901f73617813ab337a117 Mon Sep 17 00:00:00 2001 From: Vadim Lazuk Date: Thu, 19 Nov 2026 14:29:44 +0300 Subject: [PATCH 09/16] fix(maven): reuse an existing build configuration for Maven goal runs (#4503) Running a lifecycle goal such as package from the Maven tool window always created a temporary ' [package]' configuration, even when a saved or detected configuration already ran the same goal. adoptTemporary only matched by id or main class. Maven and Gradle runs now also match a kept configuration with the same build tool, command, directory and exact arguments, which is then selected and run instead; a different flag set (for example -DskipTests) still gets its own temporary configuration. Co-authored-by: Inf1mum <8135225+Inf1mum@users.noreply.github.com> --- src/features/run/java.test.ts | 46 +++++++++++++++++++++++++++++++++++ src/features/run/store.ts | 15 +++++++++++- 2 files changed, 60 insertions(+), 1 deletion(-) diff --git a/src/features/run/java.test.ts b/src/features/run/java.test.ts index ffeed732ca..2071c470f2 100644 --- a/src/features/run/java.test.ts +++ b/src/features/run/java.test.ts @@ -668,6 +668,52 @@ describe("temporary configurations", () => { await saveTemporary(app.id).catch(() => undefined); expect(useRun.getState().temporary).toEqual([]); }); + + it("reuse the detected configuration of the same Maven goal instead of adding a temporary one", () => { + const detected = cfg({ id: "maven:package", kind: "maven", name: "mvn package", args: ["package"] }); + useRun.setState({ configs: [detected] }); + const goal = cfg({ + id: "maven:goal:pom.xml:package", + kind: "maven", + name: "demo [package]", + args: ["package"], + detected: false, + }); + expect(adoptTemporary(goal)).toBe(detected); + expect(useRun.getState().temporary).toEqual([]); + expect(useRun.getState().selectedId).toBe(detected.id); + }); + + it("reuse a Maven goal configuration with the same command line, but not across goals, flags, builds or tools", () => { + const detected = cfg({ id: "maven:package", kind: "maven", name: "mvn package", args: ["package"] }); + useRun.setState({ configs: [detected] }); + const goal = (over: Partial): RunConfig => + cfg({ id: "maven:goal:pom.xml:package", kind: "maven", args: ["package"], detected: false, ...over }); + expect(adoptTemporary(goal({}))).toBe(detected); + expect( + adoptTemporary(goal({ id: "maven:goal:pom.xml:package.skipTests", args: ["package", "-DskipTests"] })).id, + ).toBe("maven:goal:pom.xml:package.skipTests"); + expect(adoptTemporary(goal({ id: "maven:goal:pom.xml:clean", args: ["clean"] })).id).toBe( + "maven:goal:pom.xml:clean", + ); + expect(adoptTemporary(goal({ id: "maven:goal:core/pom.xml:package", args: ["package"], cwd: "core" })).id).toBe( + "maven:goal:core/pom.xml:package", + ); + expect(adoptTemporary(goal({ id: "gradle:task:...:package", kind: "gradle", command: "gradle" })).id).toBe( + "gradle:task:...:package", + ); + const { configs, temporary } = useRun.getState(); + expect(temporary).toHaveLength(4); + expect(configs.filter((c) => !temporary.includes(c.id))).toEqual([detected]); + }); + + it("reuse the detected configuration of the same Gradle tasks", () => { + const detected = cfg({ id: "gradle:test", kind: "gradle", name: "gradle test", args: ["test"], isTest: true }); + useRun.setState({ configs: [detected] }); + const task = cfg({ id: "gradle:task:...:test", kind: "gradle", args: ["test"], detected: false }); + expect(adoptTemporary(task)).toBe(detected); + expect(useRun.getState().temporary).toEqual([]); + }); }); describe("jvmMainCandidates", () => { diff --git a/src/features/run/store.ts b/src/features/run/store.ts index 2ca392af97..627e589904 100644 --- a/src/features/run/store.ts +++ b/src/features/run/store.ts @@ -447,6 +447,17 @@ function sameApplication(a: RunConfig, b: RunConfig): boolean { return main !== null && main === parseJavaArgs(b.args).mainClass && (a.module ?? a.cwd) === (b.module ?? b.cwd); } +/** + * IDEA's `isConfigurationFromContext` for a Maven / Gradle goal: the same command line run by the + * same build tool in the same build directory, whatever the configuration is named (#4436). The + * existing configuration is run as is, so reuse must not drop option flags. + */ +function sameBuildGoal(a: RunConfig, b: RunConfig): boolean { + if ((a.kind !== "maven" && a.kind !== "gradle") || a.kind !== b.kind) return false; + if (a.command !== b.command || (a.cwd ?? "") !== (b.cwd ?? "")) return false; + return a.args.length > 0 && a.args.length === b.args.length && a.args.every((arg, i) => arg === b.args[i]); +} + /** * Selects the configuration for a gutter / context run: a saved or detected * configuration with the same id is reused, otherwise `config` becomes a @@ -457,7 +468,9 @@ export function adoptTemporary(config: RunConfig): RunConfig { // IDEA's `findExistingConfiguration`: a configuration the user keeps for this context wins. const existing = state.configs.find((c) => c.id === config.id) ?? - state.configs.find((c) => !state.temporary.includes(c.id) && sameApplication(c, config)); + state.configs.find( + (c) => !state.temporary.includes(c.id) && (sameApplication(c, config) || sameBuildGoal(c, config)), + ); if (existing && !state.temporary.includes(config.id)) { selectConfig(existing.id); return existing; From d080ca28f819dc4c9fc1e3452bec10bb1589110b Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:34:55 +0200 Subject: [PATCH 10/16] fix(bench): require selected workloads and finite metrics (#4488) Benchmark verdicts could pass with selected workloads or required metrics missing, empty or non-finite, and pnpm perf:rust could accept stale or partial criterion results. Selections and counts are now validated before any work starts, every selected workload must report finite values for its required metrics, and Rust results are collected only for the selected packages from fresh, well-formed criterion artifacts, against a list of the benchmarks each package owns. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- docs/en/contribute/testing/perf.mdx | 16 ++- docs/zh/contribute/testing/perf.mdx | 16 ++- evals/lib/cli.test.ts | 29 +++++ evals/lib/selection.test.ts | 37 ++++++ evals/lib/selection.ts | 42 +++++++ evals/lib/verdict.test.ts | 50 +++++++- evals/lib/verdict.ts | 32 ++++- evals/run.ts | 32 +++-- perf/lib/options.test.ts | 47 ++++++++ perf/lib/options.ts | 8 ++ perf/lib/report.test.ts | 44 ++++++- perf/lib/report.ts | 26 ++++- perf/lib/rust.test.ts | 175 ++++++++++++++++++++++++++++ perf/lib/rust.ts | 157 +++++++++++++++++++++++++ perf/run.ts | 31 +++-- perf/rust.ts | 43 ++----- 16 files changed, 708 insertions(+), 77 deletions(-) create mode 100644 evals/lib/cli.test.ts create mode 100644 evals/lib/selection.test.ts create mode 100644 evals/lib/selection.ts create mode 100644 perf/lib/options.test.ts create mode 100644 perf/lib/options.ts create mode 100644 perf/lib/rust.test.ts create mode 100644 perf/lib/rust.ts diff --git a/docs/en/contribute/testing/perf.mdx b/docs/en/contribute/testing/perf.mdx index a34c92abe0..b5c8351b98 100644 --- a/docs/en/contribute/testing/perf.mdx +++ b/docs/en/contribute/testing/perf.mdx @@ -29,7 +29,9 @@ pnpm perf -- --only typing --profile --unminified # CPU profile and top functi Other options: `--warmup ` (default 1), `--headed`, `--no-build` (reuse the last build), `--channel ` (default `chromium`, or `OPENIDEA_PERF_CHANNEL`), `--fail-on-regression`. -Scenarios (`perf/scenarios.ts`): `typing`, `typingLarge`, `typingAngular`, `completion`, `consoleOutput`, `terminalTui`, `keyRepeat`, `scroll`, `gitLog`, `gitLogScrollbar`, `resizePanels`, `startup`, `tabs`, `agentTabs`, `popups`, `toolWindows`, `projectTree`, `leaks`. Bundle size (`bundle.initialJsKb`, `bundle.initialCssKb`) is checked on every run. +`--runs` must be a positive integer, `--warmup` a nonnegative integer, and `--cpu` a finite number of at least 1. Empty or unknown `--only` entries fail before building or launching a browser. Every declared selected scenario must return exactly one result; missing budgeted metrics and nonfinite metrics fail even when CPU throttling disables timing-budget enforcement. Unminified profiling builds intentionally omit bundle-size checks. + +Scenarios (`perf/scenarios.ts`): `typing`, `typingLarge`, `typingAngular`, `completion`, `consoleOutput`, `terminalTui`, `keyRepeat`, `scroll`, `gitLog`, `gitLogScrollbar`, `resizePanels`, `startup`, `tabs`, `agentTabs`, `popups`, `toolWindows`, `projectTree`, `leaks`. Bundle size (`bundle.initialJsKb`, `bundle.initialCssKb`) is checked except with `--unminified`. Latencies are measured from input to the start of the first frame that shows the result, so about 16.7 ms means "next frame". @@ -44,7 +46,7 @@ A scenario in `perf/scenarios.ts` has an `id`, a `title` and a `run(h)` that dri ## Backend: `pnpm perf:rust` -`perf/rust.ts` runs `cargo bench` for `ide-text`, `ide-language`, `ide-index`, `ide-search` and `ide-host`, reads the Criterion results from `target/criterion`, and checks each bench's mean (in µs). +`perf/rust.ts` runs `cargo bench` for `ide-text`, `ide-language`, `ide-index`, `ide-search`, `ide-host` and `ide-heap`, reads the Criterion results, and checks each bench's mean (in µs). ```sh pnpm perf:rust # run the benches, then check @@ -62,6 +64,16 @@ The benches live in `crates//benches/`: | `search_5k/…` | `ide-search` | literal, regex and dense-match search over 5k files | | `plugins/…` | `ide-host` | loading 50 plugins, cold activation, syntax highlights of a 2k-line file | +Expected IDs and package ownership are declared independently of collected artifacts in `perf/lib/rust.ts`. A selected package must produce every expected ID, including observe-only measurements. `--package` scopes both collection and required budgets, also with `--no-run`; unknown packages fail before Cargo starts. + +Six IDs are observe-only (required finite measurements, without an absolute budget): `syntax_2mb/outline_uncached`, `syntax_2mb/folding_uncached`, `index_100k/find_files/zzzz`, `index_100k/find_symbols/renderView`, `startup_20k/reopen_wait_idle`, and `search_excluded_subtrees/5k_dependencies`. New IDs need an explicit budget or observe-only classification. + +## Code intelligence: `pnpm eval` + +Use `pnpm eval --list` for scenario IDs and supported conditions. `--only` accepts comma-separated IDs or dot-prefix groups; every entry must match executable work. `--condition` accepts only `warm` or `cold`, and a selection incompatible with that condition is rejected before building or launching. Repetition counts follow the UI runner's integer requirements. + +The selected scenario/condition plan defines the required outcomes independently of collected results. Missing, duplicate or unexpected outcomes fail; an empty workload cannot pass. Required timing and correctness metrics must be present and finite, rather than silently skipped by the judge. + ## Budgets and baselines [`perf/budgets.json`](https://github.com/l0ng-ai/openidea/blob/main/perf/budgets.json) holds upper bounds (lower is better): diff --git a/docs/zh/contribute/testing/perf.mdx b/docs/zh/contribute/testing/perf.mdx index ab07a92a43..42e25f70cb 100644 --- a/docs/zh/contribute/testing/perf.mdx +++ b/docs/zh/contribute/testing/perf.mdx @@ -29,7 +29,9 @@ pnpm perf -- --only typing --profile --unminified # CPU profile 和耗时最 其他选项:`--warmup `(默认 1)、`--headed`、`--no-build`(复用上次构建)、`--channel `(默认 `chromium`,或 `OPENIDEA_PERF_CHANNEL`)、`--fail-on-regression`。 -场景(`perf/scenarios.ts`):`typing`、`typingLarge`、`typingAngular`、`completion`、`consoleOutput`、`terminalTui`、`keyRepeat`、`scroll`、`gitLog`、`gitLogScrollbar`、`resizePanels`、`startup`、`tabs`、`agentTabs`、`popups`、`toolWindows`、`projectTree`、`leaks`。每次运行都会检查包体积(`bundle.initialJsKb`、`bundle.initialCssKb`)。 +`--runs` 必须为正整数,`--warmup` 为非负整数,`--cpu` 为不小于 1 的有限数值。`--only` 中的空项或未知场景会在构建或启动浏览器前报错。每个选中场景必须恰好返回一份结果;预算指标缺失或指标非有限值都会失败,即使 CPU 降速关闭了耗时预算检查。未压缩的性能分析构建不检查包体积。 + +场景(`perf/scenarios.ts`):`typing`、`typingLarge`、`typingAngular`、`completion`、`consoleOutput`、`terminalTui`、`keyRepeat`、`scroll`、`gitLog`、`gitLogScrollbar`、`resizePanels`、`startup`、`tabs`、`agentTabs`、`popups`、`toolWindows`、`projectTree`、`leaks`。除 `--unminified` 外,每次运行都会检查包体积(`bundle.initialJsKb`、`bundle.initialCssKb`)。 延迟是从输入到显示结果的第一帧开始的时间,因此约 16.7 ms 就表示“下一帧”。 @@ -44,7 +46,7 @@ pnpm perf -- --only typing --profile --unminified # CPU profile 和耗时最 ## 后端:`pnpm perf:rust` -`perf/rust.ts` 对 `ide-text`、`ide-language`、`ide-index`、`ide-search` 和 `ide-host` 运行 `cargo bench`,从 `target/criterion` 读取 Criterion 结果,检查每个基准的平均值(µs)。 +`perf/rust.ts` 对 `ide-text`、`ide-language`、`ide-index`、`ide-search`、`ide-host` 和 `ide-heap` 运行 `cargo bench`,读取 Criterion 结果,检查每个基准的平均值(µs)。 ```sh pnpm perf:rust # 跑基准并检查 @@ -62,6 +64,16 @@ pnpm perf:rust -- --package ide-text --save-baseline | `search_5k/…` | `ide-search` | 在 5 千个文件中做字面量、正则和密集匹配搜索 | | `plugins/…` | `ide-host` | 加载 50 个插件、冷激活、2 千行文件的语法高亮 | +预期 ID 及其所属包在 `perf/lib/rust.ts` 中独立于收集到的产物声明。选中的包必须提供全部预期 ID,包括仅观察的指标。`--package` 同时限定收集范围和必需预算,使用 `--no-run` 时也如此;未知包会在启动 Cargo 前报错。 + +六个 ID 仅观察(必须提供有限测量值,但没有绝对预算):`syntax_2mb/outline_uncached`、`syntax_2mb/folding_uncached`、`index_100k/find_files/zzzz`、`index_100k/find_symbols/renderView`、`startup_20k/reopen_wait_idle`、`search_excluded_subtrees/5k_dependencies`。新增 ID 必须明确设置预算或归类为仅观察。 + +## 代码智能:`pnpm eval` + +用 `pnpm eval --list` 查看场景 ID 及支持的条件。`--only` 接受逗号分隔的 ID 或点号前缀分组;每项都必须匹配可执行的工作。`--condition` 只接受 `warm` 或 `cold`,与该条件不兼容的选择会在构建或启动前被拒绝。重复次数遵循 UI 运行器的整数要求。 + +选中的场景/条件计划独立于收集结果定义必需的输出。缺失、重复或非预期输出都会失败,空工作集不能通过。必需的耗时和正确性指标必须存在且为有限数值,判定器不再静默跳过它们。 + ## 预算与基线 [`perf/budgets.json`](https://github.com/l0ng-ai/openidea/blob/main/perf/budgets.json) 保存上限(越低越好): diff --git a/evals/lib/cli.test.ts b/evals/lib/cli.test.ts new file mode 100644 index 0000000000..d1f97d0d70 --- /dev/null +++ b/evals/lib/cli.test.ts @@ -0,0 +1,29 @@ +import { spawnSync } from "node:child_process"; +import { resolve } from "node:path"; +import { describe, expect, test } from "vitest"; + +const runner = resolve(import.meta.dirname, "../run.ts"); + +describe("eval CLI preflight (no app builds)", () => { + test.each([ + [["--condition", "hot"], /--condition must be warm or cold/], + [["--only", "java.app,unknown"], /no scenario matches unknown/], + [["--only", "java.app,"], /empty selector/], + [["--only", "java.app.usages", "--condition", "cold"], /no compatible scenario/], + [["--runs", "0"], /--runs/], + [["--runs", "Infinity"], /--runs/], + [["--runs", "1.5"], /--runs/], + [["--warmup", "NaN"], /--warmup/], + [["--warmup=-1"], /--warmup/], + ] as const)("rejects %j before build/start", (args, message) => { + const result = spawnSync(process.execPath, [runner, ...args], { + encoding: "utf8", + timeout: 15_000, + env: { ...process.env, PATH: "", OPENIDEA_SERVER: "/nonexistent/eval-preflight-server" }, + }); + expect(result.error).toBeUndefined(); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(message); + expect(result.stdout).not.toContain("Building openidea-server"); + }); +}); diff --git a/evals/lib/selection.test.ts b/evals/lib/selection.test.ts new file mode 100644 index 0000000000..7b230e9c6c --- /dev/null +++ b/evals/lib/selection.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, test } from "vitest"; +import { planSelection } from "./selection.ts"; + +const scenarios = [ + { id: "java.a.one", title: "One", conditions: ["warm", "cold"] as const }, + { id: "java.b.two", title: "Two", conditions: ["warm"] as const }, +]; + +describe("eval workload planning", () => { + test("full and deduplicated subset plans are independent of collected outcomes", () => { + expect(planSelection(scenarios, {}).expected).toHaveLength(3); + const plan = planSelection(scenarios, { only: " java.a, java.a.one ", condition: "cold" }); + expect(plan.selected).toEqual([scenarios[0]]); + expect(plan.expected).toEqual([{ scenario: "java.a.one", title: "One", condition: "cold" }]); + }); + test.each([ + { condition: "hot" }, + { only: "java.a,unknown" }, + { only: "" }, + { only: "java.a," }, + { only: "java.b", condition: "cold" }, + { only: "java.a,java.b", condition: "cold" }, + { runs: "0" }, + { runs: "NaN" }, + { runs: "Infinity" }, + { runs: "1.5" }, + { runs: "9007199254740992" }, + { warmup: "-1" }, + { warmup: "Infinity" }, + { warmup: "0.5" }, + ])("rejects invalid selection/counts %j", (args) => { + expect(() => planSelection(scenarios, args)).toThrow(); + }); + test("rejects zero work", () => { + expect(() => planSelection([], {})).toThrow(/no compatible/); + }); +}); diff --git a/evals/lib/selection.ts b/evals/lib/selection.ts new file mode 100644 index 0000000000..1364ae1f54 --- /dev/null +++ b/evals/lib/selection.ts @@ -0,0 +1,42 @@ +import { countOption } from "../../perf/lib/options.ts"; +import type { Condition } from "./verdict.ts"; + +interface Scenario { + id: string; + title: string; + conditions: readonly Condition[]; +} + +export interface ExpectedOutcome { + scenario: string; + title: string; + condition: Condition; +} + +export function planSelection( + scenarios: readonly T[], + args: { only?: string; condition?: string; runs?: string; warmup?: string }, +) { + const runs = countOption("runs", args.runs ?? "3", 1); + const warmup = countOption("warmup", args.warmup ?? "1", 0); + if (args.condition !== undefined && args.condition !== "warm" && args.condition !== "cold") + throw new Error("--condition must be warm or cold"); + const condition = args.condition as Condition | undefined; + const selectors = args.only?.split(",").map((s) => s.trim()); + const matches = (s: T, selector: string) => s.id === selector || s.id.startsWith(`${selector}.`); + for (const selector of selectors ?? []) { + if (!selector) throw new Error("--only contains an empty selector"); + const matching = scenarios.filter((s) => matches(s, selector)); + if (!matching.length) throw new Error(`no scenario matches ${selector} (see --list)`); + if (!matching.some((s) => s.conditions.some((c) => !condition || c === condition))) + throw new Error(`no compatible scenario for selector ${selector} under ${condition}`); + } + const selected = scenarios.filter((s) => !selectors || selectors.some((selector) => matches(s, selector))); + const expected: ExpectedOutcome[] = selected.flatMap((s) => + s.conditions + .filter((c) => !condition || c === condition) + .map((c) => ({ scenario: s.id, title: s.title, condition: c })), + ); + if (!expected.length) throw new Error("no compatible scenarios selected"); + return { selected, expected, runs, warmup, condition }; +} diff --git a/evals/lib/verdict.test.ts b/evals/lib/verdict.test.ts index 1b76349c0e..e3126c9184 100644 --- a/evals/lib/verdict.test.ts +++ b/evals/lib/verdict.test.ts @@ -20,10 +20,11 @@ const outcome = (o: Partial): Outcome => ({ }); const repro = () => "pnpm eval --only usages"; +const expected = [{ scenario: "usages", title: "Show Usages", condition: "warm" as const }]; describe("judge", () => { test("within budgets and matching the golden passes", () => { - const [v] = judge([outcome({})], budgets, null, repro); + const [v] = judge([outcome({})], budgets, null, repro, expected); expect(v).toMatchObject({ id: "usages@warm", status: "pass", failures: [], repro: "pnpm eval --only usages" }); }); @@ -39,6 +40,7 @@ describe("judge", () => { budgets, null, repro, + expected, ); expect(v!.status).toBe("fail"); expect(v!.failures.map((f) => [f.kind, f.metric])).toEqual([ @@ -52,21 +54,29 @@ describe("judge", () => { test("condition budgets override scenario budgets", () => { const [v] = judge( - [outcome({ condition: "cold", metrics: { feedbackMs: 40, completeMs: 5000, recall: 1, precision: 1 } })], + [ + outcome({ + condition: "cold", + metrics: { feedbackMs: 40, firstResultMs: 300, completeMs: 5000, recall: 1, precision: 1 }, + }), + ], budgets, null, repro, + [{ ...expected[0]!, condition: "cold" }], ); expect(v!.status).toBe("pass"); }); test("timeouts and missing goldens fail", () => { - const [timedOut, noGolden] = judge( - [outcome({ error: "find.showUsages timed out after 30000 ms" }), outcome({ comparison: undefined })], + const [timedOut] = judge( + [outcome({ error: "find.showUsages timed out after 30000 ms" })], budgets, null, repro, + expected, ); + const [noGolden] = judge([outcome({ comparison: undefined })], budgets, null, repro, expected); expect(timedOut!.failures[0]!.kind).toBe("timeout"); expect(noGolden!.failures[0]!.kind).toBe("golden"); }); @@ -78,9 +88,41 @@ describe("judge", () => { budgets, baseline, repro, + expected, ); expect(v!.status).toBe("pass"); expect(v!.regressions.map((r) => r.metric)).toEqual(["completeMs"]); expect(table([v!], false)).toContain("regressed: completeMs"); }); + + test("missing, duplicate, unexpected and empty workloads fail", () => { + for (const actual of [[], [outcome({}), outcome({})], [outcome({ scenario: "other" })]]) { + expect(judge(actual, budgets, null, repro, expected).some((v) => v.status === "fail")).toBe(true); + } + expect(judge([], budgets, null, repro, []).some((v) => v.status === "fail")).toBe(true); + }); + + test.each(["feedbackMs", "firstResultMs", "completeMs", "recall", "precision"])("requires finite %s", (metric) => { + for (const value of [undefined, NaN, Infinity, -Infinity]) { + const o = outcome({}); + if (value === undefined) delete o.metrics[metric]; + else o.metrics[metric] = value; + const [v] = judge([o], budgets, null, repro, expected); + expect(v!.status).toBe("fail"); + expect(v!.failures.some((f) => f.metric === metric)).toBe(true); + } + }); + + test("requires scenario budget metrics and rejects nonfinite unbudgeted values", () => { + const custom = { ...budgets, scenarios: { usages: { readyMs: 100 } } }; + expect(judge([outcome({})], custom, null, repro, expected)[0]!.status).toBe("fail"); + const o = outcome({}); + o.metrics.extraMs = NaN; + expect(judge([o], budgets, null, repro, expected)[0]!.status).toBe("fail"); + }); + + test("a clean empty result set with a perfect comparison passes", () => { + const o = outcome({ results: { problems: [] } }); + expect(judge([o], budgets, null, repro, expected)[0]!.status).toBe("pass"); + }); }); diff --git a/evals/lib/verdict.ts b/evals/lib/verdict.ts index 7f177a626e..9483a0cbd6 100644 --- a/evals/lib/verdict.ts +++ b/evals/lib/verdict.ts @@ -4,6 +4,7 @@ */ import { readFileSync } from "node:fs"; import type { Comparison, ResultSet } from "./golden.ts"; +import type { ExpectedOutcome } from "./selection.ts"; export type Condition = "warm" | "cold"; @@ -97,15 +98,42 @@ export function judge( budgets: Budgets, baseline: Outcome[] | null, repro: (o: Outcome) => string, + expected: readonly ExpectedOutcome[], ): Verdict[] { const base = new Map((baseline ?? []).map((o) => [idOf(o), o.metrics])); - return outcomes.map((o) => { + const expectedIds = new Set(expected.map(idOf)); + const counts = new Map(); + for (const o of outcomes) counts.set(idOf(o), (counts.get(idOf(o)) ?? 0) + 1); + const work: Outcome[] = [...outcomes]; + for (const e of expected) { + if (!counts.has(idOf(e))) work.push({ ...e, metrics: {}, samples: {}, error: "missing expected outcome" }); + } + if (!work.length) work.push({ scenario: "workload", title: "Workload", condition: "warm", metrics: {}, samples: {} }); + return work.map((o) => { const failures: Failure[] = []; + if (!expected.length) failures.push({ kind: "error", detail: "expected workload is empty" }); + if (expectedIds.size !== expected.length) failures.push({ kind: "error", detail: "duplicate expected outcome" }); + if (!expectedIds.has(idOf(o))) failures.push({ kind: "error", detail: "unexpected outcome" }); + if ((counts.get(idOf(o)) ?? 0) > 1) failures.push({ kind: "error", detail: "duplicate outcome" }); if (o.error) failures.push({ kind: /timed out/.test(o.error) ? "timeout" : "error", detail: o.error }); if (o.degraded) failures.push({ kind: "degraded", detail: o.degraded }); if (o.results && !o.comparison && !o.error) failures.push({ kind: "golden", detail: "no golden recorded: run with --update-golden and review it" }); - for (const [metric, limit] of Object.entries(budgetsFor(budgets, o))) { + const limits = budgetsFor(budgets, o); + const required = new Set(["feedbackMs", "firstResultMs", "completeMs", ...Object.keys(limits)]); + if (o.results || o.comparison) { + required.add("recall"); + required.add("precision"); + } + for (const metric of new Set([...required, ...Object.keys(o.metrics)])) { + if (!Number.isFinite(o.metrics[metric])) + failures.push({ + kind: lowerBound(metric) ? "correctness" : "budget", + metric, + detail: `${metric} is missing or nonfinite`, + }); + } + for (const [metric, limit] of Object.entries(limits)) { const value = o.metrics[metric]; if (value === undefined || !Number.isFinite(value)) continue; const over = lowerBound(metric) ? value < limit : value > limit; diff --git a/evals/run.ts b/evals/run.ts index fa8b07d822..bbf424130e 100644 --- a/evals/run.ts +++ b/evals/run.ts @@ -25,6 +25,7 @@ import { compare, readGolden, toolDrift, writeGolden, type ResultSet } from "./l import { TimeoutError } from "./lib/measure.ts"; import { fingerprint, pinnedTools, sameMachine, toolVersions, type Fingerprint } from "./lib/machine.ts"; import type { EvalScenario } from "./lib/scenario.ts"; +import { planSelection } from "./lib/selection.ts"; import { Session } from "./lib/session.ts"; import { idOf, judge, loadBudgets, table, type Condition, type Diagnostics, type Outcome } from "./lib/verdict.ts"; @@ -56,12 +57,7 @@ if (args.list) { process.exit(0); } -const runs = Math.max(1, Number(args.runs)); -const warmup = Math.max(0, Number(args.warmup)); -const only = args.only?.split(",").map((s) => s.trim()); -const conditionFilter = args.condition as Condition | undefined; -const selected = SCENARIOS.filter((s) => !only || only.some((o) => s.id === o || s.id.startsWith(`${o}.`))); -if (only && !selected.length) throw new Error(`no scenario matches ${args.only} (see --list)`); +const { runs, warmup, selected, expected, condition: conditionFilter } = planSelection(SCENARIOS, args); const goldenFile = (id: string) => join(ROOT, "evals", id.slice(0, id.indexOf(".")), "golden", `${id}.json`); @@ -296,7 +292,7 @@ async function main() { else console.warn("warning: target/eval/baseline.json is from another machine or OS: not compared"); } const repro = (o: Outcome) => `pnpm eval --only ${o.scenario} --condition ${o.condition}`; - const verdicts = judge(outcomes, loadBudgets(join(ROOT, "evals", "budgets.json")), baseline, repro); + const verdicts = judge(outcomes, loadBudgets(join(ROOT, "evals", "budgets.json")), baseline, repro, expected); const meta = { date: new Date().toISOString(), @@ -313,17 +309,17 @@ async function main() { meta, pass: verdicts.every((v) => v.status === "pass"), verdicts: verdicts.map((v) => { - const o = outcomes.find((x) => idOf(x) === v.id)!; + const o = outcomes.find((x) => idOf(x) === v.id); return { ...v, - samples: o.samples, - results: o.results, - comparison: o.comparison, - drift: o.drift, - degraded: o.degraded, - error: o.error, + samples: o?.samples, + results: o?.results, + comparison: o?.comparison, + drift: o?.drift, + degraded: o?.degraded, + error: o?.error, // Diagnostics only where something needs a look. - diagnostics: v.status === "fail" || v.regressions.length ? o.diagnostics : undefined, + diagnostics: v.status === "fail" || v.regressions.length ? o?.diagnostics : undefined, }; }), }; @@ -345,9 +341,9 @@ async function main() { for (const v of failing) { console.log(`\n${v.id} FAILED (${v.repro})`); for (const f of v.failures) console.log(` ${f.kind}: ${f.detail}`); - const o = outcomes.find((x) => idOf(x) === v.id)!; - if (o.drift?.length) console.log(` golden recorded with other tools: ${o.drift.join(", ")}`); - const slow = [...(o.diagnostics?.calls ?? [])].sort((a, b) => b.ms - a.ms).slice(0, 5); + const o = outcomes.find((x) => idOf(x) === v.id); + if (o?.drift?.length) console.log(` golden recorded with other tools: ${o.drift.join(", ")}`); + const slow = [...(o?.diagnostics?.calls ?? [])].sort((a, b) => b.ms - a.ms).slice(0, 5); if (slow.length) console.log( ` slowest commands: ${slow.map((c) => `${c.cmd} ${Math.round(c.ms)} ms${c.pending ? " (no answer)" : c.ok ? "" : " (failed)"}`).join(", ")}`, diff --git a/perf/lib/options.test.ts b/perf/lib/options.test.ts new file mode 100644 index 0000000000..c068dde289 --- /dev/null +++ b/perf/lib/options.test.ts @@ -0,0 +1,47 @@ +import { spawnSync } from "node:child_process"; +import { resolve } from "node:path"; +import { describe, expect, it } from "vitest"; +import { countOption } from "./options.ts"; + +const root = resolve(import.meta.dirname, "../.."); + +describe("benchmark CLI validation", () => { + it.each([ + ["runs", "NaN"], + ["runs", "Infinity"], + ["runs", "0"], + ["runs", "1.5"], + ["warmup", "-1"], + ["warmup", "NaN"], + ["warmup", "0.5"], + ["cpu", "NaN"], + ["cpu", "Infinity"], + ["cpu", "0"], + ])("rejects --%s %s before selecting or launching workloads", (option, value) => { + const result = spawnSync( + process.execPath, + ["perf/run.ts", "--no-build", "--only", "__unknown__", `--${option}=${value}`], + { cwd: root, encoding: "utf8", timeout: 10_000 }, + ); + expect(result.status).toBe(1); + expect(result.stderr).toContain(`--${option} must be`); + expect(result.stdout).not.toContain("Building"); + }); + + it.each(["typing,__unknown__", "", "typing,"])("rejects invalid selection %j", (selection) => { + const result = spawnSync(process.execPath, ["perf/run.ts", "--no-build", "--only", selection], { + cwd: root, + encoding: "utf8", + timeout: 10_000, + }); + expect(result.status).toBe(1); + expect(result.stderr).toContain("unknown scenario(s)"); + }); + + it("accepts integral counts and zero warmup without silently clamping", () => { + expect(countOption("runs", "5", 1)).toBe(5); + expect(countOption("warmup", "0", 0)).toBe(0); + expect(() => countOption("warmup", "", 0)).toThrow(); + expect(() => countOption("runs", "9007199254740992", 1)).toThrow(); + }); +}); diff --git a/perf/lib/options.ts b/perf/lib/options.ts new file mode 100644 index 0000000000..e7355741d6 --- /dev/null +++ b/perf/lib/options.ts @@ -0,0 +1,8 @@ +/** CLI repetition counts must be validated before any build or process launch. */ +export function countOption(name: string, raw: string, minimum: 0 | 1): number { + const value = Number(raw); + if (!raw.trim() || !Number.isSafeInteger(value) || value < minimum) { + throw new Error(`--${name} must be an integer >= ${minimum}`); + } + return value; +} diff --git a/perf/lib/report.test.ts b/perf/lib/report.test.ts index c203b76628..5de47134c0 100644 --- a/perf/lib/report.test.ts +++ b/perf/lib/report.test.ts @@ -32,6 +32,7 @@ describe("evaluate", () => { it("fails metrics over budget and budgeted metrics that are missing", () => { const r = evaluate(results, { "typing.maxMs": 33, "typing.missedFramePct": 2, "other.x": 1 }, null, { enforceBudgets: true, + expected: ["typing"], }); expect(r.rows.find((x) => x.key === "typing.maxMs")?.verdict).toBe("over-budget"); expect(r.rows.find((x) => x.key === "typing.missedFramePct")?.verdict).toBe("error"); @@ -41,18 +42,57 @@ describe("evaluate", () => { }); it("reports but does not fail budgets when not enforced", () => { - const r = evaluate(results, { "typing.maxMs": 33 }, null, { enforceBudgets: false }); + const r = evaluate(results, { "typing.maxMs": 33 }, null, { enforceBudgets: false, expected: ["typing"] }); expect(r.rows.find((x) => x.key === "typing.maxMs")?.verdict).toBe("over-budget-info"); expect(r.failures).toBe(0); }); it("compares against the baseline with relative and absolute slack", () => { const baseline = [{ id: "typing", title: "", metrics: { p95Ms: 14, maxMs: 39.5, layoutsPerKey: 2 } }]; - const r = evaluate(results, {}, baseline, { enforceBudgets: true, tolerance: 0.2, floor: 1 }); + const r = evaluate(results, {}, baseline, { + enforceBudgets: true, + expected: ["typing"], + tolerance: 0.2, + floor: 1, + }); const verdict = (k: string) => r.rows.find((x) => x.key === k)?.verdict; expect(verdict("typing.p95Ms")).toBe("regressed"); // +28 %, +4 ms expect(verdict("typing.maxMs")).toBe("ok"); // within 20 % expect(verdict("typing.layoutsPerKey")).toBe("ok"); // +50 % but only +1 (floor) expect(r.regressions).toBe(1); }); + + it("fails when a declared scenario disappears from the results", () => { + const report = evaluate(results, { "scroll.jumpMs": 50 }, null, { + enforceBudgets: true, + expected: ["typing", "scroll"], + }); + expect(report.errors).toContainEqual({ id: "scroll", error: "missing scenario result" }); + expect(report.rows.find((r) => r.key === "scroll.jumpMs")?.verdict).toBe("error"); + expect(report.failures).toBeGreaterThan(0); + }); + + it("rejects duplicate and unexpected scenario results", () => { + const report = evaluate([...results, ...results, { id: "other", title: "", metrics: { ms: 1 } }], {}, null, { + enforceBudgets: true, + expected: ["typing"], + }); + expect(report.errors).toEqual([ + { id: "typing", error: "duplicate scenario result" }, + { id: "other", error: "unexpected scenario result" }, + ]); + }); + + it("rejects an empty workload instead of returning a passing report", () => { + expect(evaluate([], {}, null, { enforceBudgets: true, expected: [] }).failures).toBeGreaterThan(0); + }); + + it("fails nonfinite metrics even without an absolute budget", () => { + const report = evaluate([{ id: "typing", title: "", metrics: { ms: Infinity } }], {}, null, { + enforceBudgets: false, + expected: ["typing"], + }); + expect(report.rows[0]?.verdict).toBe("error"); + expect(report.failures).toBe(1); + }); }); diff --git a/perf/lib/report.ts b/perf/lib/report.ts index 2ae4c66f6f..97ba0ab0d2 100644 --- a/perf/lib/report.ts +++ b/perf/lib/report.ts @@ -52,7 +52,7 @@ export function evaluate( results: ScenarioResult[], budgets: Record, baseline: ScenarioResult[] | null, - opts: { enforceBudgets: boolean; tolerance?: number; floor?: number }, + opts: { expected: readonly string[]; enforceBudgets: boolean; tolerance?: number; floor?: number }, ): Report { const tol = opts.tolerance ?? 0.2; const floor = opts.floor ?? 1; @@ -62,7 +62,21 @@ export function evaluate( const rows: Row[] = []; const errors: Report["errors"] = []; const seen = new Set(); + const expected = new Set(opts.expected); + const produced = new Set(); + if (!expected.size) errors.push({ id: "run", error: "empty workload" }); + if (expected.size !== opts.expected.length) errors.push({ id: "run", error: "duplicate expected scenario" }); for (const r of results) { + if (!expected.has(r.id)) { + errors.push({ id: r.id, error: "unexpected scenario result" }); + continue; + } + if (produced.has(r.id)) { + errors.push({ id: r.id, error: "duplicate scenario result" }); + continue; + } + produced.add(r.id); + if (!r.error && !Object.keys(r.metrics).length) errors.push({ id: r.id, error: "no metrics produced" }); if (r.error) errors.push({ id: r.id, error: r.error }); for (const [m, value] of Object.entries(r.metrics)) { const key = `${r.id}.${m}`; @@ -70,7 +84,7 @@ export function evaluate( const budget = budgets[key]; const before = base.get(key); let verdict: Verdict = "ok"; - if (!Number.isFinite(value)) verdict = budget === undefined ? "ok" : "error"; + if (!Number.isFinite(value)) verdict = "error"; else if (budget !== undefined && value > budget) verdict = opts.enforceBudgets ? "over-budget" : "over-budget-info"; else if (before !== undefined && value > before * (1 + tol) && value - before > floor) verdict = "regressed"; @@ -78,10 +92,12 @@ export function evaluate( rows.push({ key, value, budget, baseline: before, verdict }); } } - // A budgeted metric that was not produced (scenario failed or renamed) fails too. - const ran = new Set(results.map((r) => r.id)); + for (const id of expected) { + if (!produced.has(id)) errors.push({ id, error: "missing scenario result" }); + } + // Required metrics are scoped by the declared workload, never by returned data. for (const key of Object.keys(budgets)) { - if (!seen.has(key) && ran.has(key.slice(0, key.indexOf(".")))) { + if (!seen.has(key) && expected.has(key.slice(0, key.indexOf(".")))) { rows.push({ key, value: NaN, budget: budgets[key], verdict: "error" }); } } diff --git a/perf/lib/rust.test.ts b/perf/lib/rust.test.ts new file mode 100644 index 0000000000..19510db7f6 --- /dev/null +++ b/perf/lib/rust.test.ts @@ -0,0 +1,175 @@ +import { spawnSync } from "node:child_process"; +import { existsSync, mkdtempSync, mkdirSync, readFileSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { collectRustMetrics, RUST_BENCHMARKS, rustBudgets, rustPaths, selectRustPackages } from "./rust.ts"; + +const roots: string[] = []; +function fixture() { + const root = mkdtempSync(join(tmpdir(), "rust-validity-")); + roots.push(root); + return root; +} +function artifact(root: string, id: string, value: unknown = 1000, directory = id) { + const dir = join(root, directory, "new"); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "benchmark.json"), JSON.stringify({ full_id: id })); + writeFileSync(join(dir, "estimates.json"), JSON.stringify({ mean: { point_estimate: value } })); + return dir; +} +function complete(root: string, packages: readonly string[]) { + for (const p of packages) for (const id of RUST_BENCHMARKS[p]!) artifact(root, id); +} +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe("Rust workload contract", () => { + it("owns 40 unique IDs and exactly six observe-only metrics", () => { + const ids = Object.values(RUST_BENCHMARKS).flat(); + expect(ids).toHaveLength(40); + expect(new Set(ids).size).toBe(40); + const budgets = JSON.parse(readFileSync(resolve(import.meta.dirname, "../budgets.json"), "utf8")).rust; + const selected = rustBudgets(selectRustPackages(), budgets); + expect(Object.keys(selected)).toHaveLength(34); + expect(ids.filter((id) => !(id in budgets))).toEqual([ + "syntax_2mb/outline_uncached", + "syntax_2mb/folding_uncached", + "index_100k/find_files/zzzz", + "index_100k/find_symbols/renderView", + "startup_20k/reopen_wait_idle", + "search_excluded_subtrees/5k_dependencies", + ]); + expect(Object.keys(rustBudgets(["ide-text"], budgets))).toHaveLength(9); + const missing = { ...budgets }; + delete missing["text/open_1mb"]; + expect(() => rustBudgets(["ide-text"], missing)).toThrow(/classification/); + expect(() => rustBudgets(["ide-text"], { ...budgets, "text/new": 1 })).toThrow(/unknown/); + expect(() => rustBudgets(["ide-text"], { ...budgets, "syntax_2mb/outline_uncached": 1 })).toThrow(/observe-only/); + }); + + it("rejects unknown or empty packages and deduplicates before cargo", () => { + expect(() => selectRustPackages([])).toThrow(/empty/); + expect(() => selectRustPackages([""])).toThrow(/unknown/); + expect(() => selectRustPackages(["not-a-crate"])).toThrow(/unknown/); + expect(selectRustPackages(["ide-text", "ide-text"])).toEqual(["ide-text"]); + }); + + it("rejects unknown CLI packages without invoking cargo", () => { + const root = fixture(); + const marker = join(root, "cargo-invoked"); + writeFileSync(join(root, "cargo"), `#!/bin/sh\n: > '${marker}'\nexit 99\n`, { mode: 0o755 }); + const result = spawnSync( + process.execPath, + [resolve(import.meta.dirname, "../rust.ts"), "--package", "not-a-crate"], + { + env: { ...process.env, PATH: root, CARGO_TARGET_DIR: join(root, "target") }, + encoding: "utf8", + }, + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toMatch(/unknown Rust package/); + expect(existsSync(marker)).toBe(false); + }); + + it("resolves target and Criterion overrides relative to cargo's cwd", () => { + expect(rustPaths("/work", {})).toEqual({ target: "/work/target", criterion: "/work/target/criterion" }); + expect(rustPaths("/work", { CARGO_TARGET_DIR: "private" })).toEqual({ + target: "/work/private", + criterion: "/work/private/criterion", + }); + expect(rustPaths("/work", { CARGO_TARGET_DIR: "/private", CRITERION_HOME: "results" })).toEqual({ + target: "/private", + criterion: "/work/results", + }); + }); + + it("accepts a complete full workload and converts nanoseconds to microseconds", () => { + const root = fixture(); + complete(root, selectRustPackages()); + expect(Object.keys(collectRustMetrics(root, selectRustPackages()))).toHaveLength(40); + expect(collectRustMetrics(root, ["ide-text"])["text/open_1mb"]).toBe(1); + }); + + it("requires selected IDs independently of budgets, including observe-only IDs", () => { + const root = fixture(); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/missing/); + complete(root, ["ide-language"]); + rmSync(join(root, "syntax_2mb/outline_uncached"), { recursive: true }); + expect(() => collectRustMetrics(root, ["ide-language"])).toThrow(/outline_uncached/); + expect(() => collectRustMetrics(root, selectRustPackages())).toThrow(/missing/); + }); + + it.each([ + ["ide-language", "syntax_2mb/outline_uncached"], + ["ide-language", "syntax_2mb/folding_uncached"], + ["ide-index", "index_100k/find_files/zzzz"], + ["ide-index", "index_100k/find_symbols/renderView"], + ["ide-index", "startup_20k/reopen_wait_idle"], + ["ide-search", "search_excluded_subtrees/5k_dependencies"], + ])("requires observe-only metric %s / %s", (p, id) => { + const root = fixture(); + complete(root, [p]); + rmSync(join(root, id), { recursive: true }); + expect(() => collectRustMetrics(root, [p])).toThrow(/missing selected/); + }); + + it("ignores known unselected artifacts, including their malformed estimates", () => { + const root = fixture(); + complete(root, ["ide-text"]); + artifact(root, "heap/index_1m_objects", "bad"); + const unrelated = artifact(root, "heap/dominators_1m_random"); + writeFileSync(join(unrelated, "benchmark.json"), "{"); + expect(Object.keys(collectRustMetrics(root, ["ide-text"]))).toHaveLength(RUST_BENCHMARKS["ide-text"].length); + }); + + it("rejects duplicate IDs and unknown selected IDs even with complete expected results", () => { + const root = fixture(); + complete(root, ["ide-text"]); + artifact(root, "text/open_1mb", 1000, "duplicate"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/duplicate/); + rmSync(join(root, "duplicate"), { recursive: true }); + artifact(root, "text/renamed"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/unknown/); + }); + + it.each([null, "1000", -1, {}])("rejects invalid means: %j", (value) => { + const root = fixture(); + complete(root, ["ide-text"]); + artifact(root, "text/open_1mb", value); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/estimate/); + }); + + it("accepts zero and rejects malformed metadata, absent estimates, and invalid JSON", () => { + const root = fixture(); + complete(root, ["ide-text"]); + const dir = artifact(root, "text/open_1mb", 0); + expect(collectRustMetrics(root, ["ide-text"])["text/open_1mb"]).toBe(0); + writeFileSync(join(dir, "benchmark.json"), "{}"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/full_id/); + artifact(root, "text/open_1mb"); + rmSync(join(dir, "estimates.json")); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(); + writeFileSync(join(dir, "estimates.json"), "{"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(); + writeFileSync(join(dir, "estimates.json"), "{}"); + expect(() => collectRustMetrics(root, ["ide-text"])).toThrow(/estimate/); + }); + + it.each(["benchmark.json", "estimates.json"])("requires fresh %s for a newly run workload", (file) => { + const root = fixture(); + complete(root, ["ide-text"]); + const dir = artifact(root, "text/open_1mb"); + utimesSync(join(dir, file), new Date(0), new Date(0)); + expect(() => collectRustMetrics(root, ["ide-text"], 1)).toThrow(/stale/); + expect(Object.keys(collectRustMetrics(root, ["ide-text"]))).toHaveLength(RUST_BENCHMARKS["ide-text"].length); + }); + it("rejects overflowing JSON numeric estimates, including observe-only metrics", () => { + const root = fixture(); + complete(root, ["ide-language"]); + const dir = artifact(root, "syntax_2mb/outline_uncached"); + writeFileSync(join(dir, "estimates.json"), '{"mean":{"point_estimate":1e309}}'); + expect(() => collectRustMetrics(root, ["ide-language"])).toThrow(/estimate/); + }); +}); diff --git a/perf/lib/rust.ts b/perf/lib/rust.ts new file mode 100644 index 0000000000..3c9864e00b --- /dev/null +++ b/perf/lib/rust.ts @@ -0,0 +1,157 @@ +import { existsSync, readdirSync, readFileSync, statSync } from "node:fs"; +import { join, relative, resolve, sep } from "node:path"; + +// Package-owned expectations, independent of collected artifacts and human-owned budgets. +export const RUST_BENCHMARKS: Readonly> = { + "ide-text": [ + "text/open_1mb", + "text/apply_keystroke_1mb", + "text/apply_100_changes_1mb", + "text/diff_two_edits_1mb", + "text/diff_every_line_1mb", + "text/offset_to_pos_round_trip", + "text/pos_to_byte", + "text/text_for_save_crlf_1mb", + "text/diff_one_edit_5mb", + ], + "ide-language": [ + "syntax_2mb/outline_uncached", + "syntax_2mb/folding_uncached", + "syntax_2mb/outline_cached_hit", + "syntax_2mb/folding_cached_hit", + "syntax_2mb/selection_cached_hit", + "syntax_2mb/folding_after_keystroke_incremental", + "syntax_2mb/outline_after_keystroke_incremental", + ], + "ide-index": [ + "index_100k/find_files/ordcon", + "index_100k/find_files/src/user", + "index_100k/find_files/PaymentService", + "index_100k/find_files/zzzz", + "index_100k/find_files/a", + "index_100k/find_dirs/util", + "index_100k/find_dirs/src/ui", + "index_100k/find_dirs/a", + "index_100k/find_symbols/OCo", + "index_100k/find_symbols/invoiceRepo", + "index_100k/find_symbols/renderView", + "index_100k/find_symbols/q", + "index_100k/find_symbols_types/UsSe", + "startup_20k/reopen_wait_idle", + ], + "ide-search": [ + "search_5k/literal", + "search_5k/regex", + "search_5k/dense_limit", + "search_dense_files/24x40k_limit", + "search_excluded_subtrees/5k_dependencies", + ], + "ide-host": ["plugins/load_50", "plugins/cold_activation", "plugins/syntax_highlights_2k_lines"], + "ide-heap": ["heap/index_1m_objects", "heap/dominators_1m_random"], +}; + +const OBSERVE_ONLY: Readonly> = { + "syntax_2mb/outline_uncached": true, + "syntax_2mb/folding_uncached": true, + "index_100k/find_files/zzzz": true, + "index_100k/find_symbols/renderView": true, + "startup_20k/reopen_wait_idle": true, + "search_excluded_subtrees/5k_dependencies": true, +}; + +export function selectRustPackages(packages: readonly string[] = Object.keys(RUST_BENCHMARKS)): string[] { + if (packages.length === 0) throw new Error("empty Rust package selection"); + for (const p of packages) { + if (!Object.hasOwn(RUST_BENCHMARKS, p)) throw new Error(`unknown Rust package: ${JSON.stringify(p)}`); + } + return [...new Set(packages)]; +} + +export function rustPaths(root: string, env: { CARGO_TARGET_DIR?: string; CRITERION_HOME?: string }) { + const target = resolve(root, env.CARGO_TARGET_DIR ?? "target"); + return { target, criterion: resolve(root, env.CRITERION_HOME ?? join(target, "criterion")) }; +} + +export function rustBudgets(packages: readonly string[], budgets: Record): Record { + const selected = selectRustPackages(packages); + const ids = new Set(Object.values(RUST_BENCHMARKS).flat()); + for (const id of Object.keys(OBSERVE_ONLY)) { + if (!ids.has(id)) throw new Error(`unknown Rust observe-only classification: ${id}`); + } + for (const [id, value] of Object.entries(budgets)) { + if (!ids.has(id)) throw new Error(`unknown Rust budget ID: ${id}`); + if (Object.hasOwn(OBSERVE_ONLY, id)) throw new Error(`Rust observe-only ID has an absolute budget: ${id}`); + if (!Number.isFinite(value) || value < 0) throw new Error(`invalid Rust budget: ${id}`); + } + for (const id of ids) { + if (!Object.hasOwn(budgets, id) && !Object.hasOwn(OBSERVE_ONLY, id)) { + throw new Error(`missing Rust budget classification: ${id}`); + } + } + return Object.fromEntries( + selected + .flatMap((p) => RUST_BENCHMARKS[p]!) + .filter((id) => !Object.hasOwn(OBSERVE_ONLY, id)) + .map((id) => [`rust.${id}`, budgets[id]!]), + ); +} + +/** Read the selected workload only; fresh runs require both artifact files since `started`. */ +export function collectRustMetrics(dir: string, packages: readonly string[], started?: number): Record { + const selected = new Set(selectRustPackages(packages)); + const expected = new Set([...selected].flatMap((p) => RUST_BENCHMARKS[p]!)); + const owners = new Map(); + const groups = new Map(); + for (const [p, ids] of Object.entries(RUST_BENCHMARKS)) { + for (const id of ids) { + owners.set(id, p); + groups.set(id.split("/")[0]!, p); + } + } + const metrics: Record = {}; + function readNew(sub: string) { + // Criterion sanitizes slashes in ungrouped function names to underscores. + const top = relative(dir, sub).split(sep)[0]!; + const pathOwner = [...groups].find(([group]) => top === group || top.startsWith(`${group}_`))?.[1]; + if (pathOwner && !selected.has(pathOwner)) return; + const bench = join(sub, "new", "benchmark.json"); + const estimates = join(sub, "new", "estimates.json"); + if (!existsSync(bench)) { + if (existsSync(estimates) && (!pathOwner || selected.has(pathOwner))) { + throw new Error(`missing Criterion benchmark.json: ${sub}`); + } + return; + } + const metadata: unknown = JSON.parse(readFileSync(bench, "utf8")); + const id = metadata && typeof metadata === "object" && "full_id" in metadata ? metadata.full_id : undefined; + if (typeof id !== "string" || !id) { + throw new Error(`invalid Criterion full_id: ${bench}`); + } + const owner = owners.get(id) ?? groups.get(id.split("/")[0]!); + if (owner && !selected.has(owner)) return; + if (!expected.has(id)) throw new Error(`unknown selected Criterion ID: ${id}`); + if (Object.hasOwn(metrics, id)) throw new Error(`duplicate Criterion ID: ${id}`); + for (const file of [bench, estimates]) { + if (started !== undefined && statSync(file).mtimeMs < started) + throw new Error(`stale Criterion artifact: ${file}`); + } + const est: unknown = JSON.parse(readFileSync(estimates, "utf8")); + const mean = est && typeof est === "object" && "mean" in est ? est.mean : undefined; + const value = mean && typeof mean === "object" && "point_estimate" in mean ? mean.point_estimate : undefined; + if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { + throw new Error(`invalid Criterion mean estimate: ${estimates}`); + } + metrics[id] = value / 1000; + } + function visit(path: string) { + if (!existsSync(path)) return; + readNew(path); + for (const entry of readdirSync(path, { withFileTypes: true })) { + if (entry.isDirectory() && !["new", "base", "report"].includes(entry.name)) visit(join(path, entry.name)); + } + } + visit(dir); + const missing = [...expected].filter((id) => !Object.hasOwn(metrics, id)); + if (missing.length) throw new Error(`missing selected Criterion IDs: ${missing.join(", ")}`); + return metrics; +} diff --git a/perf/run.ts b/perf/run.ts index 2554b0f0cd..c59197b04f 100644 --- a/perf/run.ts +++ b/perf/run.ts @@ -20,6 +20,7 @@ import { buildBundle, serveBundle } from "./lib/bundle.ts"; import { Harness, type Metrics, type Scenario } from "./lib/harness.ts"; import { topFunctions, type CpuProfile } from "./lib/profile.ts"; import { installInPage } from "./lib/inpage.ts"; +import { countOption } from "./lib/options.ts"; import { evaluate, loadBudgets, printReport, type ScenarioResult } from "./lib/report.ts"; import { median } from "./lib/stats.ts"; import { SCENARIOS } from "./scenarios.ts"; @@ -51,17 +52,28 @@ if (args.list) { process.exit(0); } -const runs = Math.max(1, Number(args.runs)); -const warmup = Math.max(0, Number(args.warmup)); -const cpu = Math.max(1, Number(args.cpu)); +const runs = countOption("runs", args.runs!, 1); +const warmup = countOption("warmup", args.warmup!, 0); +const cpu = Number(args.cpu); +if (!args.cpu?.trim() || !Number.isFinite(cpu) || cpu < 1) { + throw new Error("--cpu must be a finite number >= 1"); +} // Unminified builds keep function names readable in profiles; their bundle size is meaningless. const DIST = join(OUT, args.unminified ? "dist-unminified" : "dist"); -const only = args.only?.split(",").map((s) => s.trim()); -const scenarios = only ? SCENARIOS.filter((s) => only.includes(s.id)) : SCENARIOS; -if (only && scenarios.length !== only.length) { - const known = new Set(SCENARIOS.map((s) => s.id)); - throw new Error(`unknown scenario(s): ${only.filter((o) => !known.has(o)).join(", ")} (see --list)`); +const only = args.only === undefined ? undefined : [...new Set(args.only.split(",").map((s) => s.trim()))]; +const known = new Set(SCENARIOS.map((s) => s.id)); +if (known.size !== SCENARIOS.length) throw new Error("duplicate scenario ID"); +if (only?.some((id) => !known.has(id))) { + throw new Error(`unknown scenario(s): ${only.filter((id) => !known.has(id)).join(", ")} (see --list)`); } +const scenarios = only ? SCENARIOS.filter((s) => only.includes(s.id)) : SCENARIOS; +if (!scenarios.length) throw new Error("empty workload"); +const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); +for (const key of Object.keys(budgets.ui)) { + const id = key.slice(0, key.indexOf(".")); + if (id !== "bundle" && !known.has(id)) throw new Error(`budget references unknown scenario: ${key}`); +} +const expected = [...(args.unminified ? [] : ["bundle"]), ...scenarios.map((s) => s.id)]; function build() { buildBundle(ROOT, DIST, args.unminified ? ["--minify", "false"] : []); @@ -188,8 +200,9 @@ async function main() { const baseline = existsSync(baselineFile) ? (JSON.parse(readFileSync(baselineFile, "utf8")) as ScenarioResult[]) : null; - const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); + // Expectations were fixed before launch, independently of returned measurements. const report = evaluate(results, budgets.ui, baseline, { + expected, enforceBudgets: cpu === 1, tolerance: budgets.regressionTolerance, floor: budgets.regressionFloor, diff --git a/perf/rust.ts b/perf/rust.ts index a0de179a83..c34744bc94 100644 --- a/perf/rust.ts +++ b/perf/rust.ts @@ -8,15 +8,15 @@ * pnpm perf:rust -- --package ide-text --save-baseline */ import { spawnSync } from "node:child_process"; -import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join, resolve } from "node:path"; import { parseArgs } from "node:util"; import { evaluate, loadBudgets, printReport, type ScenarioResult } from "./lib/report.ts"; +import { collectRustMetrics, rustBudgets, rustPaths, selectRustPackages } from "./lib/rust.ts"; const ROOT = resolve(import.meta.dirname, ".."); -const TARGET = resolve(ROOT, process.env.CARGO_TARGET_DIR ?? "target"); +const { target: TARGET, criterion: CRITERION } = rustPaths(ROOT, process.env); const OUT = join(ROOT, "target", "perf"); -const PACKAGES = ["ide-text", "ide-language", "ide-index", "ide-search", "ide-host", "ide-heap"]; const { values: args } = parseArgs({ options: { @@ -27,50 +27,27 @@ const { values: args } = parseArgs({ }, }); -const packages = args.package ?? PACKAGES; +const packages = selectRustPackages(args.package); +const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); +const selectedBudgets = rustBudgets(packages, budgets.rust); const started = Date.now(); if (!args["no-run"]) { const r = spawnSync("cargo", ["bench", ...packages.flatMap((p) => ["-p", p]), "--benches"], { cwd: ROOT, stdio: "inherit", + env: { ...process.env, CARGO_TARGET_DIR: TARGET, CRITERION_HOME: CRITERION }, }); if (r.status !== 0) throw new Error("cargo bench failed"); } -/** Criterion results (`/new/{benchmark,estimates}.json`) → mean in µs. */ -function collect(dir: string, out: Record) { - if (!existsSync(dir)) return; - for (const entry of readdirSync(dir, { withFileTypes: true })) { - if (!entry.isDirectory() || entry.name === "report") continue; - const sub = join(dir, entry.name); - const bench = join(sub, "new", "benchmark.json"); - if (existsSync(bench) && (args["no-run"] || statSync(bench).mtimeMs >= started)) { - const { full_id } = JSON.parse(readFileSync(bench, "utf8")) as { full_id: string }; - const est = JSON.parse(readFileSync(join(sub, "new", "estimates.json"), "utf8")) as { - mean: { point_estimate: number }; - }; - out[full_id] = est.mean.point_estimate / 1000; - } - collect(sub, out); - } -} - -const metrics: Record = {}; -collect(join(TARGET, "criterion"), metrics); -if (Object.keys(metrics).length === 0) throw new Error(`no criterion results under ${join(TARGET, "criterion")}`); +const metrics = collectRustMetrics(CRITERION, packages, args["no-run"] ? undefined : started); mkdirSync(OUT, { recursive: true }); -const budgets = loadBudgets(join(ROOT, "perf", "budgets.json")); const results: ScenarioResult[] = [{ id: "rust", title: "criterion means (µs)", metrics }]; const baselineFile = join(OUT, "baseline-rust.json"); const baseline = existsSync(baselineFile) ? (JSON.parse(readFileSync(baselineFile, "utf8")) as ScenarioResult[]) : null; -// Only budgets of benches that ran: `--package` may select a subset. -const rustBudgets = Object.fromEntries( - Object.entries(budgets.rust) - .filter(([id]) => args["no-run"] || id in metrics || !args.package) - .map(([id, v]) => [`rust.${id}`, v]), -); -const report = evaluate(results, rustBudgets, baseline, { +const report = evaluate(results, selectedBudgets, baseline, { + expected: ["rust"], enforceBudgets: true, tolerance: budgets.regressionTolerance, floor: budgets.regressionFloor, From 34cb4ad5e0ec2d6211068d880cd00718be1a1649 Mon Sep 17 00:00:00 2001 From: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> Date: Thu, 19 Nov 2026 13:38:34 +0200 Subject: [PATCH 11/16] fix(bench): preserve failed trials and bound cleanup (#4489) Failed warmups and repetitions were dropped from benchmark summaries, a failed startup, build or cleanup could leave an earlier success report in place, and a hung renderer or child process could block a run. Every attempt now keeps its status, metrics and error so summaries have the complete denominator; failures replace stale reports; browser and child-process lifecycles are bounded with cleanup of owned resources; and each criterion execution gets its own artifact directory. Co-authored-by: Mr0Bread <55754540+Mr0Bread@users.noreply.github.com> --- docs/en/contribute/testing/perf.mdx | 12 + docs/zh/contribute/testing/perf.mdx | 12 + evals/lib/machine.ts | 12 +- evals/lib/measure.ts | 4 +- evals/lib/measureDeadline.test.ts | 26 ++ evals/lib/session.ts | 96 +++-- evals/run.ts | 247 ++++++++---- perf/compare/README.md | 46 ++- perf/compare/bench.py | 587 +++++++++++++++++++--------- perf/compare/test_bench.py | 211 ++++++++++ perf/lib/bundle.ts | 22 +- perf/lib/lifecycle.test.ts | 42 ++ perf/lib/lifecycle.ts | 59 +++ perf/lib/process.ts | 106 +++++ perf/lib/runnerFailure.test.ts | 58 +++ perf/lib/rust.test.ts | 55 ++- perf/lib/rust.ts | 55 ++- perf/lib/rustRun.test.ts | 234 +++++++++++ perf/lib/rustRun.ts | 253 ++++++++++++ perf/lib/trials.test.ts | 54 +++ perf/lib/trials.ts | 57 +++ perf/run.ts | 191 ++++++--- perf/rust.ts | 49 +-- smoke/fixtures/server.cjs | 5 + smoke/server.test.ts | 21 + smoke/server.ts | 47 ++- 26 files changed, 2122 insertions(+), 439 deletions(-) create mode 100644 evals/lib/measureDeadline.test.ts create mode 100644 perf/compare/test_bench.py create mode 100644 perf/lib/lifecycle.test.ts create mode 100644 perf/lib/lifecycle.ts create mode 100644 perf/lib/process.ts create mode 100644 perf/lib/runnerFailure.test.ts create mode 100644 perf/lib/rustRun.test.ts create mode 100644 perf/lib/rustRun.ts create mode 100644 perf/lib/trials.test.ts create mode 100644 perf/lib/trials.ts diff --git a/docs/en/contribute/testing/perf.mdx b/docs/en/contribute/testing/perf.mdx index b5c8351b98..5d1c94acb3 100644 --- a/docs/en/contribute/testing/perf.mdx +++ b/docs/en/contribute/testing/perf.mdx @@ -31,6 +31,10 @@ Other options: `--warmup ` (default 1), `--headed`, `--no-build` (reuse the l `--runs` must be a positive integer, `--warmup` a nonnegative integer, and `--cpu` a finite number of at least 1. Empty or unknown `--only` entries fail before building or launching a browser. Every declared selected scenario must return exactly one result; missing budgeted metrics and nonfinite metrics fail even when CPU throttling disables timing-budget enforcement. Unminified profiling builds intentionally omit bundle-size checks. +Every attempted repetition, including warmups, is retained in `target/perf/report.json` with status, metrics and failure reason. Markdown shows valid/planned and attempted counts. Missing or nonfinite repetitions are not filtered out of medians; invalid warmups also fail the scenario. Build, browser and cleanup failures replace the previous report with a fresh failure. + +UI builds and individual trials have five-minute wall-clock deadlines independent of renderer animation frames. Browser startup is bounded to 30 seconds; context/HTTP cleanup to five seconds, with bounded forced browser termination. The owned Playwright browser server adds a local WebSocket command hop; in-page timing clocks are unchanged. + Scenarios (`perf/scenarios.ts`): `typing`, `typingLarge`, `typingAngular`, `completion`, `consoleOutput`, `terminalTui`, `keyRepeat`, `scroll`, `gitLog`, `gitLogScrollbar`, `resizePanels`, `startup`, `tabs`, `agentTabs`, `popups`, `toolWindows`, `projectTree`, `leaks`. Bundle size (`bundle.initialJsKb`, `bundle.initialCssKb`) is checked except with `--unminified`. Latencies are measured from input to the start of the first frame that shows the result, so about 16.7 ms means "next frame". @@ -68,12 +72,18 @@ Expected IDs and package ownership are declared independently of collected artif Six IDs are observe-only (required finite measurements, without an absolute budget): `syntax_2mb/outline_uncached`, `syntax_2mb/folding_uncached`, `index_100k/find_files/zzzz`, `index_100k/find_symbols/renderView`, `startup_20k/reopen_wait_idle`, and `search_excluded_subtrees/5k_dependencies`. New IDs need an explicit budget or observe-only classification. +Normal runs write isolated `/runs/run-*/criterion` artifacts, a `run.json` manifest and Cargo logs. `CRITERION_HOME` and `CARGO_TARGET_DIR` are passed consistently to Cargo. Both artifact files must fall within the recorded run window; future timestamps fail. `--no-run` inspects the newest recorded run covering the selected packages, retaining original artifact dates and any recorded failure; pre-manifest output is explicitly labelled legacy inspection, not current execution. + +Cargo has a 60-minute deadline including cold compilation (`PERF_RUST_TIMEOUT_MS` overrides milliseconds), followed by bounded process-tree termination. Cargo, artifact and manifest failures write fresh `report-rust.json` and Markdown with partial evidence. + ## Code intelligence: `pnpm eval` Use `pnpm eval --list` for scenario IDs and supported conditions. `--only` accepts comma-separated IDs or dot-prefix groups; every entry must match executable work. `--condition` accepts only `warm` or `cold`, and a selection incompatible with that condition is rejected before building or launching. Repetition counts follow the UI runner's integer requirements. The selected scenario/condition plan defines the required outcomes independently of collected results. Missing, duplicate or unexpected outcomes fail; an empty workload cannot pass. Required timing and correctness metrics must be present and finite, rather than silently skipped by the judge. +Raw attempts, warmups, results and partial timeout timings remain in `target/eval/report.json`; invalid trials cannot disappear into an otherwise valid median. Startup/build failures also produce a fresh failing report. Session startup, fixture setup and each trial have five-minute wall-clock bounds; renderer measurements additionally have a Node deadline one second beyond their configured timeout. Server initialization is limited to 30 seconds, individual stdio requests to five minutes, release compilation to 60 minutes. Cleanup errors fail the run. + ## Budgets and baselines [`perf/budgets.json`](https://github.com/l0ng-ai/openidea/blob/main/perf/budgets.json) holds upper bounds (lower is better): @@ -104,4 +114,6 @@ python perf/compare/bench.py ~/src/some-project --runs 5 --wipe-caches # cold Each run launches the app on the project, waits until it is ready (the process tree's CPU stays low after the window and the log markers appear), idles, closes it, and records time to window and to ready, peak and idle memory summed over every process the app started (webview, language servers, JVMs), CPU time, exit time and cache size. Apps run interleaved after warmup runs; output goes to `results/